Skip to content

Commit

Permalink
ensure branch length and depth are same
Browse files Browse the repository at this point in the history
Signed-off-by: Jun Kimura <[email protected]>
  • Loading branch information
bluele committed Jan 14, 2024
1 parent c288978 commit 799fec1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
6 changes: 4 additions & 2 deletions crates/consensus/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ pub enum Error {
pub enum MerkleError {
/// invalid merkle branch error: leaf={0:?} branch={1:?} index={2:?} root={3:?}
InvalidMerkleBranch(H256, Vec<H256>, u64, Root),
/// too long merkle branch error: leaf={0:?} branch={1:?} index={2:?} root={3:?}
TooLongMerkleBranch(H256, Vec<H256>, u64, Root),
/// too long merkle branch error: depth={0:?} leaf={1:?} branch={2:?} index={3:?} root={4:?}
TooLongMerkleBranchLength(u32, H256, Vec<H256>, u64, Root),
/// invalid merkle branch length error: depth={0:?} leaf={1:?} branch={2:?} index={3:?} root={4:?}
InvalidMerkleBranchLength(u32, H256, Vec<H256>, u64, Root),
}

#[cfg(feature = "std")]
Expand Down
12 changes: 11 additions & 1 deletion crates/consensus/src/merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@ pub fn is_valid_merkle_branch(
leaf_index: u64,
root: Root,
) -> Result<(), MerkleError> {
if depth != branch.len() as u32 {
return Err(MerkleError::InvalidMerkleBranchLength(
depth,
leaf,
branch.to_vec(),
leaf_index,
root,
));
}
let index = 2u64.pow(depth) + leaf_index;
let mut value = leaf.clone();
for (i, b) in branch.iter().enumerate() {
Expand All @@ -20,7 +29,8 @@ pub fn is_valid_merkle_branch(
value = hash([value.as_bytes(), b.as_bytes()].concat());
}
} else {
return Err(MerkleError::TooLongMerkleBranch(
return Err(MerkleError::TooLongMerkleBranchLength(
depth,
leaf,
branch.to_vec(),
index,
Expand Down

0 comments on commit 799fec1

Please sign in to comment.