Implement basic vec tree hash cache

This commit is contained in:
Paul Hauner
2019-03-28 13:05:24 +11:00
parent 7af6eecb44
commit 224a967cce
3 changed files with 128 additions and 22 deletions

View File

@@ -1,7 +1,9 @@
use super::*;
use crate::ssz_encode;
use crate::{ssz_encode, Encodable};
impl CachedTreeHash for u64 {
type Item = Self;
fn build_cache_bytes(&self) -> Vec<u8> {
merkleize(ssz_encode(self))
}
@@ -10,10 +12,6 @@ impl CachedTreeHash for u64 {
8
}
fn max_num_leaves(&self) -> usize {
1
}
fn cached_hash_tree_root(
&self,
other: &Self,
@@ -28,3 +26,65 @@ impl CachedTreeHash for u64 {
Some(chunk + 1)
}
}
impl<T> CachedTreeHash for Vec<T>
where
T: CachedTreeHash + Encodable,
{
type Item = Self;
fn build_cache_bytes(&self) -> Vec<u8> {
let num_packed_bytes = self.num_bytes();
let num_leaves = num_sanitized_leaves(num_packed_bytes);
let mut packed = Vec::with_capacity(num_leaves * HASHSIZE);
for item in self {
packed.append(&mut ssz_encode(item));
}
let packed = sanitise_bytes(packed);
merkleize(packed)
}
fn num_bytes(&self) -> usize {
self.iter().fold(0, |acc, item| acc + item.num_bytes())
}
fn cached_hash_tree_root(
&self,
other: &Self::Item,
cache: &mut TreeHashCache,
chunk: usize,
) -> Option<usize> {
let num_packed_bytes = self.num_bytes();
let num_leaves = num_sanitized_leaves(num_packed_bytes);
if num_leaves != num_sanitized_leaves(other.num_bytes()) {
panic!("Need to handle a change in leaf count");
}
let mut packed = Vec::with_capacity(num_leaves * HASHSIZE);
// TODO: try and avoid fully encoding the whole list
for item in self {
packed.append(&mut ssz_encode(item));
}
let packed = sanitise_bytes(packed);
let num_nodes = num_nodes(num_leaves);
let num_internal_nodes = num_nodes - num_leaves;
{
let mut chunk = chunk + num_internal_nodes;
for new_chunk_bytes in packed.chunks(HASHSIZE) {
cache.maybe_update_chunk(chunk, new_chunk_bytes)?;
chunk += 1;
}
}
Some(chunk + num_nodes)
}
}