Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: make validate_merkle_proof more efficient #134

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading