Skip to content

Commit ac051d7

Browse files
Calculate fee amount after output addition
We would previously calculate the fee amount in two steps: 1. Add the weight of the empty transaction 2. Add the weight of each output That's unnecessary: you can just use the weight of the transaction *after* the output addition. This is clearer, but also avoids a rare bug: if there are many outputs, adding them would cause the "number of outputs" transaction parameter lenght to increase, and we wouldn't notice it. This might still happen when adding the drain output - this commit also adds a comment as a reminder.
1 parent 00d426b commit ac051d7

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

src/wallet/mod.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -736,8 +736,6 @@ where
736736
let mut outgoing: u64 = 0;
737737
let mut received: u64 = 0;
738738

739-
fee_amount += fee_rate.fee_wu(tx.weight());
740-
741739
let recipients = params.recipients.iter().map(|(r, v)| (r, *v));
742740

743741
for (index, (script_pubkey, value)) in recipients.enumerate() {
@@ -753,13 +751,14 @@ where
753751
script_pubkey: script_pubkey.clone(),
754752
value,
755753
};
756-
fee_amount += fee_rate.fee_vb(serialize(&new_out).len());
757754

758755
tx.output.push(new_out);
759756

760757
outgoing += value;
761758
}
762759

760+
fee_amount += fee_rate.fee_wu(tx.weight());
761+
763762
if params.change_policy != tx_builder::ChangeSpendPolicy::ChangeAllowed
764763
&& self.change_descriptor.is_none()
765764
{
@@ -851,6 +850,9 @@ where
851850
script_pubkey: drain_script,
852851
};
853852

853+
// TODO: We should pay attention when adding a new output: this might increase
854+
// the lenght of the "number of vouts" parameter by 2 bytes, potentially making
855+
// our feerate too low
854856
tx.output.push(drain_output);
855857
}
856858
};

0 commit comments

Comments
 (0)