From ae919061e2b341ae74c90f0133ba392e835cb4e1 Mon Sep 17 00:00:00 2001 From: Daniela Brozzoni Date: Tue, 12 Jul 2022 15:51:27 +0200 Subject: [PATCH] Take into account the segwit tx header when... ...selecting coins We take into account the larger segwit tx header for every transaction, not just the segwit ones. The reason for this is that we prefer to overestimate the fees for the transaction than underestimating them - the former might create txs with a slightly higher feerate than the requested one, while the latter might create txs with a slightly lower one - or worse, invalid (<1 sat/vbyte)! --- src/wallet/mod.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/wallet/mod.rs b/src/wallet/mod.rs index dccc427d..a56fdadf 100644 --- a/src/wallet/mod.rs +++ b/src/wallet/mod.rs @@ -759,6 +759,17 @@ where fee_amount += fee_rate.fee_wu(tx.weight()); + // Segwit transactions' header is 2WU larger than legacy txs' header, + // as they contain a witness marker (1WU) and a witness flag (1WU) (see BIP144). + // At this point we really don't know if the resulting transaction will be segwit + // or legacy, so we just add this 2WU to the fee_amount - overshooting the fee amount + // is better than undershooting it. + // If we pass a fee_amount that is slightly higher than the final fee_amount, we + // end up with a transaction with a slightly higher fee rate than the requested one. + // If, instead, we undershoot, we may end up with a feerate lower than the requested one + // - we might come up with non broadcastable txs! + fee_amount += fee_rate.fee_wu(2); + if params.change_policy != tx_builder::ChangeSpendPolicy::ChangeAllowed && self.change_descriptor.is_none() {