mirror of
https://github.com/sigp/lighthouse.git
synced 2026-03-23 14:54:45 +00:00
now using the Hashtree macro for most struct types
This commit is contained in:
@@ -32,6 +32,12 @@ impl TreeHash for usize {
|
||||
}
|
||||
}
|
||||
|
||||
impl TreeHash for bool {
|
||||
fn hash_tree_root_internal(&self) -> Vec<u8> {
|
||||
ssz_encode(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl TreeHash for Address {
|
||||
fn hash_tree_root_internal(&self) -> Vec<u8> {
|
||||
ssz_encode(self)
|
||||
|
||||
@@ -7,9 +7,7 @@ pub trait TreeHash {
|
||||
fn hash_tree_root_internal(&self) -> Vec<u8>;
|
||||
fn hash_tree_root(&self) -> Vec<u8> {
|
||||
let mut result = self.hash_tree_root_internal();
|
||||
if result.len() < HASHSIZE {
|
||||
zpad(&mut result, HASHSIZE);
|
||||
}
|
||||
zpad(&mut result, HASHSIZE);
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//!
|
||||
//! - `#[derive(Encode)]`
|
||||
//! - `#[derive(Decode)]`
|
||||
//! - `#[derive(Hashtree)]`
|
||||
//!
|
||||
//! These macros provide SSZ encoding/decoding for a `struct`. Fields are encoded/decoded in the
|
||||
//! order they are defined.
|
||||
@@ -126,3 +127,34 @@ pub fn ssz_decode_derive(input: TokenStream) -> TokenStream {
|
||||
};
|
||||
output.into()
|
||||
}
|
||||
|
||||
/// Implements `ssz::TreeHash` for some `struct`.
|
||||
///
|
||||
/// Fields are processed in the order they are defined.
|
||||
#[proc_macro_derive(Hashtree)]
|
||||
pub fn ssz_hashtree_derive(input: TokenStream) -> TokenStream {
|
||||
let item = parse_macro_input!(input as DeriveInput);
|
||||
|
||||
let name = &item.ident;
|
||||
|
||||
let struct_data = match &item.data {
|
||||
syn::Data::Struct(s) => s,
|
||||
_ => panic!("ssz_derive only supports structs."),
|
||||
};
|
||||
|
||||
let field_idents = get_named_field_idents(&struct_data);
|
||||
|
||||
let output = quote! {
|
||||
impl ssz::TreeHash for #name {
|
||||
fn hash_tree_root_internal(&self) -> Vec<u8> {
|
||||
let mut result: Vec<u8> = vec![];
|
||||
#(
|
||||
result.append(&mut self.#field_idents.hash_tree_root_internal());
|
||||
)*
|
||||
|
||||
ssz::hash(&result)
|
||||
}
|
||||
}
|
||||
};
|
||||
output.into()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user