Skip to content

Commit

Permalink
fix: incorrect proof hash count causing panic (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
witter-deland authored May 22, 2023
1 parent a29a05d commit 0a9acbc
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/merkle_proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,11 @@ impl<T: Hasher> MerkleProof<T> {
// The next lines copy hashes from proof hashes and group them by layer index
let mut proof_layers: Vec<Vec<(usize, T::Hash)>> = Vec::with_capacity(tree_depth + 1);
let mut proof_copy = self.proof_hashes.clone();

for proof_indices in proof_indices_by_layers {
if proof_copy.len() < proof_indices.len() {
return Err(Error::not_enough_hashes_to_calculate_root());
}
let proof_hashes = proof_copy.splice(0..proof_indices.len(), []);
proof_layers.push(proof_indices.iter().cloned().zip(proof_hashes).collect());
}
Expand Down
27 changes: 27 additions & 0 deletions tests/merkle_proof_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,33 @@ pub mod root {

Ok(())
}

#[test]
pub fn should_return_error_not_enough_hashes_to_calculate_root() {
let test_data = common::setup();
let leaf_hashes = &test_data.leaf_hashes;
let expected_root = test_data.expected_root_hex.clone();
let indices_to_prove = vec![3, 4];

let leaves_to_prove: Vec<[u8; 32]> = indices_to_prove
.iter()
.map(|i| leaf_hashes.get(*i).unwrap().clone())
.collect();

let merkle_tree = MerkleTree::<Sha256>::from_leaves(&test_data.leaf_hashes);
let proof = merkle_tree.proof(&indices_to_prove);
let extracted_root = proof.root(
&indices_to_prove,
&leaves_to_prove,
test_data.leaf_values.len() + 1,
);

assert_eq!(
extracted_root.err().unwrap().to_string(),
Error::not_enough_hashes_to_calculate_root().to_string(),
"Should return error not_enough_hashes_to_calculate_root"
);
}
}

pub mod to_bytes {
Expand Down

0 comments on commit 0a9acbc

Please sign in to comment.