Skip to content

Commit

Permalink
Merge #134: refactor: make validate_merkle_proof more efficient
Browse files Browse the repository at this point in the history
3a1f1bf refactor: make `validate_merkle_proof` more efficient (志宇)

Pull request description:

ACKs for top commit:
  notmandatory:
    ACK 3a1f1bf

Tree-SHA512: 995d1582bc13d21c13b76dcd5e5edb633a59588e713b1e0aaf33363e17c47aafb22c7f250483e60cdc68e85fc94f041a0c39815160dc2592bedf959679f804dc
  • Loading branch information
notmandatory committed Jul 31, 2024
2 parents 54797a0 + 3a1f1bf commit 746a0e6
Showing 1 changed file with 15 additions and 15 deletions.
30 changes: 15 additions & 15 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 @@ -21,21 +21,21 @@ pub fn validate_merkle_proof(
) -> bool {
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);
reversed.reverse();
// unwrap() safety: `reversed` has len 32 so `from_slice` can never fail.
let next_hash = Sha256d::from_slice(&reversed).unwrap();
for mut bytes in merkle_res.merkle.iter().cloned() {
bytes.reverse();
let next_hash = Sha256d::from_byte_array(bytes);

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

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

Expand Down

0 comments on commit 746a0e6

Please sign in to comment.