Skip to main content

reth_trie_sparse/arena/
nodes.rs

1use super::{
2    branch_child_idx::{BranchChildIdx, BranchChildIter},
3    ArenaSparseSubtrie, BranchChild, Index, NodeArena,
4};
5use alloc::{boxed::Box, vec::Vec};
6use alloy_primitives::{keccak256, B256};
7use alloy_trie::{BranchNodeCompact, TrieMask};
8use reth_trie_common::{BranchNodeMasks, Nibbles, ProofTrieNode, RlpNode, TrieNode};
9use smallvec::SmallVec;
10use strum::AsRefStr;
11
12use crate::TrieNodeEpoch;
13
14/// Tracks whether a node's RLP encoding is cached or needs recomputation.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub(super) enum ArenaSparseNodeState {
17    /// The node has been revealed but its RLP encoding is not cached.
18    Revealed,
19    /// The node has a cached RLP encoding that is still valid.
20    Cached {
21        /// The cached RLP-encoded representation of the node.
22        rlp_node: RlpNode,
23        /// The newest tracked modification epoch for this node or its descendants.
24        epoch: TrieNodeEpoch,
25    },
26    /// The node has been modified and its RLP encoding needs recomputation.
27    Dirty,
28}
29
30impl ArenaSparseNodeState {
31    /// Converts into a [`Self::Dirty`] if it's not already.
32    pub(super) const fn to_dirty(&self) -> Self {
33        Self::Dirty
34    }
35
36    /// Returns the [`RlpNode`] cached on the state, if there is one.
37    pub(super) const fn cached_rlp_node(&self) -> Option<&RlpNode> {
38        match self {
39            Self::Cached { rlp_node, .. } => Some(rlp_node),
40            _ => None,
41        }
42    }
43
44    /// Returns the cached epoch, if this node is cached.
45    pub(super) const fn cached_epoch(&self) -> Option<TrieNodeEpoch> {
46        match self {
47            Self::Cached { epoch, .. } => Some(*epoch),
48            _ => None,
49        }
50    }
51}
52
53/// The branch-specific data stored in an [`ArenaSparseNode::Branch`].
54#[derive(Debug, Clone)]
55pub(super) struct ArenaSparseNodeBranch {
56    /// Cached or dirty state of this node.
57    pub(super) state: ArenaSparseNodeState,
58    /// Revealed or blinded children, packed densely. The `state_mask` tracks which
59    /// nibble positions have entries in this `SmallVec`, which is sized to hold the maximum
60    /// of 16 children inline and therefore never spills.
61    pub(super) children: SmallVec<[BranchChild; 16]>,
62    /// Bitmask indicating which of the 16 child slots are occupied (have an entry
63    /// in `children`).
64    pub(super) state_mask: TrieMask,
65    /// Tree mask and hash mask for database persistence (`TrieUpdates`).
66    pub(super) branch_masks: BranchNodeMasks,
67}
68
69impl ArenaSparseNodeBranch {
70    /// Unsets the bit for `nibble` in `state_mask`, `hash_mask`, and `tree_mask`.
71    pub(super) const fn unset_child_bit(&mut self, nibble: u8) {
72        self.state_mask.unset_bit(nibble);
73    }
74
75    /// Inserts a child at `nibble`, updating the state mask, children array, and marking the
76    /// branch as dirty.
77    pub(super) fn set_child(&mut self, nibble: u8, child: BranchChild) {
78        let insert_pos = BranchChildIdx::insertion_point(self.state_mask, nibble);
79        self.state_mask.set_bit(nibble);
80        self.children.insert(insert_pos.get(), child);
81        self.state = ArenaSparseNodeState::Dirty;
82    }
83
84    /// Removes the child at `nibble`, updating the state mask, children array, and marking the
85    /// branch as dirty.
86    ///
87    /// # Panics
88    ///
89    /// Panics if `nibble` is not set in the state mask.
90    pub(super) fn remove_child(&mut self, nibble: u8) {
91        let child_idx =
92            BranchChildIdx::new(self.state_mask, nibble).expect("nibble not found in state_mask");
93        self.children.remove(child_idx.get());
94        self.unset_child_bit(nibble);
95        self.state = ArenaSparseNodeState::Dirty;
96    }
97
98    /// Returns the sibling child in a branch with exactly 2 children.
99    ///
100    /// # Panics
101    ///
102    /// Panics (debug) if the branch does not have exactly 2 children, or if `nibble` is not set.
103    pub(super) fn sibling_child(&self, nibble: u8) -> BranchChild {
104        debug_assert_eq!(
105            self.state_mask.count_bits(),
106            2,
107            "sibling_child requires exactly 2 children"
108        );
109        let child_idx =
110            BranchChildIdx::new(self.state_mask, nibble).expect("nibble not found in state_mask");
111        // With exactly 2 children the dense array has indices 0 and 1.
112        self.children[1 - child_idx.get()]
113    }
114
115    /// Iterates over `(nibble, child)` pairs in nibble order.
116    pub(super) fn child_iter(&self) -> impl Iterator<Item = (u8, BranchChild)> + '_ {
117        BranchChildIter::new(self.state_mask).map(|(idx, nibble)| (nibble, self.children[idx]))
118    }
119
120    /// Returns a [`BranchNodeCompact`] from this branch's masks and children hashes.
121    pub(super) fn branch_node_compact(&self, arena: &NodeArena) -> BranchNodeCompact {
122        let mut hashes = Vec::with_capacity(self.branch_masks.hash_mask.count_bits() as usize);
123        for (nibble, child) in self.child_iter() {
124            if self.branch_masks.hash_mask.is_bit_set(nibble) {
125                let hash = match child.revealed_index() {
126                    Some(child_idx) => arena[child_idx].cached_hash(),
127                    None => arena.blinded(child).as_hash().expect("blinded child must be a hash"),
128                };
129                hashes.push(hash);
130            }
131        }
132        BranchNodeCompact::new(
133            self.state_mask,
134            self.branch_masks.tree_mask,
135            self.branch_masks.hash_mask,
136            hashes,
137            None,
138        )
139    }
140}
141
142/// A node in the arena-based sparse trie.
143#[derive(Debug, Clone, AsRefStr)]
144pub(super) enum ArenaSparseNode {
145    /// Indicates a trie with no nodes.
146    EmptyRoot {
147        /// Cached or dirty state of this node. Its cached RLP is always the empty root hash.
148        state: ArenaSparseNodeState,
149    },
150    /// A branch node with up to 16 children.
151    Branch(ArenaSparseNodeBranch),
152    /// An extension node with a revealed or blinded branch child.
153    Extension {
154        /// The extension key.
155        key: Nibbles,
156        /// The extension's revealed or blinded branch child.
157        child: ExtensionChild,
158        /// Cached or dirty state of the extension, independent of its branch child.
159        state: ArenaSparseNodeState,
160    },
161    /// A leaf node containing a value.
162    Leaf {
163        /// Cached or dirty state of this node.
164        state: ArenaSparseNodeState,
165        /// The RLP-encoded leaf value.
166        value: Vec<u8>,
167        /// The remaining key suffix for this leaf.
168        key: Nibbles,
169    },
170    /// A subtrie that can be taken for parallel processing.
171    Subtrie(Box<ArenaSparseSubtrie>),
172    /// Placeholder for a subtrie that has been temporarily taken for parallel operations.
173    TakenSubtrie,
174    /// Tombstone for a vacated slot. [`NodeArena::remove`](super::NodeArena::remove) also puts
175    /// the slot on the arena's free list, [`NodeArena::drain_node`](super::NodeArena::drain_node)
176    /// does not.
177    Free,
178}
179
180impl ArenaSparseNode {
181    /// Returns the state of an empty root, branch, extension, leaf, or subtrie root,
182    /// or `None` for other types.
183    pub(super) fn state_ref(&self) -> Option<&ArenaSparseNodeState> {
184        match self {
185            Self::EmptyRoot { state } |
186            Self::Leaf { state, .. } |
187            Self::Extension { state, .. } => Some(state),
188            Self::Branch(b) => Some(&b.state),
189            Self::Subtrie(s) => s.arena[s.root].state_ref(),
190            _ => None,
191        }
192    }
193
194    /// Returns the mutable state of an empty root, branch, extension, or leaf.
195    ///
196    /// # Panics
197    ///
198    /// Panics if called on a subtrie or vacant node.
199    pub(super) fn state_mut(&mut self) -> &mut ArenaSparseNodeState {
200        match self {
201            Self::EmptyRoot { state } |
202            Self::Leaf { state, .. } |
203            Self::Extension { state, .. } => state,
204            Self::Branch(b) => &mut b.state,
205            _ => panic!("state_mut called on a node without its own state"),
206        }
207    }
208
209    /// Returns `true` if this node's RLP encoding is cached.
210    pub(super) fn is_cached(&self) -> bool {
211        self.state_ref().is_some_and(|s| matches!(s, ArenaSparseNodeState::Cached { .. }))
212    }
213
214    /// Returns the short key of the extension or leaf, or None.
215    pub(super) const fn short_key(&self) -> Option<&Nibbles> {
216        match self {
217            Self::Extension { key, .. } | Self::Leaf { key, .. } => Some(key),
218            _ => None,
219        }
220    }
221
222    /// Returns the extension key, if this is an extension node.
223    pub(super) const fn extension_key(&self) -> Option<&Nibbles> {
224        match self {
225            Self::Extension { key, .. } => Some(key),
226            _ => None,
227        }
228    }
229
230    /// Returns the revealed branch index of this extension, or `None` for a blinded child.
231    pub(super) const fn extension_child(&self) -> Option<Index> {
232        match self {
233            Self::Extension { child, .. } => child.revealed_index(),
234            _ => None,
235        }
236    }
237
238    /// Returns a reference to the branch data.
239    ///
240    /// # Panics
241    ///
242    /// Panics if this is not a `Branch` node.
243    pub(super) fn branch_ref(&self) -> &ArenaSparseNodeBranch {
244        match self {
245            Self::Branch(b) => b,
246            _ => panic!("branch_ref called on non-Branch node {self:?}"),
247        }
248    }
249
250    /// Returns a mutable reference to the branch data.
251    ///
252    /// # Panics
253    ///
254    /// Panics if this is not a `Branch` node.
255    pub(super) fn branch_mut(&mut self) -> &mut ArenaSparseNodeBranch {
256        match self {
257            Self::Branch(b) => b,
258            _ => panic!("branch_mut called on non-Branch node {self:?}"),
259        }
260    }
261
262    /// Returns a reference to the subtrie if this is a `Subtrie` node, or `None`.
263    #[cfg(all(debug_assertions, not(feature = "fuzz")))]
264    pub(super) const fn as_subtrie(&self) -> Option<&ArenaSparseSubtrie> {
265        match self {
266            Self::Subtrie(s) => Some(s),
267            _ => None,
268        }
269    }
270
271    /// Returns `true` if this node should contribute a set bit in its parent's `hash_mask`.
272    ///
273    /// That is, if the node is a branch without a parent extension whose cached RLP is a hash
274    /// (>= 32 bytes). Small branches whose RLP is embedded don't get a `hash_mask` bit.
275    pub(super) fn hash_mask_bit(&self) -> bool {
276        match self {
277            Self::Branch(b) => {
278                b.state.cached_rlp_node().expect("branch's RlpNode must be cached").is_hash()
279            }
280            Self::Subtrie(s) => s.arena[s.root].hash_mask_bit(),
281            _ => false,
282        }
283    }
284
285    /// Returns the cached hash of this node. Panics if the node's state is not `Cached`.
286    ///
287    /// If the `RlpNode` is already a hash (>= 32 bytes encoded), returns it directly.
288    /// Otherwise keccak-hashes the RLP encoding to produce the hash. This handles the
289    /// case where a branch's RLP is small enough to be embedded rather than hashed.
290    pub(super) fn cached_hash(&self) -> B256 {
291        let rlp_node = match self {
292            Self::Branch(ArenaSparseNodeBranch { state, .. }) |
293            Self::Extension { state, .. } |
294            Self::Leaf { state, .. } => state
295                .cached_rlp_node()
296                .expect("cached_hash called on non-Cached branch, extension, or leaf: {self:?}"),
297            Self::Subtrie(s) => return s.arena[s.root].cached_hash(),
298            _ => panic!("cached_hash called on {self:?}"),
299        };
300        rlp_node.as_hash().unwrap_or_else(|| keccak256(rlp_node.as_slice()))
301    }
302}
303
304impl ArenaSparseNode {
305    /// Converts a calculator proof node into an arena node, retaining a blinded backing branch
306    /// when the extension's separate branch proof is not supplied.
307    pub(super) fn from_proof_node(
308        arena: &mut NodeArena,
309        proof_node: ProofTrieNode,
310        extension_child: Option<ProofTrieNode>,
311    ) -> Self {
312        let ProofTrieNode { node, masks, .. } = proof_node;
313        match node {
314            TrieNode::EmptyRoot => Self::EmptyRoot { state: ArenaSparseNodeState::Revealed },
315            TrieNode::Leaf(leaf) => Self::Leaf {
316                state: ArenaSparseNodeState::Revealed,
317                key: leaf.key,
318                value: leaf.value,
319            },
320            TrieNode::Branch(branch) => {
321                let children = branch.stack[..branch.state_mask.count_bits() as usize]
322                    .iter()
323                    .map(|rlp| arena.insert_blinded(rlp.clone()))
324                    .collect();
325                Self::Branch(ArenaSparseNodeBranch {
326                    state: ArenaSparseNodeState::Revealed,
327                    children,
328                    state_mask: branch.state_mask,
329                    branch_masks: masks.unwrap_or_default(),
330                })
331            }
332            TrieNode::Extension(extension) => {
333                let child = match extension_child {
334                    Some(branch) => {
335                        let branch = Self::from_proof_node(arena, branch, None);
336                        ExtensionChild::Revealed(arena.insert(branch))
337                    }
338                    None => ExtensionChild::Blinded(extension.child),
339                };
340                Self::Extension { key: extension.key, child, state: ArenaSparseNodeState::Revealed }
341            }
342        }
343    }
344}
345
346/// The branch referenced by an extension, without allocating an arena slot until revealed.
347#[derive(Debug, Clone)]
348pub(super) enum ExtensionChild {
349    /// The index of a revealed branch in the same arena.
350    Revealed(Index),
351    /// The branch reference supplied by the extension proof.
352    Blinded(RlpNode),
353}
354
355impl ExtensionChild {
356    /// Returns the branch index, or `None` while the branch is blinded.
357    pub(super) const fn revealed_index(&self) -> Option<Index> {
358        match self {
359            Self::Revealed(index) => Some(*index),
360            Self::Blinded(_) => None,
361        }
362    }
363}