From 1b28375658d2016ea072a10b10fbebc362fa8514 Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Thu, 31 Mar 2022 15:16:39 +0200 Subject: [PATCH 1/2] Abstract tap branch hash computing into a dedicated method --- src/util/taproot.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/util/taproot.rs b/src/util/taproot.rs index 69d381b7..d4f5f9dd 100644 --- a/src/util/taproot.rs +++ b/src/util/taproot.rs @@ -131,6 +131,21 @@ impl TapLeafHash { } } +impl TapBranchHash { + /// Computes branch hash given two hashes of the nodes underneath it. + pub fn from_node_hashes(a: sha256::Hash, b: sha256::Hash) -> TapBranchHash { + let mut eng = TapBranchHash::engine(); + if a < b { + eng.input(&a); + eng.input(&b); + } else { + eng.input(&b); + eng.input(&a); + }; + TapBranchHash::from_engine(eng) + } +} + /// Maximum depth of a taproot tree script spend path. // https://github.com/bitcoin/bitcoin/blob/e826b22da252e0599c61d21c98ff89f366b3120f/src/script/interpreter.h#L229 pub const TAPROOT_CONTROL_MAX_NODE_COUNT: usize = 128; From f3ebfd6f8b049a2e2cfe6e9bd2b1b2f788b98d48 Mon Sep 17 00:00:00 2001 From: Dr Maxim Orlovsky Date: Thu, 31 Mar 2022 15:21:36 +0200 Subject: [PATCH 2/2] Remove repeated tap branch hash computing logic --- src/util/taproot.rs | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/src/util/taproot.rs b/src/util/taproot.rs index d4f5f9dd..bc5794fd 100644 --- a/src/util/taproot.rs +++ b/src/util/taproot.rs @@ -576,16 +576,9 @@ impl NodeInfo { b_leaf.merkle_branch.push(a.hash)?; // add hashing partner all_leaves.push(b_leaf); } - let mut eng = TapBranchHash::engine(); - if a.hash < b.hash { - eng.input(&a.hash); - eng.input(&b.hash); - } else { - eng.input(&b.hash); - eng.input(&a.hash); - }; + let hash = TapBranchHash::from_node_hashes(a.hash, b.hash); Ok(Self { - hash: sha256::Hash::from_engine(eng), + hash: sha256::Hash::from_inner(hash.into_inner()), leaves: all_leaves, }) } @@ -790,16 +783,11 @@ impl ControlBlock { let mut curr_hash = TapBranchHash::from_inner(leaf_hash.into_inner()); // Verify the proof for elem in self.merkle_branch.as_inner() { - let mut eng = TapBranchHash::engine(); - if curr_hash.as_inner() < elem.as_inner() { - eng.input(&curr_hash); - eng.input(elem); - } else { - eng.input(elem); - eng.input(&curr_hash); - } // Recalculate the curr hash as parent hash - curr_hash = TapBranchHash::from_engine(eng); + curr_hash = TapBranchHash::from_node_hashes( + sha256::Hash::from_inner(curr_hash.into_inner()), + *elem + ); } // compute the taptweak let tweak = TapTweakHash::from_key_and_tweak(self.internal_key, Some(curr_hash));