mirror of
https://github.com/sigp/lighthouse.git
synced 2026-03-19 12:56:12 +00:00
Remove tree hashing from ssz crate
This commit is contained in:
@@ -3,6 +3,8 @@ use hashing::hash;
|
||||
use int_to_bytes::int_to_bytes32;
|
||||
use ssz::ssz_encode;
|
||||
|
||||
mod impls;
|
||||
|
||||
pub trait TreeHash {
|
||||
fn tree_hash_type() -> TreeHashType;
|
||||
|
||||
@@ -13,70 +15,9 @@ pub trait TreeHash {
|
||||
fn tree_hash_root(&self) -> Vec<u8>;
|
||||
}
|
||||
|
||||
impl TreeHash for u64 {
|
||||
fn tree_hash_type() -> TreeHashType {
|
||||
TreeHashType::Basic
|
||||
}
|
||||
|
||||
fn tree_hash_packed_encoding(&self) -> Vec<u8> {
|
||||
ssz_encode(self)
|
||||
}
|
||||
|
||||
fn tree_hash_packing_factor() -> usize {
|
||||
HASHSIZE / 8
|
||||
}
|
||||
|
||||
fn tree_hash_root(&self) -> Vec<u8> {
|
||||
int_to_bytes32(*self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> TreeHash for Vec<T>
|
||||
where
|
||||
T: TreeHash,
|
||||
{
|
||||
fn tree_hash_type() -> TreeHashType {
|
||||
TreeHashType::List
|
||||
}
|
||||
|
||||
fn tree_hash_packed_encoding(&self) -> Vec<u8> {
|
||||
unreachable!("List should never be packed.")
|
||||
}
|
||||
|
||||
fn tree_hash_packing_factor() -> usize {
|
||||
unreachable!("List should never be packed.")
|
||||
}
|
||||
|
||||
fn tree_hash_root(&self) -> Vec<u8> {
|
||||
let leaves = match T::tree_hash_type() {
|
||||
TreeHashType::Basic => {
|
||||
let mut leaves =
|
||||
Vec::with_capacity((HASHSIZE / T::tree_hash_packing_factor()) * self.len());
|
||||
|
||||
for item in self {
|
||||
leaves.append(&mut item.tree_hash_packed_encoding());
|
||||
}
|
||||
|
||||
leaves
|
||||
}
|
||||
TreeHashType::Composite | TreeHashType::List => {
|
||||
let mut leaves = Vec::with_capacity(self.len() * HASHSIZE);
|
||||
|
||||
for item in self {
|
||||
leaves.append(&mut item.tree_hash_root())
|
||||
}
|
||||
|
||||
leaves
|
||||
}
|
||||
};
|
||||
|
||||
// Mix in the length
|
||||
let mut root_and_len = Vec::with_capacity(HASHSIZE * 2);
|
||||
root_and_len.append(&mut efficient_merkleize(&leaves)[0..32].to_vec());
|
||||
root_and_len.append(&mut int_to_bytes32(self.len() as u64));
|
||||
|
||||
hash(&root_and_len)
|
||||
}
|
||||
pub fn merkle_root(bytes: &[u8]) -> Vec<u8> {
|
||||
// TODO: replace this with a _more_ efficient fn which is more memory efficient.
|
||||
efficient_merkleize(&bytes)[0..32].to_vec()
|
||||
}
|
||||
|
||||
pub fn efficient_merkleize(bytes: &[u8]) -> Vec<u8> {
|
||||
|
||||
Reference in New Issue
Block a user