Skip to main content

ethrex_trie/
node_hash.rs

1#[cfg(not(feature = "std"))]
2use alloc::vec::Vec;
3use ethereum_types::H256;
4use ethrex_crypto::Crypto;
5use ethrex_rlp::{decode::RLPDecode, encode::RLPEncode, error::RLPDecodeError, structs::Encoder};
6
7use crate::rkyv_utils::H256Wrapper;
8
9/// Struct representing a trie node hash
10/// If the encoded node is less than 32 bits, contains the encoded node itself
11// TODO: Check if we can omit the Inline variant, as nodes will always be bigger than 32 bits in our use case
12// TODO: Check if making this `Copy` can make the code less verbose at a reasonable performance cost
13#[derive(
14    Debug,
15    Clone,
16    Copy,
17    PartialEq,
18    Hash,
19    PartialOrd,
20    Ord,
21    Eq,
22    serde::Serialize,
23    serde::Deserialize,
24    rkyv::Serialize,
25    rkyv::Deserialize,
26    rkyv::Archive,
27)]
28pub enum NodeHash {
29    Hashed(#[rkyv(with=H256Wrapper)] H256),
30    // Inline is always len < 32. We need to store the length of the data, a u8 is enough.
31    Inline(([u8; 31], u8)),
32}
33
34impl AsRef<[u8]> for NodeHash {
35    fn as_ref(&self) -> &[u8] {
36        match self {
37            NodeHash::Inline((slice, len)) => &slice[0..(*len as usize)],
38            NodeHash::Hashed(x) => x.as_bytes(),
39        }
40    }
41}
42
43impl NodeHash {
44    /// Returns the `NodeHash` of an encoded node (encoded using the NodeEncoder)
45    ///
46    /// `crypto` is a generic parameter, here and in every hashing function of
47    /// this crate, instead of a `&dyn Crypto`. Passing a concrete provider to a
48    /// `&dyn Crypto` parameter makes the compiler emit that provider's whole
49    /// vtable, which keeps every one of its methods linked in. This crate names
50    /// `NativeCrypto` where no provider is in scope, so a zkVM guest, which
51    /// hashes through its own provider, would also link `NativeCrypto`'s
52    /// modexp, pairing and signature code. With a generic parameter those calls
53    /// are dispatched statically and reference `keccak256` alone. `?Sized`
54    /// keeps accepting the callers that hold a `&dyn Crypto`.
55    pub fn from_encoded(encoded: &[u8], crypto: &(impl Crypto + ?Sized)) -> NodeHash {
56        if encoded.len() >= 32 {
57            let hash = crypto.keccak256(encoded);
58            NodeHash::Hashed(H256::from_slice(&hash))
59        } else {
60            NodeHash::from_slice(encoded)
61        }
62    }
63
64    /// Converts a slice of an already hashed data (in case it's not inlineable) to a NodeHash.
65    /// Panics if the slice is over 32 bytes
66    /// If you need to hash it in case its len >= 32 see `from_encoded`
67    pub(crate) fn from_slice(slice: &[u8]) -> NodeHash {
68        match slice.len() {
69            0..32 => {
70                let mut buffer = [0; 31];
71                buffer[0..slice.len()].copy_from_slice(slice);
72                NodeHash::Inline((buffer, slice.len() as u8))
73            }
74            _ => NodeHash::Hashed(H256::from_slice(slice)),
75        }
76    }
77
78    /// Returns the finalized hash
79    /// NOTE: This will hash smaller nodes, only use to get the final root hash, not for intermediate node hashes
80    pub fn finalize(self, crypto: &(impl Crypto + ?Sized)) -> H256 {
81        match self {
82            NodeHash::Inline(_) => H256(crypto.keccak256(self.as_ref())),
83            NodeHash::Hashed(x) => x,
84        }
85    }
86
87    /// Returns true if the hash is valid
88    /// The hash will only be considered invalid if it is empty
89    /// Aka if it has a default value instead of being a product of hash computation
90    pub fn is_valid(&self) -> bool {
91        !matches!(self, NodeHash::Inline(v) if v.1 == 0)
92    }
93
94    /// Encodes this NodeHash with the given encoder.
95    pub fn encode<'a>(&self, mut encoder: Encoder<'a>) -> Encoder<'a> {
96        match self {
97            NodeHash::Inline(_) => {
98                encoder = encoder.encode_raw(self.as_ref());
99            }
100            NodeHash::Hashed(_) => {
101                encoder = encoder.encode_bytes(self.as_ref());
102            }
103        }
104        encoder
105    }
106
107    pub fn len(&self) -> usize {
108        match self {
109            NodeHash::Hashed(h256) => h256.as_bytes().len(),
110            NodeHash::Inline(value) => value.1 as usize,
111        }
112    }
113
114    pub fn is_empty(&self) -> bool {
115        match self {
116            NodeHash::Hashed(h256) => h256.as_bytes().is_empty(),
117            NodeHash::Inline(value) => value.1 == 0,
118        }
119    }
120}
121
122impl From<H256> for NodeHash {
123    fn from(value: H256) -> Self {
124        NodeHash::Hashed(value)
125    }
126}
127
128impl From<NodeHash> for Vec<u8> {
129    fn from(val: NodeHash) -> Self {
130        val.as_ref().to_vec()
131    }
132}
133
134impl From<&NodeHash> for Vec<u8> {
135    fn from(val: &NodeHash) -> Self {
136        val.as_ref().to_vec()
137    }
138}
139
140impl Default for NodeHash {
141    fn default() -> Self {
142        NodeHash::Inline(([0; 31], 0))
143    }
144}
145
146// Encoded as Vec<u8>
147impl RLPEncode for NodeHash {
148    fn encode(&self, buf: &mut dyn bytes::BufMut) {
149        RLPEncode::encode(&Into::<Vec<u8>>::into(self), buf)
150    }
151
152    fn length(&self) -> usize {
153        match self {
154            NodeHash::Hashed(_) => 33,                   // 1 byte prefix + 32 bytes
155            NodeHash::Inline((_, 0)) => 1,               // if empty then it's encoded to RLP_NULL
156            NodeHash::Inline((_, len)) => *len as usize, // already encoded
157        }
158    }
159}
160
161impl RLPDecode for NodeHash {
162    fn decode_unfinished(rlp: &[u8]) -> Result<(Self, &[u8]), ethrex_rlp::error::RLPDecodeError> {
163        let (hash, rest): (Vec<u8>, &[u8]);
164        (hash, rest) = RLPDecode::decode_unfinished(rlp)?;
165        if hash.len() > 32 {
166            return Err(RLPDecodeError::InvalidLength);
167        }
168        let hash = NodeHash::from_slice(&hash);
169        Ok((hash, rest))
170    }
171}