Skip to content

Commit ea811d6

Browse files
authored
perf: remove allocations from merkle tree proof verification logic (#8614)
This PR does two small things: - Removes the allocations that were happening on each loop - Makes it more explicit that the bit in the index is only being used to specify the order of the inputs for the hash function Co-Authored-By: Kevaundray Wedderburn <kevtheappdev@gmail.com>
1 parent 9b3d7e3 commit ea811d6

File tree

1 file changed

+9
-10
lines changed
  • consensus/merkle_proof/src

1 file changed

+9
-10
lines changed

consensus/merkle_proof/src/lib.rs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use ethereum_hashing::{ZERO_HASHES, hash, hash32_concat};
1+
use ethereum_hashing::{ZERO_HASHES, hash32_concat};
22
use safe_arith::ArithError;
33
use std::sync::LazyLock;
44

@@ -382,20 +382,19 @@ pub fn verify_merkle_proof(
382382
pub fn merkle_root_from_branch(leaf: H256, branch: &[H256], depth: usize, index: usize) -> H256 {
383383
assert_eq!(branch.len(), depth, "proof length should equal depth");
384384

385-
let mut merkle_root = leaf.as_slice().to_vec();
385+
let mut merkle_root = leaf.0;
386386

387-
for (i, leaf) in branch.iter().enumerate().take(depth) {
387+
for (i, branch_node) in branch.iter().enumerate().take(depth) {
388388
let ith_bit = (index >> i) & 0x01;
389-
if ith_bit == 1 {
390-
merkle_root = hash32_concat(leaf.as_slice(), &merkle_root)[..].to_vec();
389+
let (left, right) = if ith_bit == 1 {
390+
(branch_node.as_slice(), merkle_root.as_slice())
391391
} else {
392-
let mut input = merkle_root;
393-
input.extend_from_slice(leaf.as_slice());
394-
merkle_root = hash(&input);
395-
}
392+
(merkle_root.as_slice(), branch_node.as_slice())
393+
};
394+
merkle_root = hash32_concat(left, right);
396395
}
397396

398-
H256::from_slice(&merkle_root)
397+
H256::from(merkle_root)
399398
}
400399

401400
impl From<ArithError> for MerkleTreeError {

0 commit comments

Comments
 (0)