From ae2aaaa43667b0bc2c7a0ae23f1ff20ec0755157 Mon Sep 17 00:00:00 2001 From: Martin Habovstiak Date: Mon, 13 Feb 2023 11:16:31 +0100 Subject: [PATCH] Add `script_pubkey_lens` method In some cases people construct the transaction with a dummy fee output value before calculating the weight. A method to create the iterator over `script_pubkey` lengths is useful in such cases. --- bitcoin/src/blockdata/transaction.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/bitcoin/src/blockdata/transaction.rs b/bitcoin/src/blockdata/transaction.rs index 8cb13064..8d384dd5 100644 --- a/bitcoin/src/blockdata/transaction.rs +++ b/bitcoin/src/blockdata/transaction.rs @@ -1014,6 +1014,15 @@ impl Transaction { pub fn is_lock_time_enabled(&self) -> bool { self.input.iter().any(|i| i.enables_lock_time()) } + + /// Returns an iterator over lengths of `script_pubkey`s in the outputs. + /// + /// This is useful in combination with [`predict_weight`] if you have the transaction already + /// constructed with a dummy value in the fee output which you'll adjust after calculating the + /// weight. + pub fn script_pubkey_lens(&self) -> impl Iterator + '_ { + self.output.iter().map(|txout| txout.script_pubkey.len()) + } } impl_consensus_encoding!(TxOut, value, script_pubkey); @@ -1177,6 +1186,10 @@ impl From<&Transaction> for Wtxid { /// preceding compact size. The lenght of preceding compact size is computed and added inside the /// function for convenience. /// +/// If you have the transaction already constructed (except for signatures) with a dummy value for +/// fee output you can use the return value of [`Transaction::script_pubkey_lens`] method directly +/// as the second argument. +/// /// # Usage /// /// When signing a transaction one doesn't know the signature before knowing the transaction fee and