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#[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 pub const fn new(partial: Nibbles, value: ValueRLP) -> Self {
39 Self { partial, value }
40 }
41
42 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 pub fn insert(&mut self, path: Nibbles, value: ValueOrHash) -> Result<Option<Node>, TrieError> {
53 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 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 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 ValueOrHash::Hash(_) => todo!("handle override case (error?)"),
100 },
101 )
102 } else {
103 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 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 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 pub fn compute_hash(&self, crypto: &(impl Crypto + ?Sized)) -> NodeHash {
145 self.compute_hash_no_alloc(&mut vec![], crypto)
146 }
147
148 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 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 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 #[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}