1#[cfg(not(feature = "std"))]
2use alloc::{boxed::Box, vec::Vec};
3use ethrex_crypto::{Crypto, NativeCrypto};
4use ethrex_rlp::encode::RLPEncode;
5
6use crate::ValueRLP;
7use crate::nibbles::Nibbles;
8use crate::node::NodeRemoveResult;
9use crate::node_hash::NodeHash;
10use crate::{
11 TrieDB,
12 error::{ExtensionNodeErrorData, InconsistentTreeError, TrieError},
13};
14
15use super::{BranchNode, Node, NodeRef, ValueOrHash};
16
17#[derive(
20 Debug,
21 Clone,
22 PartialEq,
23 serde::Serialize,
24 serde::Deserialize,
25 rkyv::Serialize,
26 rkyv::Deserialize,
27 rkyv::Archive,
28)]
29pub struct ExtensionNode {
30 pub prefix: Nibbles,
31 pub child: NodeRef,
32}
33
34impl ExtensionNode {
35 pub const fn new(prefix: Nibbles, child: NodeRef) -> Self {
37 Self { prefix, child }
38 }
39
40 pub fn get(&self, db: &dyn TrieDB, mut path: Nibbles) -> Result<Option<ValueRLP>, TrieError> {
42 if path.skip_prefix(&self.prefix) {
45 let child_node = self.child.get_node(db, path.current())?.ok_or_else(|| {
46 TrieError::InconsistentTree(Box::new(
47 InconsistentTreeError::ExtensionNodeChildNotFound(ExtensionNodeErrorData {
48 node_hash: self
49 .child
50 .compute_hash(&NativeCrypto)
51 .finalize(&NativeCrypto),
52 extension_node_hash: self
53 .compute_hash(&NativeCrypto)
54 .finalize(&NativeCrypto),
55 extension_node_prefix: self.prefix.clone(),
56 node_path: path.current(),
57 }),
58 ))
59 })?;
60
61 child_node.get(db, path)
62 } else {
63 Ok(None)
64 }
65 }
66
67 pub fn insert(
70 &mut self,
71 db: &dyn TrieDB,
72 path: Nibbles,
73 value: ValueOrHash,
74 ) -> Result<Option<Node>, TrieError> {
75 let match_index = path.count_prefix(&self.prefix);
86 if match_index == self.prefix.len() {
87 let path = path.offset(match_index);
88 let Some(child_node) = self.child.get_node_mut(db, path.current())? else {
90 return Err(TrieError::InconsistentTree(Box::new(
91 InconsistentTreeError::ExtensionNodeChildNotFound(ExtensionNodeErrorData {
92 node_hash: self
93 .child
94 .compute_hash(&NativeCrypto)
95 .finalize(&NativeCrypto),
96 extension_node_hash: self
97 .compute_hash(&NativeCrypto)
98 .finalize(&NativeCrypto),
99 extension_node_prefix: self.prefix.clone(),
100 node_path: path.current(),
101 }),
102 )));
103 };
104 child_node.insert(db, path, value)?;
105 self.child.clear_hash();
106 Ok(None)
107 } else if match_index == 0 {
108 let mut new_node = if self.prefix.len() == 1 {
109 self.child.clone()
110 } else {
111 Node::from(ExtensionNode::new(
112 self.prefix.offset(1),
113 self.child.clone(),
114 ))
115 .into()
116 };
117 let mut choices = BranchNode::EMPTY_CHOICES;
118 let mut branch_node = if self.prefix.at(0) == 16 {
119 match new_node.get_node_mut(db, path.current())? {
120 Some(Node::Leaf(leaf)) => {
121 BranchNode::new_with_value(choices, leaf.value.clone())
122 }
123 Some(_) => {
124 return Err(TrieError::InconsistentTree(Box::new(
125 InconsistentTreeError::ExtensionNodeChildDiffers(
126 ExtensionNodeErrorData {
127 node_hash: new_node
128 .compute_hash(&NativeCrypto)
129 .finalize(&NativeCrypto),
130 extension_node_hash: self
131 .compute_hash(&NativeCrypto)
132 .finalize(&NativeCrypto),
133 extension_node_prefix: self.prefix.clone(),
134 node_path: path.current(),
135 },
136 ),
137 )));
138 }
139 None => {
140 return Err(TrieError::InconsistentTree(Box::new(
141 InconsistentTreeError::ExtensionNodeChildNotFound(
142 ExtensionNodeErrorData {
143 node_hash: new_node
144 .compute_hash(&NativeCrypto)
145 .finalize(&NativeCrypto),
146 extension_node_hash: self
147 .compute_hash(&NativeCrypto)
148 .finalize(&NativeCrypto),
149 extension_node_prefix: self.prefix.clone(),
150 node_path: path.current(),
151 },
152 ),
153 )));
154 }
155 }
156 } else {
157 choices[self.prefix.at(0)] = new_node;
158 BranchNode::new(choices)
159 };
160 branch_node.insert(db, path, value)?;
161 Ok(Some(branch_node.into()))
162 } else {
163 let mut new_extension =
164 ExtensionNode::new(self.prefix.offset(match_index), self.child.clone());
165 let new_node = new_extension
166 .insert(db, path.offset(match_index), value)?
167 .unwrap_or(new_extension.into());
168 self.prefix = self.prefix.slice(0, match_index);
169 self.child = new_node.into();
170 Ok(None)
171 }
172 }
173
174 pub fn remove(
175 &mut self,
176 db: &dyn TrieDB,
177 mut path: Nibbles,
178 ) -> Result<(Option<NodeRemoveResult>, Option<ValueRLP>), TrieError> {
179 if path.skip_prefix(&self.prefix) {
189 let Some(child_node) = self.child.get_node_mut(db, path.current())? else {
190 return Err(TrieError::InconsistentTree(Box::new(
191 InconsistentTreeError::ExtensionNodeChildNotFound(ExtensionNodeErrorData {
192 node_hash: self
193 .child
194 .compute_hash(&NativeCrypto)
195 .finalize(&NativeCrypto),
196 extension_node_hash: self
197 .compute_hash(&NativeCrypto)
198 .finalize(&NativeCrypto),
199 extension_node_prefix: self.prefix.clone(),
200 node_path: path.current(),
201 }),
202 )));
203 };
204 let (empty_trie, old_value) = child_node.remove(db, path)?;
206 let result = if empty_trie {
208 Ok((None, old_value))
209 } else {
210 let node = match child_node {
211 branch_node @ Node::Branch(_) => {
213 self.child = (*branch_node).clone().into();
214 NodeRemoveResult::Mutated
215 }
216 Node::Extension(extension_node) => {
218 let mut extension_node = extension_node.take();
219 let mut self_node = self.take();
220 self_node.prefix.extend(&extension_node.prefix);
221 extension_node.prefix = self_node.prefix;
222 NodeRemoveResult::New(extension_node.into())
223 }
224 Node::Leaf(leaf_node) => {
226 let mut leaf_node = leaf_node.take();
227 let mut self_node = self.take();
228 self_node.prefix.extend(&leaf_node.partial);
229 leaf_node.partial = self_node.prefix;
230 NodeRemoveResult::New(leaf_node.into())
231 }
232 };
233 Ok((Some(node), old_value))
234 };
235 self.child.clear_hash();
236 result
237 } else {
238 Ok((Some(NodeRemoveResult::Mutated), None))
239 }
240 }
241
242 pub fn compute_hash(&self, crypto: &(impl Crypto + ?Sized)) -> NodeHash {
244 self.compute_hash_no_alloc(&mut vec![], crypto)
245 }
246
247 pub fn compute_hash_no_alloc(
249 &self,
250 buf: &mut Vec<u8>,
251 crypto: &(impl Crypto + ?Sized),
252 ) -> NodeHash {
253 buf.clear();
254 self.encode(buf);
255 let hash = NodeHash::from_encoded(buf, crypto);
256 buf.clear();
257 hash
258 }
259
260 pub fn get_path(
264 &self,
265 db: &dyn TrieDB,
266 mut path: Nibbles,
267 node_path: &mut Vec<Vec<u8>>,
268 ) -> Result<(), TrieError> {
269 let encoded = self.encode_to_vec();
271 if encoded.len() >= 32 {
272 node_path.push(encoded);
273 };
274 if path.skip_prefix(&self.prefix) {
276 let child_node = self.child.get_node(db, path.current())?.ok_or_else(|| {
277 TrieError::InconsistentTree(Box::new(
278 InconsistentTreeError::ExtensionNodeChildNotFound(ExtensionNodeErrorData {
279 node_hash: self
280 .child
281 .compute_hash(&NativeCrypto)
282 .finalize(&NativeCrypto),
283 extension_node_hash: self
284 .compute_hash(&NativeCrypto)
285 .finalize(&NativeCrypto),
286 extension_node_prefix: self.prefix.clone(),
287 node_path: path.current(),
288 }),
289 ))
290 })?;
291 child_node.get_path(db, path, node_path)?;
292 }
293 Ok(())
294 }
295
296 pub fn take(&mut self) -> Self {
300 ExtensionNode {
301 prefix: self.prefix.take(),
302 child: self.child.clone(),
303 }
304 }
305}
306
307#[cfg(test)]
308mod test {
309 use ethrex_crypto::NativeCrypto;
310 use ethrex_rlp::{decode::RLPDecode, encode::RLPEncode};
311
312 use super::*;
313 use crate::{Trie, node::LeafNode, pmt_node};
314
315 #[test]
316 fn new() {
317 let node = ExtensionNode::new(Nibbles::default(), Default::default());
318
319 assert_eq!(node.prefix.len(), 0);
320 assert_eq!(node.child, Default::default());
321 }
322
323 #[test]
324 fn get_some() {
325 let trie = Trie::new_temp();
326 let node = pmt_node! { @(trie)
327 extension { [0], branch {
328 0 => leaf { vec![16] => vec![0x12, 0x34, 0x56, 0x78] },
329 1 => leaf { vec![16] => vec![0x34, 0x56, 0x78, 0x9A] },
330 } }
331 };
332
333 assert_eq!(
334 node.get(trie.db.as_ref(), Nibbles::from_bytes(&[0x00]))
335 .unwrap(),
336 Some(vec![0x12, 0x34, 0x56, 0x78]),
337 );
338 assert_eq!(
339 node.get(trie.db.as_ref(), Nibbles::from_bytes(&[0x01]))
340 .unwrap(),
341 Some(vec![0x34, 0x56, 0x78, 0x9A]),
342 );
343 }
344
345 #[test]
346 fn get_none() {
347 let trie = Trie::new_temp();
348 let node = pmt_node! { @(trie)
349 extension { [0], branch {
350 0 => leaf { vec![16] => vec![0x12, 0x34, 0x56, 0x78] },
351 1 => leaf { vec![16] => vec![0x34, 0x56, 0x78, 0x9A] },
352 } }
353 };
354
355 assert_eq!(
356 node.get(trie.db.as_ref(), Nibbles::from_bytes(&[0x02]))
357 .unwrap(),
358 None,
359 );
360 }
361
362 #[test]
363 fn insert_passthrough() {
364 let trie = Trie::new_temp();
365 let mut node = pmt_node! { @(trie)
366 extension { [0], branch {
367 0 => leaf { vec![16] => vec![0x12, 0x34, 0x56, 0x78] },
368 1 => leaf { vec![16] => vec![0x34, 0x56, 0x78, 0x9A] },
369 } }
370 };
371
372 let none = node
373 .insert(
374 trie.db.as_ref(),
375 Nibbles::from_bytes(&[0x02]),
376 Vec::new().into(),
377 )
378 .unwrap();
379 assert!(none.is_none());
380
381 assert_eq!(node.prefix.as_ref(), &[0]);
382 }
383
384 #[test]
385 fn insert_branch() {
386 let trie = Trie::new_temp();
387 let mut node = pmt_node! { @(trie)
388 extension { [0], branch {
389 0 => leaf { vec![16] => vec![0x12, 0x34, 0x56, 0x78] },
390 1 => leaf { vec![16] => vec![0x34, 0x56, 0x78, 0x9A] },
391 } }
392 };
393
394 let node = node
395 .insert(
396 trie.db.as_ref(),
397 Nibbles::from_bytes(&[0x10]),
398 vec![0x20].into(),
399 )
400 .unwrap();
401 let node = match node {
402 Some(Node::Branch(x)) => x,
403 _ => panic!("expected a branch node"),
404 };
405 assert_eq!(
406 node.get(trie.db.as_ref(), Nibbles::from_bytes(&[0x10]))
407 .unwrap(),
408 Some(vec![0x20])
409 );
410 }
411
412 #[test]
413 fn insert_branch_extension() {
414 let trie = Trie::new_temp();
415 let mut node = pmt_node! { @(trie)
416 extension { [0, 0], branch {
417 0 => leaf { vec![16] => vec![0x12, 0x34, 0x56, 0x78] },
418 1 => leaf { vec![16]=> vec![0x34, 0x56, 0x78, 0x9A] },
419 } }
420 };
421
422 let node = node
423 .insert(
424 trie.db.as_ref(),
425 Nibbles::from_bytes(&[0x10]),
426 vec![0x20].into(),
427 )
428 .unwrap();
429 let node = match node {
430 Some(Node::Branch(x)) => x,
431 _ => panic!("expected a branch node"),
432 };
433 assert_eq!(
434 node.get(trie.db.as_ref(), Nibbles::from_bytes(&[0x10]))
435 .unwrap(),
436 Some(vec![0x20])
437 );
438 }
439
440 #[test]
441 fn insert_extension_branch() {
442 let trie = Trie::new_temp();
443 let mut node = pmt_node! { @(trie)
444 extension { [0, 0], branch {
445 0 => leaf { vec![16] => vec![0x12, 0x34, 0x56, 0x78] },
446 1 => leaf { vec![16] => vec![0x34, 0x56, 0x78, 0x9A] },
447 } }
448 };
449
450 let path = Nibbles::from_bytes(&[0x01]);
451 let value = vec![0x02];
452
453 let none = node
454 .insert(trie.db.as_ref(), path.clone(), value.clone().into())
455 .unwrap();
456
457 assert!(none.is_none());
458 assert_eq!(node.get(trie.db.as_ref(), path).unwrap(), Some(value));
459 }
460
461 #[test]
462 fn insert_extension_branch_extension() {
463 let trie = Trie::new_temp();
464 let mut node = pmt_node! { @(trie)
465 extension { [0, 0], branch {
466 0 => leaf { vec![16] => vec![0x12, 0x34, 0x56, 0x78] },
467 1 => leaf { vec![16] => vec![0x34, 0x56, 0x78, 0x9A] },
468 } }
469 };
470
471 let path = Nibbles::from_bytes(&[0x01]);
472 let value = vec![0x04];
473
474 let none = node
475 .insert(trie.db.as_ref(), path.clone(), value.clone().into())
476 .unwrap();
477
478 assert!(none.is_none());
479 assert_eq!(node.get(trie.db.as_ref(), path).unwrap(), Some(value));
480 }
481
482 #[test]
483 fn remove_none() {
484 let trie = Trie::new_temp();
485 let mut node = pmt_node! { @(trie)
486 extension { [0], branch {
487 0 => leaf { vec![16] => vec![0x00] },
488 1 => leaf { vec![16] => vec![0x01] },
489 } }
490 };
491
492 let (node, value) = node
493 .remove(trie.db.as_ref(), Nibbles::from_bytes(&[0x02]))
494 .unwrap();
495
496 assert!(matches!(node, Some(NodeRemoveResult::Mutated)));
497 assert_eq!(value, None);
498 }
499
500 #[test]
501 fn remove_into_leaf() {
502 let trie = Trie::new_temp();
503 let mut node = pmt_node! { @(trie)
504 extension { [0], branch {
505 0 => leaf { vec![16] => vec![0x00] },
506 1 => leaf { vec![16] => vec![0x01] },
507 } }
508 };
509
510 let (node, value) = node
511 .remove(trie.db.as_ref(), Nibbles::from_bytes(&[0x01]))
512 .unwrap();
513
514 assert!(matches!(node, Some(NodeRemoveResult::New(Node::Leaf(_)))));
515 assert_eq!(value, Some(vec![0x01]));
516 }
517
518 #[test]
519 fn remove_into_extension() {
520 let trie = Trie::new_temp();
521 let mut node = pmt_node! { @(trie)
522 extension { [0], branch {
523 0 => leaf { vec![16] => vec![0x00] },
524 1 => extension { [0], branch {
525 0 => leaf { vec![16] => vec![0x01, 0x00] },
526 1 => leaf { vec![16] => vec![0x01, 0x01] },
527 } },
528 } }
529 };
530
531 let (node, value) = node
532 .remove(trie.db.as_ref(), Nibbles::from_bytes(&[0x00]))
533 .unwrap();
534
535 assert!(matches!(
536 node,
537 Some(NodeRemoveResult::New(Node::Extension(_)))
538 ));
539 assert_eq!(value, Some(vec![0x00]));
540 }
541
542 #[test]
543 fn compute_hash() {
544 let leaf_node_a = LeafNode::new(Nibbles::from_hex(vec![0, 16]), vec![0x12, 0x34]);
554 let leaf_node_b = LeafNode::new(Nibbles::from_hex(vec![0, 16]), vec![0x56, 0x78]);
555 let mut choices = BranchNode::EMPTY_CHOICES;
556 choices[0] = leaf_node_a.compute_hash(&NativeCrypto).into();
557 choices[1] = leaf_node_b.compute_hash(&NativeCrypto).into();
558 let branch_node = BranchNode::new(choices);
559 let node = ExtensionNode::new(
560 Nibbles::from_hex(vec![0, 0]),
561 branch_node.compute_hash(&NativeCrypto).into(),
562 );
563
564 assert_eq!(
565 node.compute_hash(&NativeCrypto).as_ref(),
566 &[
567 0xDD, 0x82, 0x00, 0x00, 0xD9, 0xC4, 0x30, 0x82, 0x12, 0x34, 0xC4, 0x30, 0x82, 0x56,
568 0x78, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
569 0x80, 0x80,
570 ],
571 );
572 }
573
574 #[test]
575 fn compute_hash_long() {
576 let leaf_node_a = LeafNode::new(
586 Nibbles::from_hex(vec![0, 16]),
587 vec![0x12, 0x34, 0x56, 0x78, 0x9A],
588 );
589 let leaf_node_b = LeafNode::new(
590 Nibbles::from_hex(vec![0, 16]),
591 vec![0x34, 0x56, 0x78, 0x9A, 0xBC],
592 );
593 let mut choices = BranchNode::EMPTY_CHOICES;
594 choices[0] = leaf_node_a.compute_hash(&NativeCrypto).into();
595 choices[1] = leaf_node_b.compute_hash(&NativeCrypto).into();
596 let branch_node = BranchNode::new(choices);
597 let node = ExtensionNode::new(
598 Nibbles::from_hex(vec![0, 0]),
599 branch_node.compute_hash(&NativeCrypto).into(),
600 );
601
602 assert_eq!(
603 node.compute_hash(&NativeCrypto).as_ref(),
604 &[
605 0xFA, 0xBA, 0x42, 0x79, 0xB3, 0x9B, 0xCD, 0xEB, 0x7C, 0x53, 0x0F, 0xD7, 0x6E, 0x5A,
606 0xA3, 0x48, 0xD3, 0x30, 0x76, 0x26, 0x14, 0x84, 0x55, 0xA0, 0xAE, 0xFE, 0x0F, 0x52,
607 0x89, 0x5F, 0x36, 0x06,
608 ],
609 );
610 }
611
612 #[test]
613 fn symmetric_encoding_a() {
614 let node: Node = pmt_node! { @(trie)
615 extension { [0], branch {
616 0 => leaf { vec![16] => vec![0x12, 0x34, 0x56, 0x78] },
617 1 => leaf { vec![16] => vec![0x34, 0x56, 0x78, 0x9A] },
618 } }
619 }
620 .into();
621 assert_eq!(Node::decode(&node.encode_to_vec()).unwrap(), node)
622 }
623
624 #[test]
625 fn symmetric_encoding_b() {
626 let node: Node = pmt_node! { @(trie)
627 extension { [0], branch {
628 0 => leaf { vec![16] => vec![0x00] },
629 1 => extension { [0], branch {
630 0 => leaf { vec![16] => vec![0x01, 0x00] },
631 1 => leaf { vec![16] => vec![0x01, 0x01] },
632 } },
633 } }
634 }
635 .into();
636
637 assert_eq!(Node::decode(&node.encode_to_vec()).unwrap(), node)
638 }
639
640 #[test]
641 fn symmetric_encoding_c() {
642 let node: Node = pmt_node! { @(trie)
643 extension { [0], branch {
644 0 => leaf { vec![16] => vec![0x00] },
645 1 => extension { [0], branch {
646 0 => leaf { vec![16] => vec![0x01, 0x00] },
647 1 => leaf { vec![16] => vec![0x01, 0x01] },
648 2 => leaf { vec![16] => vec![0x01, 0x00] },
649 3 => leaf { vec![16] => vec![0x03, 0x01] },
650 4 => leaf { vec![16] => vec![0x04, 0x00] },
651 5 => leaf { vec![16] => vec![0x05, 0x01] },
652 6 => leaf { vec![16] => vec![0x06, 0x00] },
653 7 => leaf { vec![16] => vec![0x07, 0x01] },
654 8 => leaf { vec![16] => vec![0x08, 0x00] },
655 9 => leaf { vec![16] => vec![0x09, 0x01] },
656 10 => leaf { vec![16] => vec![0x10, 0x00] },
657 11 => leaf { vec![16] => vec![0x11, 0x01] },
658 } },
659 } }
660 }
661 .into();
662 assert_eq!(Node::decode(&node.encode_to_vec()).unwrap(), node)
663 }
664}