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.
This commit is contained in:
Martin Habovstiak 2023-02-13 11:16:31 +01:00
parent cf068d16b0
commit ae2aaaa436
1 changed files with 13 additions and 0 deletions

View File

@ -1014,6 +1014,15 @@ impl Transaction {
pub fn is_lock_time_enabled(&self) -> bool { pub fn is_lock_time_enabled(&self) -> bool {
self.input.iter().any(|i| i.enables_lock_time()) 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<Item = usize> + '_ {
self.output.iter().map(|txout| txout.script_pubkey.len())
}
} }
impl_consensus_encoding!(TxOut, value, script_pubkey); 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 /// preceding compact size. The lenght of preceding compact size is computed and added inside the
/// function for convenience. /// 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 /// # Usage
/// ///
/// When signing a transaction one doesn't know the signature before knowing the transaction fee and /// When signing a transaction one doesn't know the signature before knowing the transaction fee and