From 59f174996765bf127f1c5ed96d3b77e95f21e19c Mon Sep 17 00:00:00 2001 From: Rusty Russell Date: Wed, 12 Jan 2022 13:41:58 +1030 Subject: [PATCH] bitcoin: fix tx weight calculation when there are no witnesses, but will be. We had an out-by-two error when calculating weights, because we grab weights on unsigned txs. Signed-off-by: Rusty Russell --- bitcoin/tx.c | 13 ++++++++++++- bitcoin/tx.h | 2 +- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/bitcoin/tx.c b/bitcoin/tx.c index 318a2ec94..76d47b173 100644 --- a/bitcoin/tx.c +++ b/bitcoin/tx.c @@ -457,7 +457,18 @@ size_t wally_tx_weight(const struct wally_tx *wtx) size_t bitcoin_tx_weight(const struct bitcoin_tx *tx) { - return wally_tx_weight(tx->wtx); + size_t extra; + size_t num_witnesses; + + /* If we don't have witnesses *yet*, libwally doesn't encode + * in BIP 141 style, omitting the flag and marker bytes */ + wally_tx_get_witness_count(tx->wtx, &num_witnesses); + if (num_witnesses == 0) + extra = 2; + else + extra = 0; + + return extra + wally_tx_weight(tx->wtx); } void wally_txid(const struct wally_tx *wtx, struct bitcoin_txid *txid) diff --git a/bitcoin/tx.h b/bitcoin/tx.h index 85bb38444..5bccaf7b6 100644 --- a/bitcoin/tx.h +++ b/bitcoin/tx.h @@ -57,7 +57,7 @@ void wally_txid(const struct wally_tx *wtx, struct bitcoin_txid *txid); u8 *linearize_tx(const tal_t *ctx, const struct bitcoin_tx *tx); u8 *linearize_wtx(const tal_t *ctx, const struct wally_tx *wtx); -/* Get weight of tx in Sipa. */ +/* Get weight of tx in Sipa; assumes it will have witnesses! */ size_t bitcoin_tx_weight(const struct bitcoin_tx *tx); size_t wally_tx_weight(const struct wally_tx *wtx);