Skip to main content

ethrex_trie/node/
leaf.rs

1#[cfg(not(feature = "std"))]
2use alloc::{string::ToString, vec::Vec};
3use core::mem;
4
5use ethrex_crypto::Crypto;
6use ethrex_rlp::encode::RLPEncode;
7
8use crate::{
9    ValueRLP,
10    error::TrieError,
11    nibbles::Nibbles,
12    node::{BranchNode, NodeRemoveResult},
13    node_hash::NodeHash,
14};
15
16use super::{ExtensionNode, Node, ValueOrHash};
17/// Leaf Node of an an Ethereum Compatible Patricia Merkle Trie
18/// Contains the node's hash, value & path
19#[derive(
20    Debug,
21    Clone,
22    Default,
23    PartialEq,
24    Eq,
25    serde::Serialize,
26    serde::Deserialize,
27    rkyv::Deserialize,
28    rkyv::Serialize,
29    rkyv::Archive,
30)]
31pub struct LeafNode {
32    pub partial: Nibbles,
33    pub value: ValueRLP,
34}
35
36impl LeafNode {
37    /// Creates a new leaf node and stores the given (path, value) pair
38    pub const fn new(partial: Nibbles, value: ValueRLP) -> Self {
39        Self { partial, value }
40    }
41
42    /// Returns the stored value if the given path matches the stored path
43    pub fn get(&self, path: Nibbles) -> Result<Option<ValueRLP>, TrieError> {
44        if self.partial == path {
45            Ok(Some(self.value.clone()))
46        } else {
47            Ok(None)
48        }
49    }
50
51    /// Stores the received value and returns the new root of the subtrie previously consisting of self
52    pub fn insert(&mut self, path: Nibbles, value: ValueOrHash) -> Result<Option<Node>, TrieError> {
53        /* Possible flow paths:
54            Leaf { SelfValue } -> Leaf { Value }
55            Leaf { SelfValue } -> Extension { Branch { [Self,...] Value } }
56            Leaf { SelfValue } -> Extension { Branch { [ Leaf { Value } , ... ], SelfValue} }
57            Leaf { SelfValue } -> Branch { [ Leaf { Value }, Self, ... ], None}
58        */
59        // If the path matches the stored path, update the value and return self
60        if self.partial == path {
61            match value {
62                ValueOrHash::Value(value) => self.value = value,
63                ValueOrHash::Hash(_) => {
64                    return Err(TrieError::Verify(
65                        "attempt to override proof node with external hash".to_string(),
66                    ));
67                }
68            }
69            Ok(None)
70        } else {
71            let match_index = path.count_prefix(&self.partial);
72            let self_choice_idx = self.partial.at(match_index);
73            let new_leaf_choice_idx = path.at(match_index);
74            self.partial = self.partial.offset(match_index + 1);
75
76            let branch_node = if self_choice_idx == 16 {
77                // Create a new leaf node and store the value in it
78                // Create a new branch node with the leaf as a child and store self's value
79                // Branch { [ Leaf { Value } , ... ], SelfValue}
80                let mut choices = BranchNode::EMPTY_CHOICES;
81                choices[new_leaf_choice_idx] = match value {
82                    ValueOrHash::Value(value) => {
83                        Node::from(LeafNode::new(path.offset(match_index + 1), value)).into()
84                    }
85                    ValueOrHash::Hash(hash) => hash.into(),
86                };
87                BranchNode::new_with_value(choices, mem::take(&mut self.value))
88            } else if new_leaf_choice_idx == 16 {
89                // Create a branch node with self as a child and store the value in the branch node
90                // Branch { [Self,...], Value }
91                let mut choices = BranchNode::EMPTY_CHOICES;
92                let child: Node = self.take().into();
93                choices[self_choice_idx] = child.into();
94                BranchNode::new_with_value(
95                    choices,
96                    match value {
97                        ValueOrHash::Value(value) => value,
98                        // Value in branches don't happen in our use-case.
99                        ValueOrHash::Hash(_) => todo!("handle override case (error?)"),
100                    },
101                )
102            } else {
103                // Create a new leaf node and store the path and value in it
104                // Create a new branch node with the leaf and self as children
105                // Branch { [ Leaf { Path, Value }, Self, ... ], None, None}
106                let mut choices = BranchNode::EMPTY_CHOICES;
107                choices[new_leaf_choice_idx] = match value {
108                    ValueOrHash::Value(value) => {
109                        Node::from(LeafNode::new(path.offset(match_index + 1), value)).into()
110                    }
111                    ValueOrHash::Hash(hash) => hash.into(),
112                };
113                let child: Node = self.take().into();
114                choices[self_choice_idx] = child.into();
115                BranchNode::new(choices)
116            };
117
118            let final_node = if match_index == 0 {
119                branch_node.into()
120            } else {
121                // Create an extension node with the branch node as child
122                // Extension { BranchNode }
123                ExtensionNode::new(path.slice(0, match_index), Node::from(branch_node).into())
124                    .into()
125            };
126
127            Ok(Some(final_node))
128        }
129    }
130
131    /// Removes own value if the path matches own path and returns self and the value if it was removed
132    pub fn remove(
133        &mut self,
134        path: Nibbles,
135    ) -> Result<(Option<NodeRemoveResult>, Option<ValueRLP>), TrieError> {
136        Ok(if self.partial == path {
137            (None, Some(mem::take(&mut self.value)))
138        } else {
139            (Some(NodeRemoveResult::Mutated), None)
140        })
141    }
142
143    /// Computes the node's hash
144    pub fn compute_hash(&self, crypto: &(impl Crypto + ?Sized)) -> NodeHash {
145        self.compute_hash_no_alloc(&mut vec![], crypto)
146    }
147
148    /// Computes the node's hash, using the provided buffer
149    pub fn compute_hash_no_alloc(
150        &self,
151        buf: &mut Vec<u8>,
152        crypto: &(impl Crypto + ?Sized),
153    ) -> NodeHash {
154        buf.clear();
155        self.encode(buf);
156        let hash = NodeHash::from_encoded(buf, crypto);
157        buf.clear();
158        hash
159    }
160
161    /// Encodes the node and appends it to `node_path` if the encoded node is 32 or more bytes long
162    pub fn get_path(&self, node_path: &mut Vec<Vec<u8>>) -> Result<(), TrieError> {
163        let encoded = self.encode_to_vec();
164        if encoded.len() >= 32 {
165            node_path.push(encoded);
166        }
167        Ok(())
168    }
169
170    /// Creates a new node by emptying `self` partial and its value
171    ///
172    /// This is a way to "consume" the node when we just have a mutable reference to it
173    pub fn take(&mut self) -> Self {
174        LeafNode {
175            partial: self.partial.take(),
176            value: mem::take(&mut self.value),
177        }
178    }
179}
180
181#[cfg(test)]
182mod test {
183    use ethrex_crypto::NativeCrypto;
184    use ethrex_rlp::{decode::RLPDecode, encode::RLPEncode};
185
186    use super::*;
187    use crate::{Trie, pmt_node};
188
189    #[test]
190    fn new() {
191        let node = LeafNode::new(Default::default(), Default::default());
192        assert_eq!(node.value, ValueRLP::default());
193    }
194
195    #[test]
196    fn get_some() {
197        let node = pmt_node! { @(trie)
198            leaf { vec![1, 2, 16] => vec![0x12, 0x34, 0x56, 0x78] }
199        };
200
201        assert_eq!(
202            node.get(Nibbles::from_bytes(&[0x12])).unwrap(),
203            Some(vec![0x12, 0x34, 0x56, 0x78]),
204        );
205    }
206
207    #[test]
208    fn get_none() {
209        let node = pmt_node! { @(trie)
210            leaf { vec![1,2,16] => vec![0x12, 0x34, 0x56, 0x78] }
211        };
212
213        assert!(node.get(Nibbles::from_bytes(&[0x34])).unwrap().is_none());
214    }
215
216    #[test]
217    fn insert_replace() {
218        let mut node = pmt_node! { @(trie)
219            leaf { vec![1,2,16] => vec![0x12, 0x34, 0x56, 0x78] }
220        };
221
222        assert!(
223            node.insert(Nibbles::from_bytes(&[0x12]), vec![0x13].into())
224                .unwrap()
225                .is_none()
226        );
227
228        assert_eq!(node.value, vec![0x13]);
229    }
230
231    #[test]
232    fn insert_branch() {
233        let trie = Trie::new_temp();
234        let mut node = pmt_node! { @(trie)
235            leaf { vec![1,2,16] => vec![0x12, 0x34, 0x56, 0x78] }
236        };
237        let path = Nibbles::from_bytes(&[0x22]);
238        let value = vec![0x23];
239        let node = node.insert(path.clone(), value.clone().into()).unwrap();
240        let node = match node {
241            Some(Node::Branch(x)) => x,
242            _ => panic!("expected a branch node"),
243        };
244        assert_eq!(node.get(trie.db.as_ref(), path).unwrap(), Some(value));
245    }
246
247    #[test]
248    fn insert_extension_branch() {
249        let trie = Trie::new_temp();
250        let mut node = pmt_node! { @(trie)
251            leaf { vec![1,2,16] => vec![0x12, 0x34, 0x56, 0x78] }
252        };
253
254        let path = Nibbles::from_bytes(&[0x13]);
255        let value = vec![0x15];
256
257        let node = node.insert(path.clone(), value.clone().into()).unwrap();
258
259        assert!(matches!(node, Some(Node::Extension(_))));
260        assert_eq!(
261            node.unwrap().get(trie.db.as_ref(), path).unwrap(),
262            Some(value)
263        );
264    }
265
266    #[test]
267    fn insert_extension_branch_value_self() {
268        let trie = Trie::new_temp();
269        let mut node = pmt_node! { @(trie)
270            leaf { vec![1,2,16] => vec![0x12, 0x34, 0x56, 0x78] }
271        };
272
273        let path = Nibbles::from_bytes(&[0x12, 0x34]);
274        let value = vec![0x17];
275
276        let node = node.insert(path.clone(), value.clone().into()).unwrap();
277
278        assert!(matches!(node, Some(Node::Extension(_))));
279        assert_eq!(
280            node.unwrap().get(trie.db.as_ref(), path).unwrap(),
281            Some(value)
282        );
283    }
284
285    #[test]
286    fn insert_extension_branch_value_other() {
287        let trie = Trie::new_temp();
288        let mut node = pmt_node! { @(trie)
289            leaf { vec![1, 2, 3, 4, 16] => vec![0x12, 0x34, 0x56, 0x78] }
290        };
291
292        let path = Nibbles::from_bytes(&[0x12]);
293        let value = vec![0x17];
294
295        let node = node.insert(path.clone(), value.clone().into()).unwrap();
296
297        assert!(matches!(node, Some(Node::Extension(_))));
298        assert_eq!(
299            node.unwrap().get(trie.db.as_ref(), path).unwrap(),
300            Some(value)
301        );
302    }
303
304    // An insertion that returns branch [value=(x)] -> leaf (y) is not possible because of the path
305    // restrictions: nibbles come in pairs. If the first nibble is different, the node will be a
306    // branch but it cannot have a value. If the second nibble is different, then it'll be an
307    // extension followed by a branch with value and a child.
308
309    // Because of that, the two tests that would check those cases are neither necessary nor
310    // possible.
311
312    #[test]
313    fn remove_self() {
314        let mut node = LeafNode::new(
315            Nibbles::from_bytes(&[0x12, 0x34]),
316            vec![0x12, 0x34, 0x56, 0x78],
317        );
318        let (node, value) = node.remove(Nibbles::from_bytes(&[0x12, 0x34])).unwrap();
319
320        assert!(node.is_none());
321        assert_eq!(value, Some(vec![0x12, 0x34, 0x56, 0x78]));
322    }
323
324    #[test]
325    fn remove_none() {
326        let mut node = LeafNode::new(
327            Nibbles::from_bytes(&[0x12, 0x34]),
328            vec![0x12, 0x34, 0x56, 0x78],
329        );
330
331        let (node, value) = node.remove(Nibbles::from_bytes(&[0x12])).unwrap();
332
333        assert!(node.is_some());
334        assert_eq!(value, None);
335    }
336
337    #[test]
338    fn compute_hash_x() {
339        let node = LeafNode::new(Nibbles::from_bytes(b"key".as_ref()), b"value".to_vec());
340        let node_hash_ref = node.compute_hash(&NativeCrypto);
341        assert_eq!(
342            node_hash_ref.as_ref(),
343            &[
344                0xCB, 0x84, 0x20, 0x6B, 0x65, 0x79, 0x85, 0x76, 0x61, 0x6C, 0x75, 0x65
345            ],
346        );
347    }
348
349    #[test]
350    fn compute_hash_long() {
351        let node = LeafNode::new(
352            Nibbles::from_bytes(b"key".as_ref()),
353            b"a comparatively long value".to_vec(),
354        );
355
356        let node_hash_ref = node.compute_hash(&NativeCrypto);
357        assert_eq!(
358            node_hash_ref.as_ref(),
359            &[
360                0xEB, 0x92, 0x75, 0xB3, 0xAE, 0x09, 0x3A, 0x17, 0x75, 0x7C, 0xFB, 0x42, 0xF7, 0xD5,
361                0x57, 0xF9, 0xE5, 0x77, 0xBD, 0x5B, 0xEB, 0x86, 0xA8, 0x68, 0x49, 0x91, 0xA6, 0x5B,
362                0x87, 0x5F, 0x80, 0x7A,
363            ],
364        );
365    }
366
367    #[test]
368    fn symmetric_encoding_a() {
369        let node: Node = LeafNode::new(
370            Nibbles::from_bytes(b"key".as_ref()),
371            b"a comparatively long value".to_vec(),
372        )
373        .into();
374        assert_eq!(Node::decode(&node.encode_to_vec()).unwrap(), node)
375    }
376
377    #[test]
378    fn symmetric_encoding_b() {
379        let node: Node = LeafNode::new(
380            Nibbles::from_bytes(&[0x12, 0x34]),
381            vec![0x12, 0x34, 0x56, 0x78],
382        )
383        .into();
384        assert_eq!(Node::decode(&node.encode_to_vec()).unwrap(), node)
385    }
386
387    #[test]
388    fn symmetric_encoding_c() {
389        let node: Node = LeafNode::new(
390            Nibbles::from_bytes(&[]),
391            vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 20],
392        )
393        .into();
394        assert_eq!(Node::decode(&node.encode_to_vec()).unwrap(), node)
395    }
396}