Merge rust-bitcoin/rust-bitcoin#2382: Improve private function `use_segwit_serialization`

dae16f052c Use any method on iterator (Tobin C. Harding)
671dc0e9e0 Use better predicate name (Tobin C. Harding)

Pull request description:

  - Patch 1: Improve the name.
  - Patch 2: Use `any` instead of manual loop.

ACKs for top commit:
  Kixunil:
    ACK dae16f052c
  apoelstra:
    ACK dae16f052c

Tree-SHA512: 9b98c21cbb5fa93c011ba8bae88ab0dd2efa807d7cb220f121c56b31fbe5a9e9cd6f29badeca092e22949dc278c1a9d3dd676cd2919a11f13101d0dd83ec9313
This commit is contained in:
Andrew Poelstra 2024-01-23 15:32:31 +00:00
commit ccbc976261
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 9 additions and 11 deletions

View File

@ -773,9 +773,9 @@ impl Transaction {
#[inline]
pub fn total_size(&self) -> usize {
let mut size: usize = 4; // Serialized length of a u32 for the version number.
let use_segwit = self.use_segwit_serialization();
let uses_segwit = self.uses_segwit_serialization();
if use_segwit {
if uses_segwit {
size += 2; // 1 byte for the marker and 1 for the flag.
}
@ -784,7 +784,7 @@ impl Transaction {
.input
.iter()
.map(|input| {
if use_segwit {
if uses_segwit {
input.total_size()
} else {
input.base_size()
@ -984,12 +984,10 @@ impl Transaction {
}
/// Returns whether or not to serialize transaction as specified in BIP-144.
fn use_segwit_serialization(&self) -> bool {
for input in &self.input {
if !input.witness.is_empty() {
fn uses_segwit_serialization(&self) -> bool {
if self.input.iter().any(|input| !input.witness.is_empty()) {
return true;
}
}
// To avoid serialization ambiguity, no inputs means we use BIP141 serialization (see
// `Transaction` docs for full explanation).
self.input.is_empty()
@ -1175,7 +1173,7 @@ impl Encodable for Transaction {
len += self.version.consensus_encode(w)?;
// Legacy transaction serialization format only includes inputs and outputs.
if !self.use_segwit_serialization() {
if !self.uses_segwit_serialization() {
len += self.input.consensus_encode(w)?;
len += self.output.consensus_encode(w)?;
} else {
@ -2167,14 +2165,14 @@ mod tests {
for (is_segwit, tx, expected_weight) in &txs {
let txin_weight = if *is_segwit { TxIn::segwit_weight } else { TxIn::legacy_weight };
let tx: Transaction = deserialize(Vec::from_hex(tx).unwrap().as_slice()).unwrap();
assert_eq!(*is_segwit, tx.use_segwit_serialization());
assert_eq!(*is_segwit, tx.uses_segwit_serialization());
let mut calculated_weight = empty_transaction_weight
+ tx.input.iter().fold(Weight::ZERO, |sum, i| sum + txin_weight(i))
+ tx.output.iter().fold(Weight::ZERO, |sum, o| sum + o.weight());
// The empty tx uses segwit serialization but a legacy tx does not.
if !tx.use_segwit_serialization() {
if !tx.uses_segwit_serialization() {
calculated_weight -= Weight::from_wu(2);
}