change merkle_root return to Option

This commit is contained in:
Boog900 2024-11-15 20:34:11 +00:00
parent 05cda9762f
commit e6fdef6d0b
No known key found for this signature in database
GPG key ID: 42AB1287CB0041C2
2 changed files with 10 additions and 8 deletions

View file

@ -126,7 +126,10 @@ impl Block {
transactions.push(self.miner_transaction.hash()); transactions.push(self.miner_transaction.hash());
transactions.extend_from_slice(&self.transactions); 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(); write_varint(&(1 + self.transactions.len()), &mut blob).unwrap();
blob blob
} }

View file

@ -6,13 +6,12 @@ use crate::primitives::keccak256;
/// https://github.com/monero-project/monero/blob/893916ad091a92e765ce3241b94e706ad012b62a /// https://github.com/monero-project/monero/blob/893916ad091a92e765ce3241b94e706ad012b62a
/// /src/crypto/tree-hash.c#L62 /// /src/crypto/tree-hash.c#L62
/// ///
/// # Panics /// This function returns [`None`] if the tree is empty.
/// This function will panic if the tree is empty. pub fn merkle_root(mut leafs: Vec<[u8; 32]>) -> Option<[u8; 32]> {
pub fn merkle_root(mut leafs: Vec<[u8; 32]>) -> [u8; 32] {
match leafs.len() { match leafs.len() {
0 => panic!("Can't compute Merkle root for empty tree"), 0 => None,
1 => leafs[0], 1 => Some(leafs[0]),
2 => keccak256([leafs[0], leafs[1]].concat()), 2 => Some(keccak256([leafs[0], leafs[1]].concat())),
_ => { _ => {
// Monero preprocess this so the length is a power of 2 // 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 let mut high_pow_2 = 4; // 4 is the lowest value this can be
@ -52,7 +51,7 @@ pub fn merkle_root(mut leafs: Vec<[u8; 32]>) -> [u8; 32] {
leafs = new_hashes; leafs = new_hashes;
new_hashes = Vec::with_capacity(leafs.len() / 2); new_hashes = Vec::with_capacity(leafs.len() / 2);
} }
leafs[0] Some(leafs[0])
} }
} }
} }