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