From 92d066ba92b238029d1f073708ae7f8bef9111ee Mon Sep 17 00:00:00 2001 From: Witter Date: Tue, 16 May 2023 18:57:13 +0800 Subject: [PATCH 1/2] [fix] incorrect proof hash count panic --- src/merkle_proof.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/merkle_proof.rs b/src/merkle_proof.rs index 1a87116..f8a0e49 100644 --- a/src/merkle_proof.rs +++ b/src/merkle_proof.rs @@ -228,7 +228,11 @@ impl MerkleProof { // The next lines copy hashes from proof hashes and group them by layer index let mut proof_layers: Vec> = 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()); } From 367a0a1f2faf2fb95f5caeebdea30f2c6637f56f Mon Sep 17 00:00:00 2001 From: Witter Date: Sat, 20 May 2023 20:19:40 +0800 Subject: [PATCH 2/2] [test] unit test for bug fix --- tests/merkle_proof_test.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/merkle_proof_test.rs b/tests/merkle_proof_test.rs index d0bb380..aa32042 100644 --- a/tests/merkle_proof_test.rs +++ b/tests/merkle_proof_test.rs @@ -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::::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 {