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#[derive(Debug, Clone, PartialEq, Eq)]
16pub(super) enum ArenaSparseNodeState {
17 Revealed,
19 Cached {
21 rlp_node: RlpNode,
23 epoch: TrieNodeEpoch,
25 },
26 Dirty,
28}
29
30impl ArenaSparseNodeState {
31 pub(super) const fn to_dirty(&self) -> Self {
33 Self::Dirty
34 }
35
36 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 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#[derive(Debug, Clone)]
55pub(super) struct ArenaSparseNodeBranch {
56 pub(super) state: ArenaSparseNodeState,
58 pub(super) children: SmallVec<[BranchChild; 16]>,
62 pub(super) state_mask: TrieMask,
65 pub(super) branch_masks: BranchNodeMasks,
67}
68
69impl ArenaSparseNodeBranch {
70 pub(super) const fn unset_child_bit(&mut self, nibble: u8) {
72 self.state_mask.unset_bit(nibble);
73 }
74
75 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 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 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 self.children[1 - child_idx.get()]
113 }
114
115 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 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#[derive(Debug, Clone, AsRefStr)]
144pub(super) enum ArenaSparseNode {
145 EmptyRoot {
147 state: ArenaSparseNodeState,
149 },
150 Branch(ArenaSparseNodeBranch),
152 Extension {
154 key: Nibbles,
156 child: ExtensionChild,
158 state: ArenaSparseNodeState,
160 },
161 Leaf {
163 state: ArenaSparseNodeState,
165 value: Vec<u8>,
167 key: Nibbles,
169 },
170 Subtrie(Box<ArenaSparseSubtrie>),
172 TakenSubtrie,
174 Free,
178}
179
180impl ArenaSparseNode {
181 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 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 pub(super) fn is_cached(&self) -> bool {
211 self.state_ref().is_some_and(|s| matches!(s, ArenaSparseNodeState::Cached { .. }))
212 }
213
214 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 pub(super) const fn extension_key(&self) -> Option<&Nibbles> {
224 match self {
225 Self::Extension { key, .. } => Some(key),
226 _ => None,
227 }
228 }
229
230 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 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 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 #[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 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 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 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#[derive(Debug, Clone)]
348pub(super) enum ExtensionChild {
349 Revealed(Index),
351 Blinded(RlpNode),
353}
354
355impl ExtensionChild {
356 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}