1#![cfg_attr(not(feature = "std"), no_std)]
2#![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#[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#[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#[cfg(feature = "std")]
50pub use rustc_hash::FxHashMap;
51#[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
74pub 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
83pub type PathRLP = Vec<u8>;
85pub type ValueRLP = Vec<u8>;
87pub type NodeRLP = Vec<u8>;
89pub type TrieNode = (Nibbles, NodeRLP);
91
92pub struct Trie {
94 db: Box<dyn TrieDB>,
95 pub root: NodeRef,
96 pending_removal: FxHashSet<Nibbles>,
97 dirty: FxHashSet<Nibbles>,
98}
99
100impl Default for Trie {
102 fn default() -> Self {
103 Self::new_temp()
104 }
105}
106
107impl Trie {
108 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 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 pub fn db(&self) -> &dyn TrieDB {
137 self.db.as_ref()
138 }
139
140 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 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 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 self.root = Node::from(LeafNode::new(path, value)).into()
186 };
187 self.root.clear_hash();
188
189 Ok(())
190 }
191
192 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 if self
221 .root
222 .get_node_mut(self.db.as_ref(), Nibbles::default())?
223 .is_none()
224 {
225 return Ok(());
229 }
230
231 let all_indices: Vec<usize> = (0..sorted_paths.len()).collect();
232 const MAX_LEVELS: usize = 68;
235
236 for _ in 0..MAX_LEVELS {
237 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 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 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 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 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 pub fn hash_no_commit(&self, crypto: &dyn Crypto) -> H256 {
317 if self.root.is_valid() {
318 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 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 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 self.db.commit()?;
364
365 Ok(())
366 }
367
368 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 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 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 pub fn get_embedded_root(
446 all_nodes: &BTreeMap<H256, Node>,
447 root_hash: H256,
448 ) -> Result<NodeRef, TrieError> {
449 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 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 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 fn node_with_hash(node: Node, hash: NodeHash) -> NodeRef {
534 NodeRef::Node(Arc::new(node), OnceLock::from(hash))
535 }
536
537 fn leaf_path_len(leaf: &LeafNode) -> usize {
540 leaf.partial.len() - usize::from(leaf.partial.is_leaf())
541 }
542
543 #[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 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 #[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 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 trie.insert(path, value).unwrap();
689 }
690
691 trie.hash_no_commit(crypto)
692 }
693
694 pub(crate) fn stateless() -> Trie {
697 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 pub fn get_node(&self, partial_path: &PathRLP) -> Result<Vec<u8>, TrieError> {
716 let partial_path = match partial_path.len() {
718 n if n < 32 => Nibbles::decode_compact(partial_path),
720 32 => Nibbles::from_bytes(partial_path),
722 _ => 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 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 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 pub fn new_temp() -> Self {
822 let db = InMemoryTrieDB::new(Default::default());
823 Trie::new(Box::new(db))
824 }
825
826 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 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 #[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 validate_subtree(db, Nibbles::default(), self.root.clone())
904 }
905 }
906 }
907}
908
909fn 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 _ => {}
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 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 Node::Leaf(_) => {}
980 }
981}
982
983fn 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#[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 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 #[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 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 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 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 #[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 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}