reth_trie_sparse/trie.rs
1use crate::{
2 ArenaParallelSparseTrie, LeafUpdate, SparseTrie as SparseTrieTrait, SparseTrieUpdates,
3 TrieNodeEpoch,
4};
5use alloc::{borrow::Cow, boxed::Box};
6use alloy_primitives::{map::B256Map, B256};
7use reth_execution_errors::{SparseTrieErrorKind, SparseTrieResult};
8use reth_trie_common::{
9 BranchNodeMasks, Nibbles, ProofTrieNodeV2, ProofV2TargetParent, RlpNode, TrieMask, TrieNodeV2,
10};
11
12/// A sparse trie that is either in a "blind" state (no nodes are revealed, root node hash is
13/// unknown) or in a "revealed" state (root node has been revealed and the trie can be updated).
14///
15/// In blind mode the trie does not contain any decoded node data, which saves memory but
16/// prevents direct access to node contents. The revealed mode stores decoded nodes along
17/// with additional information such as values, allowing direct manipulation.
18///
19/// The sparse trie design is optimised for:
20/// 1. Memory efficiency - only revealed nodes are loaded into memory
21/// 2. Update tracking - changes to the trie structure can be tracked and selectively persisted
22/// 3. Incremental operations - nodes can be revealed as needed without loading the entire trie.
23/// This is what gives rise to the notion of a "sparse" trie.
24#[derive(PartialEq, Eq, Debug, Clone)]
25pub enum RevealableSparseTrie<T = ArenaParallelSparseTrie> {
26 /// The trie is blind -- no nodes have been revealed
27 ///
28 /// This is the default state. In this state, the trie cannot be directly queried or modified
29 /// until nodes are revealed.
30 ///
31 /// In this state the `RevealableSparseTrie` can optionally carry with it a cleared
32 /// sparse trie. This allows for reusing the trie's allocations between payload executions.
33 Blind(Option<Box<T>>),
34 /// Some nodes in the Trie have been revealed.
35 ///
36 /// In this state, the trie can be queried and modified for the parts
37 /// that have been revealed. Other parts remain blind and require revealing
38 /// before they can be accessed.
39 Revealed(Box<T>),
40}
41
42impl<T: Default> Default for RevealableSparseTrie<T> {
43 fn default() -> Self {
44 Self::Blind(None)
45 }
46}
47
48impl<T: SparseTrieTrait + Default> RevealableSparseTrie<T> {
49 /// Creates a new revealed but empty sparse trie.
50 pub fn revealed_empty() -> Self {
51 Self::Revealed(Box::default())
52 }
53
54 /// Reveals the root node, converting a blind trie into a revealed one.
55 ///
56 /// If the trie is blinded, its root node is replaced with `root`.
57 ///
58 /// The `masks` are used to determine how the node's children are stored.
59 /// The retention flag controls whether trie updates should be tracked.
60 ///
61 /// # Returns
62 ///
63 /// A mutable reference to the underlying [`RevealableSparseTrie`](SparseTrieTrait).
64 pub fn reveal_root(
65 &mut self,
66 root: TrieNodeV2,
67 masks: Option<BranchNodeMasks>,
68 retain_updates: bool,
69 ) -> SparseTrieResult<&mut T> {
70 // if `Blind`, we initialize the revealed trie with the given root node, using a
71 // pre-allocated trie if available.
72 if self.is_blind() {
73 let mut revealed_trie = if let Self::Blind(Some(cleared_trie)) = core::mem::take(self) {
74 cleared_trie
75 } else {
76 Box::default()
77 };
78
79 revealed_trie.set_root(root, masks, retain_updates)?;
80 *self = Self::Revealed(revealed_trie);
81 }
82
83 Ok(self.as_revealed_mut().unwrap())
84 }
85
86 /// Reveals a batch of V2 proof nodes into this trie.
87 ///
88 /// If `nodes` contains a node at the empty path it is used to reveal the root (transitioning
89 /// the trie from blind to revealed). Otherwise the trie must already be revealed.
90 pub fn reveal_v2_proof_nodes(
91 &mut self,
92 nodes: &mut [ProofTrieNodeV2],
93 retain_updates: bool,
94 ) -> SparseTrieResult<()> {
95 let trie = if let Some(root_node) = nodes.iter().find(|n| n.path.is_empty()) {
96 self.reveal_root(root_node.node.clone(), root_node.masks, retain_updates)?
97 } else {
98 self.as_revealed_mut().ok_or(SparseTrieErrorKind::Blind)?
99 };
100 trie.reveal_nodes(nodes)?;
101
102 Ok(())
103 }
104}
105
106impl<T: SparseTrieTrait> RevealableSparseTrie<T> {
107 /// Creates a new blind sparse trie.
108 ///
109 /// # Examples
110 ///
111 /// ```
112 /// use reth_trie_sparse::RevealableSparseTrie;
113 ///
114 /// let trie = <RevealableSparseTrie>::blind();
115 /// assert!(trie.is_blind());
116 /// let trie = <RevealableSparseTrie>::default();
117 /// assert!(trie.is_blind());
118 /// ```
119 pub const fn blind() -> Self {
120 Self::Blind(None)
121 }
122
123 /// Creates a new blind sparse trie, clearing and later reusing the given
124 /// [`RevealableSparseTrie`](SparseTrieTrait).
125 pub fn blind_from(mut trie: T) -> Self {
126 trie.clear();
127 Self::Blind(Some(Box::new(trie)))
128 }
129
130 /// Returns `true` if the sparse trie has no revealed nodes.
131 pub const fn is_blind(&self) -> bool {
132 matches!(self, Self::Blind(_))
133 }
134
135 /// Returns `true` if the sparse trie is revealed.
136 pub const fn is_revealed(&self) -> bool {
137 matches!(self, Self::Revealed(_))
138 }
139
140 /// Returns an immutable reference to the underlying revealed sparse trie.
141 ///
142 /// Returns `None` if the trie is blinded.
143 pub const fn as_revealed_ref(&self) -> Option<&T> {
144 if let Self::Revealed(revealed) = self {
145 Some(revealed)
146 } else {
147 None
148 }
149 }
150
151 /// Returns a mutable reference to the underlying revealed sparse trie.
152 ///
153 /// Returns `None` if the trie is blinded.
154 pub fn as_revealed_mut(&mut self) -> Option<&mut T> {
155 if let Self::Revealed(revealed) = self {
156 Some(revealed)
157 } else {
158 None
159 }
160 }
161
162 /// Calculates the root hash of the trie.
163 ///
164 /// This will update any remaining dirty nodes before computing the root hash.
165 /// "dirty" nodes are nodes that need their hashes to be recomputed because one or more of their
166 /// children's hashes have changed.
167 ///
168 /// # Returns
169 ///
170 /// - `Some(B256)` with the calculated root hash if the trie is revealed.
171 /// - `None` if the trie is still blind.
172 pub fn root(&mut self, new_epoch: TrieNodeEpoch) -> Option<B256> {
173 Some(self.as_revealed_mut()?.root(new_epoch))
174 }
175
176 /// Returns true if the root node is cached and does not need any recomputation.
177 pub fn is_root_cached(&self) -> bool {
178 self.as_revealed_ref().is_some_and(|trie| trie.is_root_cached())
179 }
180
181 /// Returns the root hash along with any accumulated update information.
182 ///
183 /// This is useful for when you need both the root hash and information about
184 /// what nodes were modified, which can be used to efficiently update
185 /// an external database.
186 ///
187 /// # Returns
188 ///
189 /// An `Option` tuple consisting of:
190 /// - The trie root hash (`B256`).
191 /// - A [`SparseTrieUpdates`] structure containing information about updated nodes.
192 /// - `None` if the trie is still blind.
193 pub fn root_with_updates(
194 &mut self,
195 new_epoch: TrieNodeEpoch,
196 ) -> Option<(B256, SparseTrieUpdates)> {
197 let revealed = self.as_revealed_mut()?;
198 Some((revealed.root(new_epoch), revealed.take_updates()))
199 }
200
201 /// Clears this trie, setting it to a blind state.
202 ///
203 /// If this instance was revealed, or was itself a `Blind` with a pre-allocated
204 /// [`RevealableSparseTrie`](SparseTrieTrait), this will set to `Blind` carrying a cleared
205 /// pre-allocated [`RevealableSparseTrie`](SparseTrieTrait).
206 #[inline]
207 pub fn clear(&mut self) {
208 *self = match core::mem::replace(self, Self::blind()) {
209 s @ Self::Blind(_) => s,
210 Self::Revealed(mut trie) => {
211 trie.clear();
212 Self::Blind(Some(trie))
213 }
214 };
215 }
216}
217
218impl<T: SparseTrieTrait + Default> RevealableSparseTrie<T> {
219 /// Applies batch leaf updates to the sparse trie.
220 ///
221 /// For blind tries, all updates are kept in the map and proof targets are emitted
222 /// for every key (with no known parent since nothing is revealed).
223 ///
224 /// For revealed tries, delegates to the inner implementation which will:
225 /// - Apply updates where possible
226 /// - Keep blocked updates in the map
227 /// - Emit proof targets for blinded paths
228 pub fn update_leaves(
229 &mut self,
230 updates: &mut B256Map<LeafUpdate>,
231 mut proof_required_fn: impl FnMut(B256, ProofV2TargetParent),
232 ) -> SparseTrieResult<()> {
233 match self {
234 Self::Blind(_) => {
235 // Nothing is revealed - emit proof targets for all keys without a known parent.
236 for key in updates.keys() {
237 proof_required_fn(*key, ProofV2TargetParent::NONE);
238 }
239 // All updates remain in the map for retry after proofs are fetched
240 Ok(())
241 }
242 Self::Revealed(trie) => trie.update_leaves(updates, proof_required_fn),
243 }
244 }
245}
246
247/// Enum representing sparse trie node type.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub enum SparseNodeType {
250 /// Empty trie node.
251 Empty,
252 /// A placeholder that stores only the hash for a node that has not been fully revealed.
253 Hash,
254 /// Sparse leaf node.
255 Leaf,
256 /// Sparse extension node.
257 Extension {
258 /// A flag indicating whether the extension node should be stored in the database.
259 store_in_db_trie: Option<bool>,
260 },
261 /// Sparse branch node.
262 Branch {
263 /// A flag indicating whether the branch node should be stored in the database.
264 store_in_db_trie: Option<bool>,
265 },
266}
267
268impl SparseNodeType {
269 /// Returns true if the node is a hash node.
270 pub const fn is_hash(&self) -> bool {
271 matches!(self, Self::Hash)
272 }
273
274 /// Returns true if the node is a branch node.
275 pub const fn is_branch(&self) -> bool {
276 matches!(self, Self::Branch { .. })
277 }
278
279 /// Returns true if the node should be stored in the database.
280 pub const fn store_in_db_trie(&self) -> Option<bool> {
281 match *self {
282 Self::Extension { store_in_db_trie } | Self::Branch { store_in_db_trie } => {
283 store_in_db_trie
284 }
285 _ => None,
286 }
287 }
288}
289
290/// Enum representing trie nodes in sparse trie.
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub enum SparseNode {
293 /// Empty trie node.
294 Empty,
295 /// Sparse leaf node with remaining key suffix.
296 Leaf {
297 /// Remaining key suffix for the leaf node.
298 key: Nibbles,
299 /// Tracker for the node's state, e.g. cached `RlpNode` tracking.
300 state: SparseNodeState,
301 },
302 /// Sparse extension node with key.
303 Extension {
304 /// The key slice stored by this extension node.
305 key: Nibbles,
306 /// Tracker for the node's state, e.g. cached `RlpNode` tracking.
307 state: SparseNodeState,
308 },
309 /// Sparse branch node with state mask.
310 Branch {
311 /// The bitmask representing children present in the branch node.
312 state_mask: TrieMask,
313 /// Tracker for the node's state, e.g. cached `RlpNode` tracking.
314 state: SparseNodeState,
315 /// The mask of the children that are blinded.
316 blinded_mask: TrieMask,
317 /// The hashes of the children that are blinded.
318 blinded_hashes: Box<[B256; 16]>,
319 },
320}
321
322impl SparseNode {
323 /// Create new [`SparseNode::Branch`] from state mask and blinded nodes.
324 #[cfg(test)]
325 pub fn new_branch(state_mask: TrieMask, blinded_children: &[(u8, B256)]) -> Self {
326 let mut blinded_mask = TrieMask::default();
327 let mut blinded_hashes = Box::new([B256::ZERO; 16]);
328
329 for (nibble, hash) in blinded_children {
330 blinded_mask.set_bit(*nibble);
331 blinded_hashes[*nibble as usize] = *hash;
332 }
333 Self::Branch { state_mask, state: SparseNodeState::Dirty, blinded_mask, blinded_hashes }
334 }
335
336 /// Create new [`SparseNode::Branch`] with two bits set.
337 pub fn new_split_branch(bit_a: u8, bit_b: u8) -> Self {
338 let state_mask = TrieMask::new(
339 // set bits for both children
340 (1u16 << bit_a) | (1u16 << bit_b),
341 );
342 Self::Branch {
343 state_mask,
344 state: SparseNodeState::Dirty,
345 blinded_mask: TrieMask::default(),
346 blinded_hashes: Box::new([B256::ZERO; 16]),
347 }
348 }
349
350 /// Create new [`SparseNode::Extension`] from the key slice.
351 pub const fn new_ext(key: Nibbles) -> Self {
352 Self::Extension { key, state: SparseNodeState::Dirty }
353 }
354
355 /// Create new [`SparseNode::Leaf`] from leaf key and value.
356 pub const fn new_leaf(key: Nibbles) -> Self {
357 Self::Leaf { key, state: SparseNodeState::Dirty }
358 }
359
360 /// Returns the cached [`RlpNode`] of the node, if it's available.
361 pub fn cached_rlp_node(&self) -> Option<Cow<'_, RlpNode>> {
362 match &self {
363 Self::Empty => None,
364 Self::Leaf { state, .. } |
365 Self::Extension { state, .. } |
366 Self::Branch { state, .. } => state.cached_rlp_node().map(Cow::Borrowed),
367 }
368 }
369
370 /// Returns the cached hash of the node, if it's available.
371 pub fn cached_hash(&self) -> Option<B256> {
372 match &self {
373 Self::Empty => None,
374 Self::Leaf { state, .. } |
375 Self::Extension { state, .. } |
376 Self::Branch { state, .. } => state.cached_hash(),
377 }
378 }
379
380 /// Sets the hash of the node for testing purposes.
381 ///
382 /// For [`SparseNode::Empty`] nodes, this method panics.
383 #[cfg(any(test, feature = "test-utils"))]
384 pub fn set_state(&mut self, new_state: SparseNodeState) {
385 match self {
386 Self::Empty => {
387 panic!("Cannot set hash for Empty or Hash nodes")
388 }
389 Self::Leaf { state, .. } |
390 Self::Extension { state, .. } |
391 Self::Branch { state, .. } => {
392 *state = new_state;
393 }
394 }
395 }
396
397 /// Sets the state of the node and returns a new node with the same state.
398 #[cfg(any(test, feature = "test-utils"))]
399 pub fn with_state(mut self, state: SparseNodeState) -> Self {
400 self.set_state(state);
401 self
402 }
403}
404
405/// Tracks the current state of a node in the trie, specifically regarding whether it's been updated
406/// or not.
407#[derive(Debug, Clone, PartialEq, Eq)]
408pub enum SparseNodeState {
409 /// The node has been updated and its new `RlpNode` has not yet been calculated.
410 ///
411 /// If a node is dirty and has children (branches or extensions) then at least once child must
412 /// also be dirty.
413 Dirty,
414 /// The node has a cached `RlpNode`, either from being revealed or computed after an update.
415 Cached {
416 /// The RLP node which is used to represent this node in its parent. Usually this is the
417 /// RLP encoding of the node's hash, except for when the node RLP encodes to <32
418 /// bytes.
419 rlp_node: RlpNode,
420 /// Flag indicating if this node is cached in the database.
421 ///
422 /// NOTE for extension nodes this actually indicates the node's child branch is in the
423 /// database, not the extension itself.
424 store_in_db_trie: Option<bool>,
425 },
426}
427
428impl SparseNodeState {
429 /// Returns the cached [`RlpNode`] of the node, if it's available.
430 pub const fn cached_rlp_node(&self) -> Option<&RlpNode> {
431 match self {
432 Self::Cached { rlp_node, .. } => Some(rlp_node),
433 Self::Dirty => None,
434 }
435 }
436
437 /// Returns the cached hash of the node, if it's available.
438 pub fn cached_hash(&self) -> Option<B256> {
439 self.cached_rlp_node().and_then(|n| n.as_hash())
440 }
441
442 /// Returns whether or not this node is stored in the db, or None if it's not known.
443 pub const fn store_in_db_trie(&self) -> Option<bool> {
444 match self {
445 Self::Cached { store_in_db_trie, .. } => *store_in_db_trie,
446 Self::Dirty => None,
447 }
448 }
449}
450
451/// RLP node stack item.
452#[derive(Clone, PartialEq, Eq, Debug)]
453pub struct RlpNodeStackItem {
454 /// Path to the node.
455 pub path: Nibbles,
456 /// RLP node.
457 pub rlp_node: RlpNode,
458 /// Type of the node.
459 pub node_type: SparseNodeType,
460}
461
462impl SparseTrieUpdates {
463 /// Clears the updates, but keeps the backing data structures allocated.
464 pub fn clear(&mut self) {
465 self.updated_nodes.clear();
466 self.removed_nodes.clear();
467 }
468
469 /// Extends the updates with another set of updates.
470 pub fn extend(&mut self, other: Self) {
471 self.updated_nodes.extend(other.updated_nodes);
472 self.removed_nodes.extend(other.removed_nodes);
473 }
474}