Skip to main content

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