reth_trie/proof_v2/node.rs
1use crate::proof_v2::DeferredValueEncoder;
2use alloy_rlp::Encodable;
3use reth_execution_errors::trie::StateProofError;
4use reth_trie_common::{
5 BranchNode, BranchNodeMasks, ExtensionNode, ExtensionNodeRef, LeafNode, LeafNodeRef, Nibbles,
6 ProofTrieNode, RlpNode, TrieMask, TrieNode,
7};
8
9/// A trie node which is the child of a branch in the trie.
10#[derive(Debug)]
11pub(crate) enum ProofTrieBranchChild<RF> {
12 /// A leaf node whose value has yet to be calculated and encoded.
13 Leaf {
14 /// The short key of the leaf.
15 short_key: Nibbles,
16 /// The [`DeferredValueEncoder`] which will encode the leaf's value.
17 value: RF,
18 },
19 /// A branch node whose children have already been flattened into [`RlpNode`]s.
20 Branch {
21 /// The node itself, for use during RLP encoding.
22 node: BranchNode,
23 /// Short key of the separate parent extension, if any.
24 short_key: Nibbles,
25 /// Bitmasks carried over from cached `BranchNodeCompact` values, if any.
26 masks: Option<BranchNodeMasks>,
27 },
28 /// A node whose type is not known, as it has already been converted to an [`RlpNode`].
29 RlpNode {
30 /// The RLP-encoded node.
31 node: RlpNode,
32 /// The path from the parent branch's child nibble to the encoded node. This field can only
33 /// be set if `node` was sourced from the hashes of a cached branch, and therefore we know
34 /// that it is a blinded branch.
35 short_key: Nibbles,
36 /// Whether this node contributes to its parent's hash mask when it is a direct child.
37 hash_mask_bit: bool,
38 /// Whether this node contributes to its parent's tree mask.
39 tree_mask_bit: bool,
40 },
41}
42
43impl<RF: DeferredValueEncoder> ProofTrieBranchChild<RF> {
44 /// Converts this child into its RLP node representation.
45 ///
46 /// This potentially also returns an `RlpNode` buffer which can be re-used for other
47 /// [`ProofTrieBranchChild`]s.
48 pub(crate) fn into_rlp(
49 self,
50 buf: &mut Vec<u8>,
51 ) -> Result<(RlpNode, Option<Vec<RlpNode>>), StateProofError> {
52 match self {
53 Self::Leaf { short_key, value } => {
54 // RLP encode the value itself
55 value.encode(buf)?;
56 let value_enc_len = buf.len();
57
58 // Determine the required buffer size for the encoded leaf
59 let leaf_enc_len = LeafNodeRef::new(&short_key, buf).length();
60
61 // We want to re-use buf for the encoding of the leaf node as well. To do this we
62 // will keep appending to it, leaving the already encoded value in-place. First we
63 // must ensure the buffer is big enough, then we'll split.
64 buf.resize(value_enc_len + leaf_enc_len, 0);
65
66 // SAFETY we have just resized the above to be greater than `value_enc_len`, so it
67 // must be in-bounds.
68 let (value_buf, mut leaf_buf) =
69 unsafe { buf.split_at_mut_unchecked(value_enc_len) };
70
71 // Encode the leaf into the right side of the split buffer, and return the RlpNode.
72 LeafNodeRef::new(&short_key, value_buf).encode(&mut leaf_buf);
73 Ok((RlpNode::from_rlp(&buf[value_enc_len..]), None))
74 }
75 Self::Branch { node, short_key, .. } => {
76 node.encode(buf);
77 let branch_rlp = RlpNode::from_rlp(buf);
78 if short_key.is_empty() {
79 return Ok((branch_rlp, Some(node.stack)));
80 }
81 buf.clear();
82 ExtensionNodeRef::new(&short_key, branch_rlp.as_slice()).encode(buf);
83 Ok((RlpNode::from_rlp(buf), Some(node.stack)))
84 }
85 Self::RlpNode { node, short_key, hash_mask_bit, .. } => {
86 if short_key.is_empty() {
87 return Ok((node, None))
88 }
89
90 // Only branch hashes sourced from a cached hash mask can have an external short
91 // key. Other committed nodes already encode their key internally.
92 debug_assert!(hash_mask_bit);
93 ExtensionNodeRef::new(&short_key, node.as_slice()).encode(buf);
94 Ok((RlpNode::from_rlp(buf), None))
95 }
96 }
97 }
98
99 /// Converts this child into a proof node and its separate child branch, if any.
100 ///
101 /// The optional branch precedes the returned extension in depth-first order.
102 ///
103 /// # Errors
104 ///
105 /// Returns [`StateProofError::TrieInconsistency`] if called on a [`Self::RlpNode`].
106 pub(crate) fn into_proof_trie_node(
107 self,
108 path: Nibbles,
109 buf: &mut Vec<u8>,
110 ) -> Result<(ProofTrieNode, Option<ProofTrieNode>), StateProofError> {
111 let (node, masks) = match self {
112 Self::Leaf { short_key, value } => {
113 value.encode(buf)?;
114 // Counter-intuitively a clone is better here than a `core::mem::take`. If we take
115 // the buffer then future RLP-encodes will need to re-allocate a new one, and
116 // RLP-encodes after those may need a bigger buffer and therefore re-alloc again.
117 //
118 // By cloning here we do a single allocation of exactly the size we need to take
119 // this value, and the passed in buffer can remain with whatever large capacity it
120 // already has.
121 let rlp_val = buf.clone();
122 (TrieNode::Leaf(LeafNode::new(short_key, rlp_val)), None)
123 }
124 Self::Branch { node, short_key, masks } => {
125 if short_key.is_empty() {
126 (TrieNode::Branch(node), masks)
127 } else {
128 node.encode(buf);
129 let child = RlpNode::from_rlp(buf);
130 let branch = ProofTrieNode {
131 path: path.join(&short_key),
132 node: TrieNode::Branch(node),
133 masks,
134 };
135 let extension = ProofTrieNode {
136 path,
137 node: TrieNode::Extension(ExtensionNode::new(short_key, child)),
138 masks: None,
139 };
140 return Ok((extension, Some(branch)));
141 }
142 }
143 // Cached hashes cannot be retained as proof nodes: targeted children are recalculated,
144 // while untargeted children are either combined into a branch or discarded. Reaching
145 // this arm means inconsistent cached trie data left a blinded node as the local root.
146 Self::RlpNode { .. } => {
147 return Err(StateProofError::TrieInconsistency(
148 "cannot convert RLP node to proof node".to_string(),
149 ))
150 }
151 };
152
153 Ok((ProofTrieNode { node, path, masks }, None))
154 }
155
156 /// Returns the child's short key.
157 pub(crate) const fn short_key(&self) -> &Nibbles {
158 match self {
159 Self::Leaf { short_key, .. } |
160 Self::Branch { short_key, .. } |
161 Self::RlpNode { short_key, .. } => short_key,
162 }
163 }
164
165 /// Returns this child's hash and tree mask contributions.
166 pub(crate) fn mask_bits(&self) -> (bool, bool) {
167 match self {
168 Self::Leaf { .. } => (false, false),
169 Self::Branch { node, short_key, masks } => (
170 short_key.is_empty() && node.length() >= 32,
171 masks.is_some_and(|masks| !masks.is_empty()),
172 ),
173 Self::RlpNode { short_key, hash_mask_bit, tree_mask_bit, .. } => {
174 (*hash_mask_bit && short_key.is_empty(), *tree_mask_bit)
175 }
176 }
177 }
178
179 /// Trims the given number of nibbles off the head of the short key.
180 ///
181 /// # Panics
182 ///
183 /// - If the given len is longer than the short key
184 pub(crate) fn trim_short_key_prefix(&mut self, len: usize) {
185 match self {
186 Self::Leaf { short_key, .. } |
187 Self::Branch { short_key, .. } |
188 Self::RlpNode { short_key, .. } => {
189 *short_key = trim_nibbles_prefix(short_key, len);
190 }
191 }
192 }
193}
194
195/// A single branch in the trie which is under construction. The actual child nodes of the branch
196/// will be tracked as [`ProofTrieBranchChild`]s on a stack.
197#[derive(Debug)]
198pub(crate) struct ProofTrieBranch {
199 /// The length of the parent extension node's short key. If zero then the branch's parent is
200 /// not an extension but instead another branch.
201 pub(crate) ext_len: u8,
202 /// A mask tracking which child nibbles are set on the branch so far. There will be a single
203 /// child on the stack for each set bit.
204 pub(crate) state_mask: TrieMask,
205}
206
207/// Trims the first `len` nibbles from the head of the given `Nibbles`.
208///
209/// # Panics
210///
211/// Panics if the given `len` is greater than the length of the `Nibbles`.
212pub(crate) fn trim_nibbles_prefix(n: &Nibbles, len: usize) -> Nibbles {
213 debug_assert!(n.len() >= len);
214 n.slice_unchecked(len, n.len())
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use crate::proof_v2::value::StorageDeferredValueEncoder;
221 use alloy_primitives::B256;
222
223 #[test]
224 fn branch_proofs_keep_extensions_separate() {
225 for stack in [
226 vec![RlpNode::from_rlp(&[0xc2, 0x20, 0x01]); 2],
227 vec![RlpNode::word_rlp(&B256::repeat_byte(0x11)); 2],
228 ] {
229 let node = BranchNode::new(stack, TrieMask::new(0b11));
230 let encoded_branch = alloy_rlp::encode(&node);
231 let branch_rlp = RlpNode::from_rlp(&encoded_branch);
232 let key = Nibbles::from_nibbles([2, 3]);
233 let extension = ExtensionNode::new(key, branch_rlp);
234 let masks =
235 Some(BranchNodeMasks { hash_mask: TrieMask::new(1), tree_mask: TrieMask::new(2) });
236 let child = ProofTrieBranchChild::<StorageDeferredValueEncoder>::Branch {
237 node: node.clone(),
238 short_key: key,
239 masks,
240 };
241 let path = Nibbles::from_nibbles([1]);
242 let (proof, branch) = child.into_proof_trie_node(path, &mut Vec::new()).unwrap();
243
244 assert_eq!(
245 proof,
246 ProofTrieNode { path, node: TrieNode::Extension(extension.clone()), masks: None }
247 );
248 assert_eq!(
249 branch,
250 Some(ProofTrieNode {
251 path: path.join(&key),
252 node: TrieNode::Branch(node.clone()),
253 masks,
254 })
255 );
256 let child = ProofTrieBranchChild::<StorageDeferredValueEncoder>::Branch {
257 node,
258 short_key: key,
259 masks,
260 };
261 let (rlp, freed) = child.into_rlp(&mut Vec::new()).unwrap();
262 assert_eq!(rlp, RlpNode::from_rlp(&alloy_rlp::encode(extension)));
263 assert_eq!(freed.unwrap().len(), 2);
264 }
265 }
266
267 #[test]
268 fn test_trim_nibbles_prefix_basic() {
269 // Create nibbles [1, 2, 3, 4, 5, 6]
270 let nibbles = Nibbles::from_nibbles([1, 2, 3, 4, 5, 6]);
271
272 // Trim first 2 nibbles
273 let trimmed = trim_nibbles_prefix(&nibbles, 2);
274 assert_eq!(trimmed.len(), 4);
275
276 // Verify the remaining nibbles are [3, 4, 5, 6]
277 assert_eq!(trimmed.get(0), Some(3));
278 assert_eq!(trimmed.get(1), Some(4));
279 assert_eq!(trimmed.get(2), Some(5));
280 assert_eq!(trimmed.get(3), Some(6));
281 }
282
283 #[test]
284 fn test_trim_nibbles_prefix_zero() {
285 // Create nibbles [10, 11, 12, 13]
286 let nibbles = Nibbles::from_nibbles([10, 11, 12, 13]);
287
288 // Trim zero nibbles - should return identical nibbles
289 let trimmed = trim_nibbles_prefix(&nibbles, 0);
290 assert_eq!(trimmed, nibbles);
291 }
292
293 #[test]
294 fn test_trim_nibbles_prefix_all() {
295 // Create nibbles [1, 2, 3, 4]
296 let nibbles = Nibbles::from_nibbles([1, 2, 3, 4]);
297
298 // Trim all nibbles - should return empty
299 let trimmed = trim_nibbles_prefix(&nibbles, 4);
300 assert!(trimmed.is_empty());
301 }
302
303 #[test]
304 fn test_trim_nibbles_prefix_empty() {
305 // Create empty nibbles
306 let nibbles = Nibbles::new();
307
308 // Trim zero from empty - should return empty
309 let trimmed = trim_nibbles_prefix(&nibbles, 0);
310 assert!(trimmed.is_empty());
311 }
312}