Skip to content

Commit

Permalink
change merkle_root return to Option
Browse files Browse the repository at this point in the history
  • Loading branch information
Boog900 committed Nov 15, 2024
1 parent 05cda97 commit e6fdef6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
5 changes: 4 additions & 1 deletion networks/monero/src/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,10 @@ impl Block {
transactions.push(self.miner_transaction.hash());
transactions.extend_from_slice(&self.transactions);

blob.extend_from_slice(&merkle_root(transactions));
blob.extend_from_slice(
&merkle_root(transactions)
.expect("the tree will not be empty, the miner tx is always present"),
);
write_varint(&(1 + self.transactions.len()), &mut blob).unwrap();
blob
}
Expand Down
13 changes: 6 additions & 7 deletions networks/monero/src/merkle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ use crate::primitives::keccak256;
/// https://github.com/monero-project/monero/blob/893916ad091a92e765ce3241b94e706ad012b62a
/// /src/crypto/tree-hash.c#L62
///
/// # Panics
/// This function will panic if the tree is empty.
pub fn merkle_root(mut leafs: Vec<[u8; 32]>) -> [u8; 32] {
/// This function returns [`None`] if the tree is empty.
pub fn merkle_root(mut leafs: Vec<[u8; 32]>) -> Option<[u8; 32]> {
match leafs.len() {
0 => panic!("Can't compute Merkle root for empty tree"),
1 => leafs[0],
2 => keccak256([leafs[0], leafs[1]].concat()),
0 => None,
1 => Some(leafs[0]),
2 => Some(keccak256([leafs[0], leafs[1]].concat())),
_ => {
// Monero preprocess this so the length is a power of 2
let mut high_pow_2 = 4; // 4 is the lowest value this can be
Expand Down Expand Up @@ -52,7 +51,7 @@ pub fn merkle_root(mut leafs: Vec<[u8; 32]>) -> [u8; 32] {
leafs = new_hashes;
new_hashes = Vec::with_capacity(leafs.len() / 2);
}
leafs[0]
Some(leafs[0])
}
}
}

0 comments on commit e6fdef6

Please sign in to comment.