lighthouse-pulse/eth2/utils/ssz/src/impl_tree_hash.rs

64 lines
1.3 KiB
Rust
Raw Normal View History

2018-12-04 20:37:12 +00:00
use super::ethereum_types::{Address, H256};
use super::{merkle_hash, ssz_encode, TreeHash};
2018-12-04 20:37:12 +00:00
impl TreeHash for u8 {
2019-01-24 04:47:28 +00:00
fn hash_tree_root(&self) -> Vec<u8> {
2018-12-04 20:37:12 +00:00
ssz_encode(self)
}
}
impl TreeHash for u16 {
2019-01-24 04:47:28 +00:00
fn hash_tree_root(&self) -> Vec<u8> {
2018-12-04 20:37:12 +00:00
ssz_encode(self)
}
}
impl TreeHash for u32 {
2019-01-24 04:47:28 +00:00
fn hash_tree_root(&self) -> Vec<u8> {
2018-12-04 20:37:12 +00:00
ssz_encode(self)
}
}
impl TreeHash for u64 {
2019-01-24 04:47:28 +00:00
fn hash_tree_root(&self) -> Vec<u8> {
2018-12-04 20:37:12 +00:00
ssz_encode(self)
}
}
impl TreeHash for Address {
2019-01-24 04:47:28 +00:00
fn hash_tree_root(&self) -> Vec<u8> {
2018-12-04 20:37:12 +00:00
ssz_encode(self)
}
}
impl TreeHash for H256 {
2019-01-24 04:47:28 +00:00
fn hash_tree_root(&self) -> Vec<u8> {
2018-12-04 20:37:12 +00:00
ssz_encode(self)
}
}
impl<T> TreeHash for Vec<T>
where
T: TreeHash,
{
2019-01-24 04:47:28 +00:00
/// Returns the merkle_hash of a list of hash_tree_root values created
/// from the given list.
/// Note: A byte vector, Vec<u8>, must be converted to a slice (as_slice())
/// to be handled properly (i.e. hashed) as byte array.
2019-01-24 04:47:28 +00:00
fn hash_tree_root(&self) -> Vec<u8> {
let mut tree_hashes = self.iter().map(|x| x.hash_tree_root()).collect();
merkle_hash(&mut tree_hashes)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_impl_tree_hash_vec() {
2019-01-24 04:47:28 +00:00
let result = vec![1u32, 2, 3, 4, 5, 6, 7].hash_tree_root();
assert_eq!(result.len(), 32);
}
}