diff --git a/crates/eth2util/src/hash.rs b/crates/eth2util/src/hash.rs new file mode 100644 index 00000000..85aa9915 --- /dev/null +++ b/crates/eth2util/src/hash.rs @@ -0,0 +1,38 @@ +use pluto_eth2api::spec::phase0::{Root, Slot}; +use pluto_ssz::{HashWalker, Hasher, HasherError}; + +/// Hashing error. +#[derive(Debug, thiserror::Error)] +pub enum HashError { + /// Failed to hash the slot root. + #[error("hash epoch: {0}")] + HashEpoch(#[from] HasherError), +} + +/// Result type for hash helpers. +type Result = std::result::Result; + +/// Returns the SSZ hash root of the slot. +pub fn slot_hash_root(slot: Slot) -> Result { + let mut hasher = Hasher::default(); + let index = hasher.index(); + + hasher.put_uint64(slot)?; + hasher.merkleize(index)?; + + Ok(hasher.hash_root()?) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_slot_hash_root() { + let resp = slot_hash_root(2).expect("hash slot"); + assert_eq!( + hex::encode(resp), + "0200000000000000000000000000000000000000000000000000000000000000" + ); + } +} diff --git a/crates/eth2util/src/lib.rs b/crates/eth2util/src/lib.rs index f8aede98..acd10dcf 100644 --- a/crates/eth2util/src/lib.rs +++ b/crates/eth2util/src/lib.rs @@ -13,6 +13,9 @@ pub mod rlp; /// EIP712 utilities. pub mod eip712; +/// SSZ hash helpers. +pub mod hash; + /// Network utilities. pub mod network;