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::{
71 node::{BranchNode, ExtensionNode, LeafNode},
72 trie_iter::TrieIterator,
73};
74
75use ethrex_rlp::decode::RLPDecode;
76
77pub 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
86pub type PathRLP = Vec<u8>;
88pub type ValueRLP = Vec<u8>;
90pub type NodeRLP = Vec<u8>;
92pub type TrieNode = (Nibbles, NodeRLP);
94
95pub struct Trie {
97 db: Box<dyn TrieDB>,
98 pub root: NodeRef,
99 pending_removal: FxHashSet<Nibbles>,
100 dirty: FxHashSet<Nibbles>,
101}
102
103impl Default for Trie {
105 fn default() -> Self {
106 Self::new_temp()
107 }
108}
109
110impl Trie {
111 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 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 pub fn db(&self) -> &dyn TrieDB {
140 self.db.as_ref()
141 }
142
143 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 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 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 self.root = Node::from(LeafNode::new(path, value)).into()
189 };
190 self.root.clear_hash();
191
192 Ok(())
193 }
194
195 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 if self
224 .root
225 .get_node_mut(self.db.as_ref(), Nibbles::default())?
226 .is_none()
227 {
228 return Ok(());
232 }
233
234 let all_indices: Vec<usize> = (0..sorted_paths.len()).collect();
235 const MAX_LEVELS: usize = 68;
238
239 for _ in 0..MAX_LEVELS {
240 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 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 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 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 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 pub fn hash_no_commit(&self, crypto: &(impl Crypto + ?Sized)) -> H256 {
320 if self.root.is_valid() {
321 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 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 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 self.db.commit()?;
367
368 Ok(())
369 }
370
371 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 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 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 pub fn get_embedded_root(
449 all_nodes: &BTreeMap<H256, Node>,
450 root_hash: H256,
451 ) -> Result<NodeRef, TrieError> {
452 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 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 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 fn node_with_hash(node: Node, hash: NodeHash) -> NodeRef {
550 NodeRef::Node(Arc::new(node), OnceLock::from(hash))
551 }
552
553 fn leaf_path_len(leaf: &LeafNode) -> usize {
556 leaf.partial.len() - usize::from(leaf.partial.is_leaf())
557 }
558
559 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 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 #[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 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 #[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 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 trie.insert(path, value).unwrap();
739 }
740
741 trie.hash_no_commit(crypto)
742 }
743
744 pub(crate) fn stateless() -> Trie {
747 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 pub fn get_node(&self, partial_path: &PathRLP) -> Result<Vec<u8>, TrieError> {
766 let partial_path = match partial_path.len() {
768 n if n < 32 => Nibbles::decode_compact(partial_path),
770 32 => Nibbles::from_bytes(partial_path),
772 _ => 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 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 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 pub fn new_temp() -> Self {
872 let db = InMemoryTrieDB::new(Default::default());
873 Trie::new(Box::new(db))
874 }
875
876 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 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 #[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 validate_subtree(db, Nibbles::default(), self.root.clone())
954 }
955 }
956 }
957}
958
959fn 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 _ => {}
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 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 Node::Leaf(_) => {}
1030 }
1031}
1032
1033fn 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#[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 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 #[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 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 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 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 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 #[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 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}