Skip to content

Commit

Permalink
refactor: make validate_merkle_proof more efficient
Browse files Browse the repository at this point in the history
  • Loading branch information
evanlinjin committed Jun 18, 2024
1 parent 64c77ee commit d515f51
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use bitcoin::hash_types::TxMerkleNode;
use bitcoin::hashes::sha256d::Hash as Sha256d;
use bitcoin::hashes::Hash;
use bitcoin::hashes::{Hash, HashEngine};
use bitcoin::Txid;
use types::GetMerkleRes;

Expand All @@ -22,20 +22,20 @@ pub fn validate_merkle_proof(
let mut index = merkle_res.pos;
let mut cur = txid.to_raw_hash();
for bytes in &merkle_res.merkle {
let mut reversed = [0u8; 32];
reversed.copy_from_slice(bytes);
let mut reversed = bytes.to_owned();
reversed.reverse();
// unwrap() safety: `reversed` has len 32 so `from_slice` can never fail.
let next_hash = Sha256d::from_slice(&reversed).unwrap();
let next_hash = Sha256d::from_byte_array(reversed);

let (left, right) = if index % 2 == 0 {
(cur, next_hash)
} else {
(next_hash, cur)
};

let data = [&left[..], &right[..]].concat();
cur = Sha256d::hash(&data);
let mut engine = Sha256d::engine();
engine.input(left.as_ref());
engine.input(right.as_ref());
cur = Sha256d::from_engine(engine);
index /= 2;
}

Expand Down

0 comments on commit d515f51

Please sign in to comment.