Skip to content

Commit 9ab6789

Browse files
committed
bitcoin: fix out-by-one-error in bitcoin_tx_input_weight.
We need one byte for the number of witness elements. Some callers added it themselves, but it's always needed. So document and fix the callers. Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
1 parent 5dac1bc commit 9ab6789

File tree

3 files changed

+9
-6
lines changed

3 files changed

+9
-6
lines changed

bitcoin/tx.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -893,7 +893,8 @@ size_t bitcoin_tx_input_sig_weight(void)
893893
/* Input weight */
894894
size_t bitcoin_tx_input_weight(bool p2sh, size_t witness_weight)
895895
{
896-
size_t weight = witness_weight;
896+
/* We assume < 253 witness elements */
897+
size_t weight = 1 + witness_weight;
897898

898899
/* Input weight: txid + index + sequence */
899900
weight += (32 + 4 + 4) * 4;
@@ -914,8 +915,8 @@ size_t bitcoin_tx_input_weight(bool p2sh, size_t witness_weight)
914915

915916
size_t bitcoin_tx_simple_input_witness_weight(void)
916917
{
917-
/* Account for witness (1 byte count + sig + key) */
918-
return 1 + (bitcoin_tx_input_sig_weight() + 1 + 33);
918+
/* Account for witness (sig + key) */
919+
return bitcoin_tx_input_sig_weight() + 1 + 33;
919920
}
920921

921922
/* We only do segwit inputs, and we assume witness is sig + key */

bitcoin/tx.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -315,7 +315,9 @@ size_t bitcoin_tx_output_weight(size_t outscript_len);
315315
/* Weight to push sig on stack. */
316316
size_t bitcoin_tx_input_sig_weight(void);
317317

318-
/* Segwit input, but with parameter for witness weight (size) */
318+
/* Segwit input, but with parameter for witness weight (size).
319+
* witness_weight must include the varint_size() for each witness element,
320+
* but not the varint_size() for the number of elements. */
319321
size_t bitcoin_tx_input_weight(bool p2sh, size_t witness_weight);
320322

321323
/* The witness weight for a simple (sig + key) input */

onchaind/onchaind.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -186,9 +186,9 @@ static void trim_maximum_feerate(struct amount_sat funding,
186186
* * `txin[0]` script bytes: 0
187187
* * `txin[0]` witness: `0 <signature_for_pubkey1> <signature_for_pubkey2>`
188188
*/
189-
/* Account for witness (1 byte count + 1 empty + sig + sig) */
189+
/* Account for witness (1 empty + sig + sig) */
190190
assert(tal_count(commitment->inputs) == 1);
191-
weight += bitcoin_tx_input_weight(false, 1 + 1 + 2 * bitcoin_tx_input_sig_weight());
191+
weight += bitcoin_tx_input_weight(false, 1 + 2 * bitcoin_tx_input_sig_weight());
192192

193193
for (size_t i = 0; i < tal_count(commitment->outputs); i++) {
194194
struct amount_asset amt;

0 commit comments

Comments
 (0)