Skip to main content

ethrex_trie/
trie.rs

1#![cfg_attr(not(feature = "std"), no_std)]
2// In no_std builds the per-node hash cache (`OnceLock`) is a non-atomic, `!Sync`
3// cell (see `node::OnceLock`), which makes `Node` `!Sync` and trips
4// `arc_with_non_send_sync` on the `Arc<Node>` in `NodeRef`. The `Arc` is
5// deliberate: the type is shared with the std build, where `Node` is `Send + Sync`
6// and nodes are handed across rayon workers during parallel merkleization. The
7// single-threaded no_std consumer (the zkVM guest) never shares across threads, so
8// the atomic refcount is harmless here and keeps a single unified node type across
9// both builds.
10#![cfg_attr(not(feature = "std"), allow(clippy::arc_with_non_send_sync))]
11
12#[macro_use]
13extern crate alloc;
14
15pub mod db;
16pub mod error;
17// Witness recording (Arc<Mutex>) is host-only; the guest verifies against a witness.
18#[cfg(feature = "std")]
19pub mod logger;
20mod nibbles;
21pub mod node;
22mod node_hash;
23pub mod rkyv_utils;
24mod rlp;
25#[cfg(test)]
26mod test_utils;
27// Parallel merkleization (std threads + crossbeam) is host-only.
28#[cfg(feature = "std")]
29pub mod threadpool;
30mod trie_iter;
31#[cfg(feature = "std")]
32pub mod trie_sorted;
33mod verify_range;
34
35use alloc::collections::BTreeMap;
36use alloc::sync::Arc;
37#[cfg(not(feature = "std"))]
38use alloc::{boxed::Box, vec::Vec};
39use ethereum_types::H256;
40use ethrex_crypto::{Crypto, NativeCrypto};
41use ethrex_rlp::constants::RLP_NULL;
42use ethrex_rlp::encode::RLPEncode;
43
44#[cfg(feature = "std")]
45use rustc_hash::FxHashSet;
46// `FxHashMap` is part of the public API (`get_embedded_root_committed`). Its concrete
47// type is build-dependent, so callers that build this crate `no_std` (e.g. the guest
48// via `ethrex-common`) must name it through this re-export to stay type-compatible.
49#[cfg(feature = "std")]
50pub use rustc_hash::FxHashMap;
51// rustc-hash's map/set aliases require std; use hashbrown with the Fx hasher otherwise.
52#[cfg(not(feature = "std"))]
53pub type FxHashMap<K, V> = hashbrown::HashMap<K, V, rustc_hash::FxBuildHasher>;
54#[cfg(not(feature = "std"))]
55type FxHashSet<K> = hashbrown::HashSet<K, rustc_hash::FxBuildHasher>;
56
57pub use self::db::{InMemoryTrieDB, TrieDB};
58#[cfg(feature = "std")]
59pub use self::logger::{TrieLogger, TrieWitness};
60pub use self::nibbles::Nibbles;
61#[cfg(feature = "std")]
62pub use self::threadpool::ThreadPool;
63pub use self::verify_range::verify_range;
64pub use self::{
65    node::{Node, NodeRef, OnceLock},
66    node_hash::NodeHash,
67};
68
69pub use self::error::{ExtensionNodeErrorData, InconsistentTreeError, TrieError};
70use self::{node::LeafNode, trie_iter::TrieIterator};
71
72use ethrex_rlp::decode::RLPDecode;
73
74/// Hash of an empty trie: `keccak256(RLP_NULL)`, a well-known Ethereum constant.
75/// Hardcoded so it needs no lazy initialization, works in `const` contexts, and
76/// pulls no lazy-cell dependency into `no_std` builds. The
77/// `empty_trie_hash_matches_keccak` test pins it to the computed value.
78pub const EMPTY_TRIE_HASH: H256 = H256([
79    0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e,
80    0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21,
81]);
82
83/// RLP-encoded trie path
84pub type PathRLP = Vec<u8>;
85/// RLP-encoded trie value
86pub type ValueRLP = Vec<u8>;
87/// RLP-encoded trie node
88pub type NodeRLP = Vec<u8>;
89/// Represents a node in the Merkle Patricia Trie.
90pub type TrieNode = (Nibbles, NodeRLP);
91
92/// Ethereum-compatible Merkle Patricia Trie
93pub struct Trie {
94    db: Box<dyn TrieDB>,
95    pub root: NodeRef,
96    pending_removal: FxHashSet<Nibbles>,
97    dirty: FxHashSet<Nibbles>,
98}
99
100// `Default` builds an in-memory (InMemoryTrieDB) trie.
101impl Default for Trie {
102    fn default() -> Self {
103        Self::new_temp()
104    }
105}
106
107impl Trie {
108    /// Creates a new Trie from a clean DB
109    pub fn new(db: Box<dyn TrieDB>) -> Self {
110        Self {
111            db,
112            root: NodeRef::default(),
113            pending_removal: Default::default(),
114            dirty: Default::default(),
115        }
116    }
117
118    /// Creates a trie from an already-initialized DB and sets root as the root node of the trie
119    pub fn open(db: Box<dyn TrieDB>, root: H256) -> Self {
120        Self {
121            db,
122            root: if root != EMPTY_TRIE_HASH {
123                NodeHash::from(root).into()
124            } else {
125                Default::default()
126            },
127            pending_removal: Default::default(),
128            dirty: Default::default(),
129        }
130    }
131
132    /// Return a reference to the internal database.
133    ///
134    /// Warning: All changes made to the db will bypass the trie and may cause the trie to suddenly
135    ///   become inconsistent.
136    pub fn db(&self) -> &dyn TrieDB {
137        self.db.as_ref()
138    }
139
140    /// Retrieve an RLP-encoded value from the trie given its RLP-encoded path.
141    pub fn get(&self, pathrlp: &[u8]) -> Result<Option<ValueRLP>, TrieError> {
142        let path = Nibbles::from_bytes(pathrlp);
143
144        if !self.dirty.contains(&path) && self.db().flatkeyvalue_computed(path.clone()) {
145            let Some(value_rlp) = self.db.get(path)? else {
146                return Ok(None);
147            };
148            if value_rlp.is_empty() {
149                return Ok(None);
150            }
151            return Ok(Some(value_rlp));
152        }
153
154        Ok(match self.root {
155            NodeRef::Node(ref node, _) => node.get(self.db.as_ref(), path)?,
156            NodeRef::Hash(hash) if hash.is_valid() => {
157                Node::decode(&self.db.get(Nibbles::default())?.ok_or_else(|| {
158                    TrieError::InconsistentTree(Box::new(InconsistentTreeError::RootNotFound(
159                        hash.finalize(&NativeCrypto),
160                    )))
161                })?)
162                .map_err(TrieError::RLPDecode)?
163                .get(self.db.as_ref(), path)?
164            }
165            _ => None,
166        })
167    }
168
169    /// Insert an RLP-encoded value into the trie.
170    pub fn insert(&mut self, path: PathRLP, value: ValueRLP) -> Result<(), TrieError> {
171        let path = Nibbles::from_bytes(&path);
172        self.pending_removal.remove(&path);
173        self.dirty.insert(path.clone());
174
175        if self.root.is_valid() {
176            // If the trie is not empty, call the root node's insertion logic.
177            self.root
178                .get_node_mut(self.db.as_ref(), Nibbles::default())?
179                .ok_or_else(|| {
180                    TrieError::InconsistentTree(Box::new(InconsistentTreeError::RootNotFoundNoHash))
181                })?
182                .insert(self.db.as_ref(), path, value)?
183        } else {
184            // If the trie is empty, just add a leaf.
185            self.root = Node::from(LeafNode::new(path, value)).into()
186        };
187        self.root.clear_hash();
188
189        Ok(())
190    }
191
192    /// Pre-resolves, via breadth-first batched reads, every trie node that the
193    /// upcoming serial `insert`/`remove` loop over `sorted_paths` would
194    /// otherwise resolve one at a time (one `db.get` per level per key).
195    ///
196    /// Nodes are installed into the in-memory arena exactly the way lazy
197    /// resolution does it (see [`NodeRef::get_node_mut`]): the decoded node
198    /// replaces the `NodeRef::Hash` with a `NodeRef::Node` that keeps the SAME
199    /// memoized hash (`OnceLock::from(hash)`). This is purely a caching step:
200    /// it never modifies any node's content, never marks anything dirty, and
201    /// is therefore transparent to the resulting root hash and to the
202    /// persisted node set produced by `collect_changes_since_last_hash`
203    /// (verified by the `trie_prefetch` equivalence test). Prefetching extra
204    /// nodes for keys that later diverge during insert is safe for the same
205    /// reason: an unmodified, hash-preserved node is never re-emitted.
206    ///
207    /// No-op if `sorted_paths` is empty or if the trie's root isn't a
208    /// `NodeRef::Hash(NodeHash::Hashed(_))` (empty trie, inline root, or a
209    /// root that's already resolved — nothing left to batch).
210    pub fn prefetch_sorted(&mut self, sorted_paths: &[Nibbles]) -> Result<(), TrieError> {
211        if sorted_paths.is_empty() {
212            return Ok(());
213        }
214        if !matches!(self.root, NodeRef::Hash(NodeHash::Hashed(_))) {
215            return Ok(());
216        }
217
218        // Resolve the root itself first, exactly like the first `insert`
219        // would (a single `db.get`).
220        if self
221            .root
222            .get_node_mut(self.db.as_ref(), Nibbles::default())?
223            .is_none()
224        {
225            // Root hash points to a node that isn't in the DB. Let the real
226            // insert/remove loop hit (and report) this inconsistency;
227            // prefetching can't fix it and shouldn't hide it.
228            return Ok(());
229        }
230
231        let all_indices: Vec<usize> = (0..sorted_paths.len()).collect();
232        // Defensive guard against a malformed/cyclic trie: legitimate paths
233        // are at most 65 nibbles (64 nibbles + leaf terminator) deep.
234        const MAX_LEVELS: usize = 68;
235
236        for _ in 0..MAX_LEVELS {
237            // Clone the root's Arc (cheap refcount bump) so the following
238            // immutable scan doesn't hold a borrow of `self.root`, freeing it
239            // up for the later mutable install pass without any `&mut`
240            // reference held across the `multi_get` call in between.
241            let root_node = match &self.root {
242                NodeRef::Node(node, _) => node.clone(),
243                _ => break,
244            };
245
246            let mut to_fetch: Vec<Nibbles> = Vec::new();
247            collect_prefetch_targets(
248                &root_node,
249                &Nibbles::default(),
250                &all_indices,
251                sorted_paths,
252                &mut to_fetch,
253            );
254            // Release the extra strong ref to the root before the mutable
255            // install pass, so `Arc::make_mut` below sees strong count 1 (the
256            // common single-owner case) and does not clone the resolved path.
257            drop(root_node);
258            if to_fetch.is_empty() {
259                break;
260            }
261
262            let mut results = self.db.multi_get(&to_fetch).into_iter();
263
264            let NodeRef::Node(root_arc, _) = &mut self.root else {
265                break;
266            };
267            let root_mut = Arc::make_mut(root_arc);
268            install_prefetch_targets(
269                root_mut,
270                &Nibbles::default(),
271                &all_indices,
272                sorted_paths,
273                &mut results,
274            )?;
275        }
276
277        Ok(())
278    }
279
280    /// Remove a value from the trie given its RLP-encoded path.
281    /// Returns the value if it was succesfully removed or None if it wasn't part of the trie
282    pub fn remove(&mut self, path: &[u8]) -> Result<Option<ValueRLP>, TrieError> {
283        self.dirty.insert(Nibbles::from_bytes(path));
284        if !self.root.is_valid() {
285            return Ok(None);
286        }
287        self.pending_removal.insert(Nibbles::from_bytes(path));
288
289        // If the trie is not empty, call the root node's removal logic.
290        let (is_trie_empty, value) = self
291            .root
292            .get_node_mut(self.db.as_ref(), Nibbles::default())?
293            .ok_or_else(|| {
294                TrieError::InconsistentTree(Box::new(InconsistentTreeError::RootNotFoundNoHash))
295            })?
296            .remove(self.db.as_ref(), Nibbles::from_bytes(path))?;
297        if is_trie_empty {
298            self.root = NodeRef::default();
299        } else {
300            self.root.clear_hash();
301        }
302
303        Ok(value)
304    }
305
306    /// Return the hash of the trie's root node.
307    /// Returns keccak(RLP_NULL) if the trie is empty
308    /// Also commits changes to the DB
309    pub fn hash(&mut self, crypto: &dyn Crypto) -> Result<H256, TrieError> {
310        self.commit(crypto)?;
311        Ok(self.hash_no_commit(crypto))
312    }
313
314    /// Return the hash of the trie's root node.
315    /// Returns keccak(RLP_NULL) if the trie is empty
316    pub fn hash_no_commit(&self, crypto: &dyn Crypto) -> H256 {
317        if self.root.is_valid() {
318            // 512 is the maximum size of an encoded node
319            let mut buf = Vec::with_capacity(512);
320            self.root
321                .compute_hash_no_alloc(&mut buf, crypto)
322                .finalize(crypto)
323        } else {
324            EMPTY_TRIE_HASH
325        }
326    }
327
328    pub fn get_root_node(&self, path: Nibbles) -> Result<Arc<Node>, TrieError> {
329        self.root
330            .get_node_checked(self.db.as_ref(), path)?
331            .ok_or_else(|| {
332                TrieError::InconsistentTree(Box::new(InconsistentTreeError::RootNotFound(
333                    self.root
334                        .compute_hash(&NativeCrypto)
335                        .finalize(&NativeCrypto),
336                )))
337            })
338    }
339
340    /// Returns a list of changes in a TrieNode format since last root hash processed.
341    ///
342    /// # Returns
343    ///
344    /// A tuple containing the hash and the list of changes.
345    pub fn collect_changes_since_last_hash(
346        &mut self,
347        crypto: &dyn Crypto,
348    ) -> (H256, Vec<TrieNode>) {
349        let updates = self.commit_without_storing(crypto);
350        let ret_hash = self.hash_no_commit(crypto);
351        (ret_hash, updates)
352    }
353
354    /// Compute the hash of the root node and flush any changes into the database.
355    ///
356    /// This method will also compute the hash of all internal nodes indirectly. It will not clear
357    /// the cached nodes.
358    pub fn commit(&mut self, crypto: &dyn Crypto) -> Result<(), TrieError> {
359        let acc = self.commit_without_storing(crypto);
360        self.db.put_batch(acc)?;
361
362        // Commit the underlying transaction
363        self.db.commit()?;
364
365        Ok(())
366    }
367
368    /// Computes the nodes that would be added if updating the trie.
369    /// Nodes are given with their hash pre-calculated.
370    pub fn commit_without_storing(&mut self, crypto: &dyn Crypto) -> Vec<TrieNode> {
371        let mut acc = Vec::new();
372        if self.root.is_valid() {
373            self.root.commit(Nibbles::default(), &mut acc, crypto);
374        }
375        if self.root.compute_hash(crypto) == NodeHash::Hashed(EMPTY_TRIE_HASH) {
376            acc.push((Nibbles::default(), vec![RLP_NULL]))
377        }
378        acc.extend(self.pending_removal.drain().map(|nib| (nib, vec![])));
379
380        acc
381    }
382
383    /// Obtain a merkle proof for the given path.
384    /// The proof will contain all the encoded nodes traversed until reaching the node where the path is stored (including this last node).
385    /// The proof will still be constructed even if the path is not stored in the trie, proving its absence.
386    ///
387    /// Note: This method has a different behavior in regard to non-existent trie root nodes. Normal
388    ///   behavior is to return `Err(InconsistentTrie)`, but this method will return
389    ///   `Ok(Vec::new())` instead.
390    pub fn get_proof(&self, path: &[u8]) -> Result<Vec<NodeRLP>, TrieError> {
391        if self.root.is_valid() {
392            let hash = self.root.compute_hash(&NativeCrypto);
393
394            let mut node_path = Vec::new();
395            if let NodeHash::Inline((data, len)) = hash {
396                node_path.push(data[..len as usize].to_vec());
397            }
398
399            let root = match self
400                .root
401                .get_node_checked(self.db.as_ref(), Nibbles::default())?
402            {
403                Some(x) => x,
404                None => return Ok(Vec::new()),
405            };
406            root.get_path(self.db.as_ref(), Nibbles::from_bytes(path), &mut node_path)?;
407
408            Ok(node_path)
409        } else {
410            Ok(Vec::new())
411        }
412    }
413
414    /// Obtains all encoded nodes traversed until reaching the node where every path is stored.
415    /// The list doesn't include the root node, this is returned separately.
416    /// Will still be constructed even if some path is not stored in the trie.
417    pub fn get_proofs(
418        &self,
419        paths: &[PathRLP],
420    ) -> Result<(Option<NodeRLP>, Vec<NodeRLP>), TrieError> {
421        if self.root.is_valid() {
422            let encoded_root = self.get_root_node(Nibbles::default())?.encode_to_vec();
423
424            let mut node_path: FxHashSet<_> = Default::default();
425            for path in paths {
426                let mut nodes = self.get_proof(path)?;
427                nodes.swap_remove(0);
428                node_path.extend(nodes);
429            }
430
431            Ok((Some(encoded_root), node_path.into_iter().collect()))
432        } else {
433            Ok((None, Vec::new()))
434        }
435    }
436
437    #[cfg(feature = "std")]
438    pub fn empty_in_memory() -> Self {
439        Self::new(Box::new(InMemoryTrieDB::new(Arc::new(
440            std::sync::Mutex::new(BTreeMap::new()),
441        ))))
442    }
443
444    /// Gets node with embedded references to child nodes, all in just one `Node`.
445    pub fn get_embedded_root(
446        all_nodes: &BTreeMap<H256, Node>,
447        root_hash: H256,
448    ) -> Result<NodeRef, TrieError> {
449        // If the root hash is of the empty trie then we can get away by setting the NodeRef to default
450        if root_hash == EMPTY_TRIE_HASH {
451            return Ok(NodeRef::default());
452        }
453
454        let root_rlp = all_nodes.get(&root_hash).ok_or_else(|| {
455            TrieError::InconsistentTree(Box::new(InconsistentTreeError::RootNotFound(root_hash)))
456        })?;
457
458        fn get_embedded_node(
459            all_nodes: &BTreeMap<H256, Node>,
460            cur_node: &Node,
461        ) -> Result<Node, TrieError> {
462            Ok(match cur_node.clone() {
463                Node::Branch(mut node) => {
464                    for choice in &mut node.choices {
465                        let NodeRef::Hash(hash) = *choice else {
466                            continue;
467                        };
468
469                        if hash.is_valid() {
470                            *choice = match all_nodes.get(&hash.finalize(&NativeCrypto)) {
471                                Some(node) => get_embedded_node(all_nodes, node)?.into(),
472                                None => hash.into(),
473                            };
474                        }
475                    }
476
477                    (*node).into()
478                }
479                Node::Extension(mut node) => {
480                    let NodeRef::Hash(hash) = node.child else {
481                        return Ok(node.into());
482                    };
483
484                    node.child = match all_nodes.get(&hash.finalize(&NativeCrypto)) {
485                        Some(node) => get_embedded_node(all_nodes, node)?.into(),
486                        None => hash.into(),
487                    };
488
489                    node.into()
490                }
491                Node::Leaf(node) => node.into(),
492            })
493        }
494
495        let root = get_embedded_node(all_nodes, root_rlp)?;
496        Ok(root.into())
497    }
498
499    /// Gets node with embedded references to child nodes, all in just one `Node`.
500    ///
501    /// Every key in the trie must be `key_nibbles` long, as in the state and
502    /// storage tries, whose keys are 64-nibble keccak256 hashes. A decoded node
503    /// whose path cannot end at that length is rejected, as EELS
504    /// `_validate_secured_trie_paths` does (execution-specs #3193): a leaf path
505    /// must end exactly there, an extension must stop short of it and a branch
506    /// must sit above it. A child referenced only by hash is not in `all_nodes`,
507    /// so it has no decoded path to check. The check runs while embedding
508    /// because a separate walk over every child slot cost the zkVM guest about
509    /// eight times as much.
510    ///
511    /// Note that this method caches the hash of each node, so it assumes the provided `all_nodes` are well-formed.
512    pub fn get_embedded_root_committed(
513        all_nodes: &FxHashMap<H256, Node>,
514        root_hash: H256,
515        crypto: &dyn Crypto,
516        key_nibbles: usize,
517    ) -> Result<NodeRef, TrieError> {
518        // If the root hash is of the empty trie then we can get away by setting the NodeRef to default
519        if root_hash == EMPTY_TRIE_HASH {
520            return Ok(NodeRef::default());
521        }
522
523        let root_rlp = all_nodes.get(&root_hash).ok_or_else(|| {
524            TrieError::InconsistentTree(Box::new(InconsistentTreeError::RootNotFound(root_hash)))
525        })?;
526
527        /// Creates an embedded node reference with its hash slot pre-seeded.
528        ///
529        /// The caller must guarantee that `hash` is the hash of the referenced
530        /// node, for example because the node was just resolved by looking that
531        /// hash up. Seeding lets later hash computations over the subtree reuse
532        /// the known value instead of re-encoding and re-hashing it.
533        fn node_with_hash(node: Node, hash: NodeHash) -> NodeRef {
534            NodeRef::Node(Arc::new(node), OnceLock::from(hash))
535        }
536
537        /// Key nibbles a leaf spells. A decoded leaf path ends with the 16
538        /// terminator, which is not a key nibble.
539        fn leaf_path_len(leaf: &LeafNode) -> usize {
540            leaf.partial.len() - usize::from(leaf.partial.is_leaf())
541        }
542
543        /// Checks the paths of a child stored inline. A node under 32 bytes is
544        /// part of its parent's encoding rather than referenced by hash, so it
545        /// is never in `all_nodes` and embedding leaves it encoded. Its own
546        /// children are inline too, since a hash reference alone takes 33 bytes.
547        #[cold]
548        fn check_inline_paths(encoded: &NodeHash, remaining: usize) -> Result<(), TrieError> {
549            match Node::decode(encoded.as_ref())? {
550                Node::Leaf(leaf) => {
551                    if leaf_path_len(&leaf) != remaining {
552                        return Err(TrieError::KeyLengthMismatch);
553                    }
554                }
555                Node::Extension(ext) => {
556                    if ext.prefix.len() >= remaining {
557                        return Err(TrieError::KeyLengthMismatch);
558                    }
559                    if let NodeRef::Hash(child @ NodeHash::Inline(_)) = ext.child
560                        && child.is_valid()
561                    {
562                        check_inline_paths(&child, remaining - ext.prefix.len())?;
563                    }
564                }
565                Node::Branch(branch) => {
566                    if remaining == 0 {
567                        return Err(TrieError::KeyLengthMismatch);
568                    }
569                    for choice in &branch.choices {
570                        if let NodeRef::Hash(child @ NodeHash::Inline(_)) = *choice
571                            && child.is_valid()
572                        {
573                            check_inline_paths(&child, remaining - 1)?;
574                        }
575                    }
576                }
577            }
578            Ok(())
579        }
580
581        fn get_embedded_node_committed(
582            all_nodes: &FxHashMap<H256, Node>,
583            cur_node: &Node,
584            remaining: usize,
585            crypto: &dyn Crypto,
586        ) -> Result<Node, TrieError> {
587            Ok(match cur_node.clone() {
588                Node::Branch(mut node) => {
589                    if remaining == 0 {
590                        return Err(TrieError::KeyLengthMismatch);
591                    }
592                    for choice in &mut node.choices {
593                        let NodeRef::Hash(hash) = *choice else {
594                            continue;
595                        };
596
597                        if hash.is_valid() {
598                            *choice = match all_nodes.get(&hash.finalize(crypto)) {
599                                Some(node) => node_with_hash(
600                                    get_embedded_node_committed(
601                                        all_nodes,
602                                        node,
603                                        remaining - 1,
604                                        crypto,
605                                    )?,
606                                    hash,
607                                ),
608                                None => {
609                                    // Testing the variant first keeps the common
610                                    // case, a sibling outside the witness, to a compare.
611                                    if let NodeHash::Inline(_) = hash {
612                                        check_inline_paths(&hash, remaining - 1)?;
613                                    }
614                                    hash.into()
615                                }
616                            };
617                        }
618                    }
619
620                    (*node).into()
621                }
622                Node::Extension(mut node) => {
623                    if node.prefix.len() >= remaining {
624                        return Err(TrieError::KeyLengthMismatch);
625                    }
626                    let remaining = remaining - node.prefix.len();
627                    let NodeRef::Hash(hash) = node.child else {
628                        return Ok(node.into());
629                    };
630
631                    node.child = match all_nodes.get(&hash.finalize(crypto)) {
632                        Some(node) => node_with_hash(
633                            get_embedded_node_committed(all_nodes, node, remaining, crypto)?,
634                            hash,
635                        ),
636                        None => {
637                            if let NodeHash::Inline(_) = hash
638                                && hash.is_valid()
639                            {
640                                check_inline_paths(&hash, remaining)?;
641                            }
642                            hash.into()
643                        }
644                    };
645
646                    node.into()
647                }
648                Node::Leaf(node) => {
649                    if leaf_path_len(&node) != remaining {
650                        return Err(TrieError::KeyLengthMismatch);
651                    }
652                    node.into()
653                }
654            })
655        }
656
657        let root = get_embedded_node_committed(all_nodes, root_rlp, key_nibbles, crypto)?;
658        Ok(node_with_hash(root, NodeHash::Hashed(root_hash)))
659    }
660
661    /// Builds a trie from a set of nodes with an empty InMemoryTrieDB as a backend because the nodes are embedded in the root.
662    ///
663    /// Note: This method will not ensure that all node references are valid. Invalid references
664    ///   will cause other methods (including, but not limited to `Trie::get`, `Trie::insert` and
665    ///   `Trie::remove`) to return `Err(InconsistentTrie)`.
666    /// Note: This method will ignore any dangling nodes. All nodes that are not accessible from the
667    ///   root node are considered dangling.
668    #[cfg(feature = "std")]
669    pub fn from_nodes(
670        root_hash: H256,
671        state_nodes: &BTreeMap<H256, Node>,
672    ) -> Result<Self, TrieError> {
673        let mut trie = Trie::new(Box::new(InMemoryTrieDB::default()));
674        let root = Self::get_embedded_root(state_nodes, root_hash)?;
675        trie.root = root;
676
677        Ok(trie)
678    }
679
680    /// Builds an in-memory trie from the given elements and returns its hash
681    pub fn compute_hash_from_unsorted_iter(
682        iter: impl Iterator<Item = (PathRLP, ValueRLP)>,
683        crypto: &dyn Crypto,
684    ) -> H256 {
685        let mut trie = Trie::stateless();
686        for (path, value) in iter {
687            // Unwraping here won't panic as our in_memory trie DB won't fail
688            trie.insert(path, value).unwrap();
689        }
690
691        trie.hash_no_commit(crypto)
692    }
693
694    /// Creates a new stateless trie. This trie won't be able to store any nodes so all data will be lost after calculating the hash
695    /// Only use it for proof verification or computing a hash from an iterator
696    pub(crate) fn stateless() -> Trie {
697        // We will only be using the trie's cache so we don't need a working DB
698        struct NullTrieDB;
699
700        impl TrieDB for NullTrieDB {
701            fn get(&self, _key: Nibbles) -> Result<Option<Vec<u8>>, TrieError> {
702                Ok(None)
703            }
704
705            fn put_batch(&self, _key_values: Vec<TrieNode>) -> Result<(), TrieError> {
706                Ok(())
707            }
708        }
709
710        Trie::new(Box::new(NullTrieDB))
711    }
712
713    /// Obtain the encoded node given its path.
714    /// Allows usage of full paths (byte slice of 32 bytes) or compact-encoded nibble slices (with length lower than 32)
715    pub fn get_node(&self, partial_path: &PathRLP) -> Result<Vec<u8>, TrieError> {
716        // Convert compact-encoded nibbles into a byte slice if necessary
717        let partial_path = match partial_path.len() {
718            // Compact-encoded nibbles
719            n if n < 32 => Nibbles::decode_compact(partial_path),
720            // Full path (No conversion needed)
721            32 => Nibbles::from_bytes(partial_path),
722            // We won't handle paths with length over 32
723            _ => return Ok(vec![]),
724        };
725
726        fn get_node_inner(
727            db: &dyn TrieDB,
728            current_path: Nibbles,
729            node: &Node,
730            mut partial_path: Nibbles,
731        ) -> Result<Vec<u8>, TrieError> {
732            // If we reached the end of the partial path, return the current node
733            if partial_path.is_empty() {
734                return Ok(node.encode_to_vec());
735            }
736            match node {
737                Node::Branch(branch_node) => match partial_path.next_choice() {
738                    Some(idx) => {
739                        let child_ref = &branch_node.choices[idx];
740                        if child_ref.is_valid() {
741                            let child_path = current_path.append_new(idx as u8);
742                            let child_node = child_ref
743                                .get_node_checked(db, child_path.clone())?
744                                .ok_or_else(|| {
745                                    TrieError::InconsistentTree(Box::new(
746                                        InconsistentTreeError::NodeNotFoundOnBranchNode(
747                                            child_ref
748                                                .compute_hash(&NativeCrypto)
749                                                .finalize(&NativeCrypto),
750                                            branch_node
751                                                .compute_hash(&NativeCrypto)
752                                                .finalize(&NativeCrypto),
753                                            child_path.clone(),
754                                        ),
755                                    ))
756                                })?;
757                            get_node_inner(db, child_path, &child_node, partial_path)
758                        } else {
759                            Ok(vec![])
760                        }
761                    }
762                    _ => Ok(vec![]),
763                },
764                Node::Extension(extension_node) => {
765                    if partial_path.skip_prefix(&extension_node.prefix)
766                        && extension_node.child.is_valid()
767                    {
768                        let child_path = partial_path.concat(&extension_node.prefix);
769                        let child_node = extension_node
770                            .child
771                            .get_node_checked(db, child_path.clone())?
772                            .ok_or_else(|| {
773                                TrieError::InconsistentTree(Box::new(
774                                    InconsistentTreeError::ExtensionNodeChildNotFound(
775                                        ExtensionNodeErrorData {
776                                            node_hash: extension_node
777                                                .child
778                                                .compute_hash(&NativeCrypto)
779                                                .finalize(&NativeCrypto),
780                                            extension_node_hash: extension_node
781                                                .compute_hash(&NativeCrypto)
782                                                .finalize(&NativeCrypto),
783                                            extension_node_prefix: extension_node.prefix.clone(),
784                                            node_path: child_path.clone(),
785                                        },
786                                    ),
787                                ))
788                            })?;
789                        get_node_inner(db, child_path, &child_node, partial_path)
790                    } else {
791                        Ok(vec![])
792                    }
793                }
794                Node::Leaf(_) => Ok(vec![]),
795            }
796        }
797
798        // Fetch node
799        if self.root.is_valid() {
800            let root_node = self.get_root_node(Default::default())?;
801            get_node_inner(
802                self.db.as_ref(),
803                Default::default(),
804                &root_node,
805                partial_path,
806            )
807        } else {
808            Ok(Vec::new())
809        }
810    }
811
812    pub fn root_node(&self) -> Result<Option<Arc<Node>>, TrieError> {
813        if self.root.is_valid() {
814            self.root.get_node(self.db.as_ref(), Nibbles::default())
815        } else {
816            Ok(None)
817        }
818    }
819
820    /// Creates a new Trie based on a temporary InMemory DB
821    pub fn new_temp() -> Self {
822        let db = InMemoryTrieDB::new(Default::default());
823        Trie::new(Box::new(db))
824    }
825
826    /// Creates a new Trie based on a temporary InMemory DB, with a specified root
827    ///
828    /// This is usually used to create a Trie from a root that was embedded with the rest of the nodes.
829    pub fn new_temp_with_root(root: NodeRef) -> Self {
830        let db = InMemoryTrieDB::new(Default::default());
831        let mut trie = Trie::new(Box::new(db));
832        trie.root = root;
833        trie
834    }
835
836    /// Validates that the Trie isn't missing any nodes expected in the branches
837    ///
838    /// This is used internally with debug assertions to check the status of the trie
839    /// after syncing operations.
840    /// Note: this operation validates the hashes because the iterator uses
841    /// get_node_checked. We shouldn't downgrade that to the unchecked version
842    pub fn validate(self) -> Result<(), TrieError> {
843        let mut expected_count = if self.root.is_valid() { 1 } else { 0 };
844        for (_, node) in self.into_iter() {
845            expected_count -= 1;
846            match node {
847                Node::Branch(branch_node) => {
848                    expected_count += branch_node
849                        .choices
850                        .iter()
851                        .filter(|child| child.is_valid())
852                        .count();
853                }
854                Node::Extension(_) => {
855                    expected_count += 1;
856                }
857                Node::Leaf(_) => {}
858            }
859        }
860        if expected_count != 0 {
861            return Err(TrieError::Verify(format!(
862                "Node count mismatch, expected {expected_count} more"
863            )));
864        }
865        Ok(())
866    }
867
868    /// Validate the trie structure in parallel by splitting at the root branch node.
869    /// Each of the root's 16 subtrees is validated independently using rayon.
870    #[cfg(feature = "std")]
871    pub fn validate_parallel(self) -> Result<(), TrieError> {
872        use rayon::prelude::*;
873
874        if !self.root.is_valid() {
875            return Ok(());
876        }
877
878        let db = &*self.db;
879        let root_node = self
880            .root
881            .get_node_checked(db, Nibbles::default())?
882            .ok_or_else(|| TrieError::Verify("Root node not found".to_string()))?;
883
884        match &*root_node {
885            Node::Branch(branch_node) => {
886                let children: Vec<(Nibbles, NodeRef)> = branch_node
887                    .choices
888                    .iter()
889                    .enumerate()
890                    .filter(|(_, child)| child.is_valid())
891                    .map(|(i, child)| {
892                        let path = Nibbles::default().append_new(i as u8);
893                        (path, child.clone())
894                    })
895                    .collect();
896
897                children.par_iter().try_for_each(|(start_path, start_ref)| {
898                    validate_subtree(db, start_path.clone(), start_ref.clone())
899                })
900            }
901            _ => {
902                // Non-branch root (rare): validate sequentially
903                validate_subtree(db, Nibbles::default(), self.root.clone())
904            }
905        }
906    }
907}
908
909/// Immutable BFS-boundary scan used by [`Trie::prefetch_sorted`]: given an
910/// already-resolved node and the set of key indices routed to it, finds every
911/// `NodeRef::Hash` child that lies on the path of at least one of those keys,
912/// stopping the recursion at the first unresolved node in each branch
913/// (already-resolved descendants, if any, are explored further in the same
914/// call). Mirrors the descent performed by `Node::get`/`BranchNode::insert`/
915/// `ExtensionNode::insert`.
916fn collect_prefetch_targets(
917    node: &Node,
918    path: &Nibbles,
919    key_indices: &[usize],
920    sorted_paths: &[Nibbles],
921    out: &mut Vec<Nibbles>,
922) {
923    match node {
924        Node::Branch(branch) => {
925            let depth = path.len();
926            let mut buckets: [Vec<usize>; 16] = core::array::from_fn(|_| Vec::new());
927            for &i in key_indices {
928                let p = sorted_paths[i].as_ref();
929                if depth >= p.len() {
930                    continue;
931                }
932                let nibble = p[depth];
933                if nibble < 16 {
934                    buckets[nibble as usize].push(i);
935                }
936            }
937            for (nibble, indices) in buckets.iter().enumerate() {
938                if indices.is_empty() {
939                    continue;
940                }
941                let child_path = path.append_new(nibble as u8);
942                match &branch.choices[nibble] {
943                    NodeRef::Hash(NodeHash::Hashed(_)) => out.push(child_path),
944                    NodeRef::Node(child, _) => {
945                        collect_prefetch_targets(child, &child_path, indices, sorted_paths, out)
946                    }
947                    // Inline (embedded, no separate disk node) or invalid/empty: nothing to fetch.
948                    _ => {}
949                }
950            }
951        }
952        Node::Extension(ext) => {
953            let depth = path.len();
954            let prefix = ext.prefix.as_ref();
955            let matched: Vec<usize> = key_indices
956                .iter()
957                .copied()
958                .filter(|&i| {
959                    let p = sorted_paths[i].as_ref();
960                    depth + prefix.len() <= p.len() && &p[depth..depth + prefix.len()] == prefix
961                })
962                .collect();
963            if matched.is_empty() {
964                // No key continues through this prefix: they diverge and will
965                // cause the extension to be restructured on insert; nothing
966                // to prefetch here.
967                return;
968            }
969            let child_path = path.concat(&ext.prefix);
970            match &ext.child {
971                NodeRef::Hash(NodeHash::Hashed(_)) => out.push(child_path),
972                NodeRef::Node(child, _) => {
973                    collect_prefetch_targets(child, &child_path, &matched, sorted_paths, out)
974                }
975                _ => {}
976            }
977        }
978        // Terminal: leaves have no children to prefetch.
979        Node::Leaf(_) => {}
980    }
981}
982
983/// Mutable counterpart to [`collect_prefetch_targets`] used by
984/// [`Trie::prefetch_sorted`]: repeats the identical descent/routing so it
985/// visits `NodeRef::Hash` children in the exact same order, installing the
986/// corresponding (same-order) `multi_get` result into the arena
987/// hash-preservingly, exactly as `NodeRef::get_node_mut` installs a single
988/// resolved node. On a `None`/empty result the ref is left untouched (absent
989/// path); the subsequent `insert` will create it.
990fn install_prefetch_targets(
991    node: &mut Node,
992    path: &Nibbles,
993    key_indices: &[usize],
994    sorted_paths: &[Nibbles],
995    results: &mut alloc::vec::IntoIter<Result<Option<Vec<u8>>, TrieError>>,
996) -> Result<(), TrieError> {
997    match node {
998        Node::Branch(branch) => {
999            let depth = path.len();
1000            let mut buckets: [Vec<usize>; 16] = core::array::from_fn(|_| Vec::new());
1001            for &i in key_indices {
1002                let p = sorted_paths[i].as_ref();
1003                if depth >= p.len() {
1004                    continue;
1005                }
1006                let nibble = p[depth];
1007                if nibble < 16 {
1008                    buckets[nibble as usize].push(i);
1009                }
1010            }
1011            for (nibble, indices) in buckets.iter().enumerate() {
1012                if indices.is_empty() {
1013                    continue;
1014                }
1015                let child_path = path.append_new(nibble as u8);
1016                let slot = &mut branch.choices[nibble];
1017                match slot {
1018                    NodeRef::Hash(hash @ NodeHash::Hashed(_)) => {
1019                        let hash = *hash;
1020                        let bytes = results.next().ok_or_else(|| {
1021                            TrieError::DbError(anyhow::anyhow!(
1022                                "prefetch_sorted: multi_get returned fewer results than requested"
1023                            ))
1024                        })??;
1025                        if let Some(bytes) = bytes.filter(|b| !b.is_empty()) {
1026                            let decoded = Node::decode(&bytes).map_err(TrieError::RLPDecode)?;
1027                            *slot = NodeRef::Node(Arc::new(decoded), OnceLock::from(hash));
1028                        }
1029                    }
1030                    NodeRef::Node(child, _) => {
1031                        let child_mut = Arc::make_mut(child);
1032                        install_prefetch_targets(
1033                            child_mut,
1034                            &child_path,
1035                            indices,
1036                            sorted_paths,
1037                            results,
1038                        )?;
1039                    }
1040                    _ => {}
1041                }
1042            }
1043        }
1044        Node::Extension(ext) => {
1045            let depth = path.len();
1046            let prefix = ext.prefix.as_ref();
1047            let matched: Vec<usize> = key_indices
1048                .iter()
1049                .copied()
1050                .filter(|&i| {
1051                    let p = sorted_paths[i].as_ref();
1052                    depth + prefix.len() <= p.len() && &p[depth..depth + prefix.len()] == prefix
1053                })
1054                .collect();
1055            if matched.is_empty() {
1056                return Ok(());
1057            }
1058            let child_path = path.concat(&ext.prefix);
1059            let slot = &mut ext.child;
1060            match slot {
1061                NodeRef::Hash(hash @ NodeHash::Hashed(_)) => {
1062                    let hash = *hash;
1063                    let bytes = results.next().ok_or_else(|| {
1064                        TrieError::DbError(anyhow::anyhow!(
1065                            "prefetch_sorted: multi_get returned fewer results than requested"
1066                        ))
1067                    })??;
1068                    if let Some(bytes) = bytes.filter(|b| !b.is_empty()) {
1069                        let decoded = Node::decode(&bytes).map_err(TrieError::RLPDecode)?;
1070                        *slot = NodeRef::Node(Arc::new(decoded), OnceLock::from(hash));
1071                    }
1072                }
1073                NodeRef::Node(child, _) => {
1074                    let child_mut = Arc::make_mut(child);
1075                    install_prefetch_targets(
1076                        child_mut,
1077                        &child_path,
1078                        &matched,
1079                        sorted_paths,
1080                        results,
1081                    )?;
1082                }
1083                _ => {}
1084            }
1085        }
1086        Node::Leaf(_) => {}
1087    }
1088    Ok(())
1089}
1090
1091/// Validate a subtree rooted at `start_ref`, checking that all referenced nodes exist
1092/// and their hashes match.
1093#[cfg(feature = "std")]
1094fn validate_subtree(
1095    db: &dyn TrieDB,
1096    start_path: Nibbles,
1097    start_ref: NodeRef,
1098) -> Result<(), TrieError> {
1099    let mut expected_count: isize = 1;
1100    let mut stack = vec![(start_path, start_ref)];
1101
1102    while let Some((path, node_ref)) = stack.pop() {
1103        let node = node_ref
1104            .get_node_checked(db, path.clone())?
1105            .ok_or_else(|| TrieError::Verify(format!("Missing node at path {path:?}")))?;
1106
1107        expected_count -= 1;
1108        match &*node {
1109            Node::Branch(branch) => {
1110                for (choice, child) in branch.choices.iter().enumerate().rev() {
1111                    if child.is_valid() {
1112                        expected_count += 1;
1113                        stack.push((path.append_new(choice as u8), child.clone()));
1114                    }
1115                }
1116            }
1117            Node::Extension(ext) => {
1118                expected_count += 1;
1119                stack.push((path.concat(&ext.prefix), ext.child.clone()));
1120            }
1121            Node::Leaf(_) => {}
1122        }
1123    }
1124
1125    if expected_count != 0 {
1126        return Err(TrieError::Verify(format!(
1127            "Node count mismatch in subtree, expected {expected_count} more"
1128        )));
1129    }
1130    Ok(())
1131}
1132
1133impl IntoIterator for Trie {
1134    type Item = (Nibbles, Node);
1135
1136    type IntoIter = TrieIterator;
1137
1138    fn into_iter(self) -> Self::IntoIter {
1139        TrieIterator::new(self)
1140    }
1141}
1142
1143pub struct ProofTrie(Trie);
1144
1145impl ProofTrie {
1146    pub fn insert(
1147        &mut self,
1148        partial_path: Nibbles,
1149        external_ref: NodeHash,
1150    ) -> Result<(), TrieError> {
1151        if self.0.root.is_valid() {
1152            // If the trie is not empty, call the root node's insertion logic.
1153            self.0
1154                .root
1155                .get_node_mut(self.0.db.as_ref(), Nibbles::default())?
1156                .ok_or_else(|| {
1157                    TrieError::InconsistentTree(Box::new(InconsistentTreeError::RootNotFoundNoHash))
1158                })?
1159                .insert(self.0.db.as_ref(), partial_path, external_ref)?;
1160            self.0.root.clear_hash();
1161        } else {
1162            self.0.root = external_ref.into();
1163        };
1164
1165        Ok(())
1166    }
1167
1168    pub fn hash(&self, crypto: &dyn Crypto) -> H256 {
1169        self.0.hash_no_commit(crypto)
1170    }
1171}
1172
1173impl From<Trie> for ProofTrie {
1174    fn from(value: Trie) -> Self {
1175        Self(value)
1176    }
1177}
1178
1179#[cfg(test)]
1180mod tests {
1181    use super::*;
1182    use ethrex_crypto::keccak::keccak_hash;
1183
1184    // Pins the hardcoded `EMPTY_TRIE_HASH` to `keccak256(RLP_NULL)` so a typo in the
1185    // byte literal can't silently diverge from the computed value.
1186    #[test]
1187    fn empty_trie_hash_matches_keccak() {
1188        assert_eq!(EMPTY_TRIE_HASH, H256(keccak_hash([RLP_NULL])));
1189    }
1190
1191    mod embedded_key_length {
1192        use super::*;
1193        use crate::node::{BranchNode, ExtensionNode};
1194
1195        /// A leaf spelling `path_nibbles` key nibbles. A 32-byte value keeps
1196        /// the encoding at 32 bytes or more, so a parent references it by hash;
1197        /// a 1-byte value keeps a short leaf under 32 bytes, so a parent stores
1198        /// it inline.
1199        fn leaf(path_nibbles: usize, value_len: usize) -> Node {
1200            let mut partial = vec![0; path_nibbles];
1201            partial.push(16);
1202            LeafNode {
1203                partial: Nibbles::from_hex(partial),
1204                value: vec![1; value_len],
1205            }
1206            .into()
1207        }
1208
1209        fn branch_over(child: &Node) -> Node {
1210            let mut choices: [NodeRef; 16] = Default::default();
1211            choices[0] = child.compute_hash(&NativeCrypto).into();
1212            BranchNode {
1213                choices,
1214                value: vec![],
1215            }
1216            .into()
1217        }
1218
1219        fn extension_over(prefix_nibbles: usize, child: &Node) -> Node {
1220            ExtensionNode {
1221                prefix: Nibbles::from_hex(vec![0; prefix_nibbles]),
1222                child: child.compute_hash(&NativeCrypto).into(),
1223            }
1224            .into()
1225        }
1226
1227        /// Embeds `root` out of a witness-style map holding it and `rest`, each
1228        /// decoded from its encoding and keyed by the hash of that encoding.
1229        fn embed(root: &Node, rest: &[&Node], key_nibbles: usize) -> Result<NodeRef, TrieError> {
1230            let mut nodes = FxHashMap::default();
1231            for node in core::iter::once(root).chain(rest.iter().copied()) {
1232                let encoded = node.encode_to_vec();
1233                nodes.insert(
1234                    H256(keccak_hash(&encoded)),
1235                    Node::decode(&encoded).expect("node decodes"),
1236                );
1237            }
1238            let root_hash = H256(keccak_hash(root.encode_to_vec()));
1239            Trie::get_embedded_root_committed(&nodes, root_hash, &NativeCrypto, key_nibbles)
1240        }
1241
1242        #[test]
1243        fn leaf_paths_must_end_at_the_key_length() {
1244            assert!(embed(&leaf(64, 32), &[], 64).is_ok());
1245            assert!(embed(&leaf(63, 32), &[], 64).is_err());
1246            assert!(embed(&leaf(67, 32), &[], 64).is_err());
1247        }
1248
1249        #[test]
1250        fn branches_and_extensions_consume_key_nibbles() {
1251            let fits = leaf(63, 32);
1252            assert!(embed(&branch_over(&fits), &[&fits], 64).is_ok());
1253            let too_long = leaf(64, 32);
1254            assert!(embed(&branch_over(&too_long), &[&too_long], 64).is_err());
1255
1256            let fits = leaf(61, 32);
1257            assert!(embed(&extension_over(3, &fits), &[&fits], 64).is_ok());
1258            let too_long = leaf(62, 32);
1259            assert!(embed(&extension_over(3, &too_long), &[&too_long], 64).is_err());
1260            let empty = leaf(0, 32);
1261            assert!(embed(&extension_over(64, &empty), &[&empty], 64).is_err());
1262
1263            // With 1-nibble keys the inner branch has no nibble left to branch on.
1264            let bottom = leaf(0, 32);
1265            let inner = branch_over(&bottom);
1266            assert!(embed(&branch_over(&inner), &[&inner, &bottom], 1).is_err());
1267        }
1268
1269        /// Inline children never appear in the witness on their own, so they
1270        /// take a separate path through the check.
1271        #[test]
1272        fn inline_children_are_checked() {
1273            let root = branch_over(&leaf(3, 1));
1274            let embedded = embed(&root, &[], 4).expect("a 4-nibble path fits");
1275            let NodeRef::Node(node, _) = embedded else {
1276                panic!("root was not embedded");
1277            };
1278            let Node::Branch(branch) = &*node else {
1279                panic!("root is not a branch");
1280            };
1281            assert!(
1282                matches!(branch.choices[0], NodeRef::Hash(NodeHash::Inline(_))),
1283                "the test needs the leaf stored inline"
1284            );
1285            assert!(embed(&branch_over(&leaf(4, 1)), &[], 4).is_err());
1286
1287            // An inline branch holding an inline leaf.
1288            assert!(embed(&branch_over(&branch_over(&leaf(2, 1))), &[], 4).is_ok());
1289            assert!(embed(&branch_over(&branch_over(&leaf(3, 1))), &[], 4).is_err());
1290        }
1291    }
1292}