serai/coordinator/tributary/src/merkle.rs

38 lines
879 B
Rust
Raw Normal View History

use blake2::{Digest, Blake2s256};
pub(crate) fn merkle(hash_args: &[[u8; 32]]) -> [u8; 32] {
let mut hashes = Vec::with_capacity(hash_args.len());
for hash in hash_args {
hashes.push(Blake2s256::digest([b"leaf_hash".as_ref(), hash].concat()));
}
let zero = [0; 32];
let mut interim;
while hashes.len() > 1 {
2023-04-11 23:04:27 +00:00
interim = Vec::with_capacity((hashes.len() + 1) / 2);
let mut i = 0;
while i < hashes.len() {
interim.push(Blake2s256::digest(
[
b"branch_hash".as_ref(),
hashes[i].as_ref(),
hashes
2023-04-12 14:52:28 +00:00
.get(i + 1)
.map(|hash| {
let res: &[u8] = hash.as_ref();
res
})
.unwrap_or(zero.as_ref()),
]
.concat(),
));
i += 2;
}
hashes = interim;
}
hashes.first().copied().map(Into::into).unwrap_or(zero)
}