reth_trie_sparse/traits.rs
1//! Traits for sparse trie implementations.
2
3use core::fmt::Debug;
4
5use alloc::{borrow::Cow, vec::Vec};
6use alloy_primitives::{
7 map::{B256Map, HashMap, HashSet},
8 B256,
9};
10use alloy_trie::BranchNodeCompact;
11use reth_execution_errors::SparseTrieResult;
12use reth_trie_common::{
13 BranchNodeMasks, Nibbles, ProofTrieNodeV2, ProofV2TargetParent, TrieNodeV2,
14};
15
16/// Modification epoch assigned to cached sparse trie nodes.
17///
18/// Epochs must increase monotonically. Nodes materialized from the parent state without being
19/// modified use [`Self::UNMODIFIED`].
20#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
21pub struct TrieNodeEpoch(u64);
22
23impl TrieNodeEpoch {
24 /// Epoch assigned to nodes materialized from the parent state without being modified.
25 pub const UNMODIFIED: Self = Self(0);
26
27 /// Creates a new node modification epoch.
28 pub const fn new(epoch: u64) -> Self {
29 Self(epoch)
30 }
31
32 /// Returns the inner epoch.
33 pub const fn get(self) -> u64 {
34 self.0
35 }
36
37 /// Returns whether a node with this epoch should be pruned at the provided cutoff.
38 pub const fn should_prune(self, prune_before: Self) -> bool {
39 self.0 < prune_before.0
40 }
41}
42
43/// Describes an update to a leaf in the sparse trie.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum LeafUpdate {
46 /// The leaf value has been changed to the given RLP-encoded value.
47 /// Empty Vec indicates the leaf has been removed.
48 Changed(Vec<u8>),
49 /// The leaf value may have changed, but the new value is not yet known.
50 /// Used for optimistic prewarming when the actual value is unavailable.
51 Touched,
52}
53
54impl LeafUpdate {
55 /// Returns true if the leaf update is a change.
56 pub const fn is_changed(&self) -> bool {
57 matches!(self, Self::Changed(_))
58 }
59
60 /// Returns true if the leaf update is a touched update.
61 pub const fn is_touched(&self) -> bool {
62 matches!(self, Self::Touched)
63 }
64}
65
66/// Trait defining common operations for revealed sparse trie implementations.
67///
68/// This trait provides a unified interface for the core trie operations needed by
69/// `RevealableSparseTrie`.
70pub trait SparseTrie: Sized + Debug + Send + Sync {
71 /// Configures the trie to have the given root node revealed.
72 ///
73 /// # Arguments
74 ///
75 /// * `root` - The root node to reveal
76 /// * `masks` - Trie masks for root branch node
77 /// * `retain_updates` - Whether to track updates
78 ///
79 /// # Returns
80 ///
81 /// `Ok(())` if successful, or an error if revealing fails. Implementations may reject
82 /// unsupported root variants. The arena implementation requires extensions to be merged
83 /// into branch nodes and returns an error for standalone [`TrieNodeV2::Extension`] roots.
84 ///
85 /// # Panics
86 ///
87 /// May panic if the trie is not new/cleared, and has already revealed nodes.
88 fn set_root(
89 &mut self,
90 root: TrieNodeV2,
91 masks: Option<BranchNodeMasks>,
92 retain_updates: bool,
93 ) -> SparseTrieResult<()>;
94
95 /// Configures the trie to retain information about updates.
96 ///
97 /// If `retain_updates` is true, the trie will record branch node updates
98 /// and deletions. This information can be used to efficiently update
99 /// an external database.
100 ///
101 /// # Arguments
102 ///
103 /// * `retain_updates` - Whether to track updates
104 fn set_updates(&mut self, retain_updates: bool);
105
106 /// Reveals one or more trie nodes if they have not been revealed before.
107 ///
108 /// Attaches supplied nodes where their paths identify blinded nodes in the current trie.
109 /// Nodes already revealed, paths diverging from the trie, and paths naming absent children
110 /// may be skipped.
111 ///
112 /// # Arguments
113 ///
114 /// * `nodes` - The nodes to be revealed, each having a path and optional set of branch node
115 /// masks. The nodes will be unsorted.
116 ///
117 /// # Returns
118 ///
119 /// `Ok(())` if processing succeeds, including when nodes are skipped, or an error if
120 /// revelation fails. Success does not guarantee that every supplied node was incorporated.
121 ///
122 /// # Note
123 ///
124 /// The implementation may modify the input nodes. A common thing to do is [`std::mem::replace`]
125 /// each node with [`TrieNodeV2::EmptyRoot`] to avoid cloning.
126 fn reveal_nodes(&mut self, nodes: &mut [ProofTrieNodeV2]) -> SparseTrieResult<()>;
127
128 /// Calculates and returns the root hash of the trie at the provided epoch.
129 ///
130 /// This processes dirty nodes by updating their RLP encodings and caching their newest
131 /// modification at `new_epoch`, then returns the root hash.
132 ///
133 /// # Returns
134 ///
135 /// The root hash of the trie.
136 fn root(&mut self, new_epoch: TrieNodeEpoch) -> B256;
137
138 /// Returns true if the root node is cached and does not need any recomputation.
139 fn is_root_cached(&self) -> bool;
140
141 /// Returns the root's modification epoch when it is clean, or `None` when it is dirty.
142 fn root_epoch(&self) -> Option<TrieNodeEpoch>;
143
144 /// Recalculates and updates the RLP hashes of subtries deeper than a certain level. The level
145 /// is defined in the implementation.
146 ///
147 /// The root node is considered to be at level 0. This method is useful for optimizing
148 /// hash recalculations after localized changes to the trie structure.
149 fn update_subtrie_hashes(&mut self, new_epoch: TrieNodeEpoch);
150
151 /// Retrieves a reference to the leaf value at the specified path.
152 ///
153 /// # Arguments
154 ///
155 /// * `full_path` - The full path to the leaf value
156 ///
157 /// # Returns
158 ///
159 /// A reference to the leaf value stored at the given full path, if it is revealed.
160 ///
161 /// Note: a value can exist in the full trie and this function still returns `None`
162 /// because the value has not been revealed.
163 ///
164 /// Hence a `None` indicates two possibilities:
165 /// - The value does not exists in the trie, so it cannot be revealed
166 /// - The value has not yet been revealed. In order to determine which is true, one would need
167 /// an exclusion proof.
168 fn get_leaf_value(&self, full_path: &Nibbles) -> Option<&Vec<u8>>;
169
170 /// Attempts to find a leaf node at the specified path.
171 ///
172 /// This method traverses the trie from the root down to the given path, checking
173 /// if a leaf exists at that path. It can be used to verify the existence of a leaf
174 /// or to generate an exclusion proof (proof that a leaf does not exist).
175 ///
176 /// # Parameters
177 ///
178 /// - `full_path`: The path to search for.
179 /// - `expected_value`: Optional expected value. If provided, will verify the leaf value
180 /// matches.
181 ///
182 /// # Returns
183 ///
184 /// - `Ok(LeafLookup::Exists)` if the leaf exists with the expected value.
185 /// - `Ok(LeafLookup::NonExistent)` if the leaf definitely does not exist (exclusion proof).
186 /// - `Err(LeafLookupError)` if the search encountered a blinded node or found a different
187 /// value.
188 fn find_leaf(
189 &self,
190 full_path: &Nibbles,
191 expected_value: Option<&Vec<u8>>,
192 ) -> Result<LeafLookup, LeafLookupError>;
193
194 /// Returns a reference to the current sparse trie updates.
195 ///
196 /// If no updates have been made/recorded, returns an empty update set.
197 fn updates_ref(&self) -> Cow<'_, SparseTrieUpdates>;
198
199 /// Consumes and returns the currently accumulated trie updates.
200 ///
201 /// This is useful when you want to apply the updates to an external database
202 /// and then start tracking a new set of updates.
203 ///
204 /// # Returns
205 ///
206 /// The accumulated updates, or an empty set if updates weren't being tracked.
207 fn take_updates(&mut self) -> SparseTrieUpdates;
208
209 /// This clears all data structures in the sparse trie, keeping the backing data structures
210 /// allocated. An empty root node is inserted at the root.
211 ///
212 /// This is useful for reusing the trie without needing to reallocate memory.
213 fn clear(&mut self);
214
215 /// Collapses nodes last modified before `prune_before` into hash stubs.
216 ///
217 /// # Preconditions
218 ///
219 /// The trie must not be dirty. An unmodified revealed root may be pruned because
220 /// proof-revealed descendants carry cached RLP nodes.
221 ///
222 /// # Returns
223 ///
224 /// The number of nodes converted to hash stubs.
225 fn prune(&mut self, prune_before: TrieNodeEpoch) -> usize;
226
227 /// Applies leaf updates to the sparse trie.
228 ///
229 /// When a [`LeafUpdate::Changed`] is successfully applied, it is removed from the
230 /// given [`B256Map`]. If it could not be applied due to blinded nodes, it remains
231 /// in the map and the callback is invoked with the required proof target.
232 ///
233 /// Once that proof is calculated and revealed via [`SparseTrie::reveal_nodes`], the same
234 /// `updates` map can be reused to retry the update.
235 ///
236 /// The callback receives `(key, parent)` where `key` is the full 32-byte hashed key
237 /// (right-padded with zeros from the blinded path) and `parent` identifies the revealed logical
238 /// parent branch. No known parent indicates that the trie is entirely blind and the proof
239 /// must include the root.
240 ///
241 /// The callback may be invoked multiple times for the same target across retry loops.
242 /// Callers should deduplicate if needed.
243 ///
244 /// [`LeafUpdate::Touched`] behaves identically except it does not modify the leaf value.
245 fn update_leaves(
246 &mut self,
247 updates: &mut B256Map<LeafUpdate>,
248 proof_required_fn: impl FnMut(B256, ProofV2TargetParent),
249 ) -> SparseTrieResult<()>;
250}
251
252/// Tracks modifications to the sparse trie structure.
253///
254/// Maintains references to both modified and pruned/removed branches, enabling
255/// one to make batch updates to a persistent database.
256#[derive(Debug, Clone, Default, PartialEq, Eq)]
257pub struct SparseTrieUpdates {
258 /// Collection of updated intermediate nodes indexed by full path.
259 pub updated_nodes: HashMap<Nibbles, BranchNodeCompact>,
260 /// Collection of removed intermediate nodes indexed by full path.
261 pub removed_nodes: HashSet<Nibbles>,
262}
263
264impl SparseTrieUpdates {
265 /// Initialize a [`Self`] with given capacities.
266 pub fn with_capacity(num_updated_nodes: usize, num_removed_nodes: usize) -> Self {
267 Self {
268 updated_nodes: HashMap::with_capacity_and_hasher(num_updated_nodes, Default::default()),
269 removed_nodes: HashSet::with_capacity_and_hasher(num_removed_nodes, Default::default()),
270 }
271 }
272}
273
274/// Error type for a leaf lookup operation
275#[derive(Debug, Clone, PartialEq, Eq)]
276pub enum LeafLookupError {
277 /// The path leads to a blinded node, cannot determine if leaf exists.
278 /// This means the witness is not complete.
279 BlindedNode {
280 /// Path to the blinded node.
281 path: Nibbles,
282 /// Hash of the blinded node.
283 hash: B256,
284 },
285 /// The path leads to a leaf with a different value than expected.
286 /// This means the witness is malformed.
287 ValueMismatch {
288 /// Path to the leaf.
289 path: Nibbles,
290 /// Expected value.
291 expected: Option<Vec<u8>>,
292 /// Actual value found.
293 actual: Vec<u8>,
294 },
295}
296
297/// Success value for a leaf lookup operation
298#[derive(Debug, Clone, PartialEq, Eq)]
299pub enum LeafLookup {
300 /// Leaf exists with expected value.
301 Exists,
302 /// Leaf does not exist (exclusion proof found).
303 NonExistent,
304}