1#[cfg(not(feature = "std"))]
2use alloc::{boxed::Box, string::ToString, vec::Vec};
3use core::mem;
4
5use ethrex_crypto::{Crypto, NativeCrypto};
6use ethrex_rlp::encode::RLPEncode;
7
8use crate::{
9 InconsistentTreeError, TrieDB, ValueRLP, error::TrieError, nibbles::Nibbles,
10 node::NodeRemoveResult, node_hash::NodeHash,
11};
12
13use super::{ExtensionNode, LeafNode, Node, NodeRef, ValueOrHash};
14
15#[derive(
18 Debug,
19 Clone,
20 PartialEq,
21 Default,
22 serde::Serialize,
23 serde::Deserialize,
24 rkyv::Serialize,
25 rkyv::Deserialize,
26 rkyv::Archive,
27)]
28pub struct BranchNode {
29 pub choices: [NodeRef; 16],
30 pub value: ValueRLP,
31}
32
33impl BranchNode {
34 const EMPTY_REF: NodeRef = NodeRef::Hash(NodeHash::Inline(([0; 31], 0)));
35
36 pub const EMPTY_CHOICES: [NodeRef; 16] = [Self::EMPTY_REF; 16];
38
39 pub fn new(choices: [NodeRef; 16]) -> Self {
41 Self {
42 choices,
43 value: Default::default(),
44 }
45 }
46
47 pub const fn new_with_value(choices: [NodeRef; 16], value: ValueRLP) -> Self {
49 Self { choices, value }
50 }
51
52 pub fn update(&mut self, new_value: ValueRLP) {
54 self.value = new_value;
55 }
56
57 pub fn get(&self, db: &dyn TrieDB, mut path: Nibbles) -> Result<Option<ValueRLP>, TrieError> {
59 if let Some(choice) = path.next_choice() {
62 let child_ref = &self.choices[choice];
64 if child_ref.is_valid() {
65 let child_node = child_ref.get_node(db, path.current())?.ok_or_else(|| {
66 TrieError::InconsistentTree(Box::new(
67 InconsistentTreeError::NodeNotFoundOnBranchNode(
68 child_ref
69 .compute_hash(&NativeCrypto)
70 .finalize(&NativeCrypto),
71 self.compute_hash(&NativeCrypto).finalize(&NativeCrypto),
72 path.current(),
73 ),
74 ))
75 })?;
76 child_node.get(db, path)
77 } else {
78 Ok(None)
79 }
80 } else {
81 Ok((!self.value.is_empty()).then_some(self.value.clone()))
83 }
84 }
85
86 pub fn insert(
88 &mut self,
89 db: &dyn TrieDB,
90 mut path: Nibbles,
91 value: ValueOrHash,
92 ) -> Result<(), TrieError> {
93 if let Some(choice) = path.next_choice() {
96 match (&mut self.choices[choice], value) {
97 (choice_ref, ValueOrHash::Value(value)) if !choice_ref.is_valid() => {
99 let new_leaf = LeafNode::new(path, value);
100 *choice_ref = Node::from(new_leaf).into()
101 }
102 (choice_ref, ValueOrHash::Value(value)) => {
104 let Some(choice_node) = choice_ref.get_node_mut(db, path.current())? else {
105 return Err(TrieError::InconsistentTree(Box::new(
106 InconsistentTreeError::NodeNotFoundOnBranchNode(
107 choice_ref
108 .compute_hash(&NativeCrypto)
109 .finalize(&NativeCrypto),
110 self.compute_hash(&NativeCrypto).finalize(&NativeCrypto),
111 path.current(),
112 ),
113 )));
114 };
115
116 choice_node.insert(db, path, value)?;
117 choice_ref.clear_hash();
118 }
119 (choice_ref, value @ ValueOrHash::Hash(hash)) => {
121 if !choice_ref.is_valid() {
122 *choice_ref = hash.into();
123 } else if path.is_empty() {
124 return Err(TrieError::Verify(
125 "attempt to override proof node with external hash".to_string(),
126 ));
127 } else {
128 let Some(choice_node) = choice_ref.get_node_mut(db, path.current())? else {
129 return Err(TrieError::InconsistentTree(Box::new(
130 InconsistentTreeError::NodeNotFoundOnBranchNode(
131 choice_ref
132 .compute_hash(&NativeCrypto)
133 .finalize(&NativeCrypto),
134 self.compute_hash(&NativeCrypto).finalize(&NativeCrypto),
135 path.current(),
136 ),
137 )));
138 };
139 choice_node.insert(db, path, value)?;
140 choice_ref.clear_hash();
141 }
142 }
143 }
144 } else if let ValueOrHash::Value(value) = value {
145 self.update(value);
147 } else {
148 todo!("handle override case (error?)")
150 }
151
152 Ok(())
153 }
154
155 pub fn remove(
159 &mut self,
160 db: &dyn TrieDB,
161 mut path: Nibbles,
162 ) -> Result<(Option<NodeRemoveResult>, Option<ValueRLP>), TrieError> {
163 let base_path = path.clone();
181
182 let value = if let Some(choice_index) = path.next_choice() {
185 if self.choices[choice_index].is_valid() {
186 let Some(child_node) =
187 self.choices[choice_index].get_node_mut(db, path.current())?
188 else {
189 return Err(TrieError::InconsistentTree(Box::new(
190 InconsistentTreeError::NodeNotFoundOnBranchNode(
191 self.choices[choice_index]
192 .compute_hash(&NativeCrypto)
193 .finalize(&NativeCrypto),
194 self.compute_hash(&NativeCrypto).finalize(&NativeCrypto),
195 path.current(),
196 ),
197 )));
198 };
199
200 let (empty_trie, old_value) = child_node.remove(db, path.clone())?;
202 if empty_trie {
203 self.choices[choice_index] = NodeHash::default().into();
205 }
206 self.choices[choice_index].clear_hash();
207 old_value
208 } else {
209 None
210 }
211 } else {
212 if !self.value.is_empty() {
214 Some(mem::take(&mut self.value))
215 } else {
216 None
217 }
218 };
219
220 let mut children = self
222 .choices
223 .iter_mut()
224 .enumerate()
225 .filter(|(_, child)| child.is_valid())
226 .collect::<Vec<_>>();
227 let new_node = match (children.len(), !self.value.is_empty()) {
228 (0, true) => NodeRemoveResult::New(
230 LeafNode::new(Nibbles::from_hex(vec![16]), mem::take(&mut self.value)).into(),
231 ),
232 (1, false) => {
234 let (choice_index, child_ref) = children.get_mut(0).unwrap();
235 let Some(child) = child_ref
236 .get_node_mut(db, base_path.current().append_new(*choice_index as u8))?
237 else {
238 return Err(TrieError::InconsistentTree(Box::new(
239 InconsistentTreeError::NodeNotFoundOnBranchNode(
240 child_ref
241 .compute_hash(&NativeCrypto)
242 .finalize(&NativeCrypto),
243 self.compute_hash(&NativeCrypto).finalize(&NativeCrypto),
244 base_path.current(),
245 ),
246 )));
247 };
248
249 let node = match child {
250 Node::Branch(_) => ExtensionNode::new(
252 Nibbles::from_hex(vec![*choice_index as u8]),
253 child_ref.clone(),
254 )
255 .into(),
256 Node::Extension(extension_node) => {
258 let mut extension_node = extension_node.take();
259 extension_node.prefix.prepend(*choice_index as u8);
260 extension_node.into()
261 }
262 Node::Leaf(leaf) => {
263 let mut leaf = leaf.take();
264 leaf.partial.prepend(*choice_index as u8);
265 leaf.into()
266 }
267 };
268 NodeRemoveResult::New(node)
269 }
270 _ => NodeRemoveResult::Mutated,
272 };
273 Ok((Some(new_node), value))
274 }
275
276 pub fn compute_hash(&self, crypto: &(impl Crypto + ?Sized)) -> NodeHash {
278 self.compute_hash_no_alloc(&mut vec![], crypto)
279 }
280
281 pub fn compute_hash_no_alloc(
283 &self,
284 buf: &mut Vec<u8>,
285 crypto: &(impl Crypto + ?Sized),
286 ) -> NodeHash {
287 buf.clear();
288 self.encode_into_vec(buf);
289 let hash = NodeHash::from_encoded(buf, crypto);
290 buf.clear();
291 hash
292 }
293
294 pub fn get_path(
298 &self,
299 db: &dyn TrieDB,
300 mut path: Nibbles,
301 node_path: &mut Vec<Vec<u8>>,
302 ) -> Result<(), TrieError> {
303 let encoded = self.encode_to_vec();
305 if encoded.len() >= 32 {
306 node_path.push(encoded);
307 };
308 if let Some(choice) = path.next_choice() {
310 let child_ref = &self.choices[choice];
312 if child_ref.is_valid() {
313 let child_node = child_ref.get_node(db, path.current())?.ok_or_else(|| {
314 TrieError::InconsistentTree(Box::new(
315 InconsistentTreeError::NodeNotFoundOnBranchNode(
316 child_ref
317 .compute_hash(&NativeCrypto)
318 .finalize(&NativeCrypto),
319 self.compute_hash(&NativeCrypto).finalize(&NativeCrypto),
320 path.current(),
321 ),
322 ))
323 })?;
324 child_node.get_path(db, path, node_path)?;
325 }
326 }
327 Ok(())
328 }
329}
330
331#[cfg(test)]
332mod test {
333 use ethereum_types::H256;
334 use ethrex_crypto::NativeCrypto;
335 use ethrex_rlp::{decode::RLPDecode, encode::RLPEncode};
336
337 use super::*;
338
339 use crate::{Trie, pmt_node};
340
341 #[test]
342 fn new() {
343 let node = BranchNode::new({
344 let mut choices = BranchNode::EMPTY_CHOICES;
345
346 choices[2] = NodeHash::Hashed(H256([2; 32])).into();
347 choices[5] = NodeHash::Hashed(H256([5; 32])).into();
348
349 choices
350 });
351
352 assert_eq!(
353 node.choices,
354 [
355 Default::default(),
356 Default::default(),
357 NodeHash::Hashed(H256([2; 32])).into(),
358 Default::default(),
359 Default::default(),
360 NodeHash::Hashed(H256([5; 32])).into(),
361 Default::default(),
362 Default::default(),
363 Default::default(),
364 Default::default(),
365 Default::default(),
366 Default::default(),
367 Default::default(),
368 Default::default(),
369 Default::default(),
370 Default::default(),
371 ],
372 );
373 }
374
375 #[test]
376 fn get_some() {
377 let trie = Trie::new_temp();
378 let node = pmt_node! { @(trie)
379 branch {
380 0 => leaf { vec![0,16] => vec![0x12, 0x34, 0x56, 0x78] },
381 1 => leaf { vec![0,16] => vec![0x34, 0x56, 0x78, 0x9A] },
382 }
383 };
384
385 assert_eq!(
386 node.get(trie.db.as_ref(), Nibbles::from_bytes(&[0x00]))
387 .unwrap(),
388 Some(vec![0x12, 0x34, 0x56, 0x78]),
389 );
390 assert_eq!(
391 node.get(trie.db.as_ref(), Nibbles::from_bytes(&[0x10]))
392 .unwrap(),
393 Some(vec![0x34, 0x56, 0x78, 0x9A]),
394 );
395 }
396
397 #[test]
398 fn get_none() {
399 let trie = Trie::new_temp();
400 let node = pmt_node! { @(trie)
401 branch {
402 0 => leaf { vec![0,16] => vec![0x12, 0x34, 0x56, 0x78] },
403 1 => leaf { vec![0,16] => vec![0x34, 0x56, 0x78, 0x9A] },
404 }
405 };
406
407 assert_eq!(
408 node.get(trie.db.as_ref(), Nibbles::from_bytes(&[0x20]))
409 .unwrap(),
410 None,
411 );
412 }
413
414 #[test]
415 fn insert_self() {
416 let trie = Trie::new_temp();
417 let mut node = pmt_node! { @(trie)
418 branch {
419 0 => leaf { vec![0, 16] => vec![0x12, 0x34, 0x56, 0x78] },
420 1 => leaf { vec![0, 16] => vec![0x34, 0x56, 0x78, 0x9A] },
421 }
422 };
423 let path = Nibbles::from_bytes(&[2]);
424 let value = vec![0x3];
425
426 node.insert(trie.db.as_ref(), path.clone(), value.clone().into())
427 .unwrap();
428
429 assert_eq!(node.get(trie.db.as_ref(), path).unwrap(), Some(value));
430 }
431
432 #[test]
433 fn insert_choice() {
434 let trie = Trie::new_temp();
435 let mut node = pmt_node! { @(trie)
436 branch {
437 0 => leaf { vec![0, 16] => vec![0x12, 0x34, 0x56, 0x78] },
438 1 => leaf { vec![0, 16] => vec![0x34, 0x56, 0x78, 0x9A] },
439 }
440 };
441
442 let path = Nibbles::from_bytes(&[0x20]);
443 let value = vec![0x21];
444
445 node.insert(trie.db.as_ref(), path.clone(), value.clone().into())
446 .unwrap();
447
448 assert_eq!(node.get(trie.db.as_ref(), path).unwrap(), Some(value));
449 }
450
451 #[test]
452 fn insert_passthrough() {
453 let trie = Trie::new_temp();
454 let node = pmt_node! { @(trie)
455 branch {
456 0 => leaf { vec![0, 16] => vec![0x12, 0x34, 0x56, 0x78] },
457 1 => leaf { vec![0, 16] => vec![0x34, 0x56, 0x78, 0x9A] },
458 }
459 };
460
461 let path = Nibbles::from_bytes(&[0x00]).offset(2);
463 let value = vec![0x1];
464
465 let mut new_node = node.clone();
466 new_node
467 .insert(trie.db.as_ref(), path, value.clone().into())
468 .unwrap();
469
470 assert_eq!(new_node.choices, node.choices);
471 assert_eq!(new_node.value, value);
472 }
473
474 #[test]
475 fn remove_choice_into_inner() {
476 let trie = Trie::new_temp();
477 let mut node = pmt_node! { @(trie)
478 branch {
479 0 => leaf { vec![0, 16] => vec![0x00] },
480 1 => leaf { vec![0, 16] => vec![0x10] },
481 }
482 };
483
484 let (node, value) = node
485 .remove(trie.db.as_ref(), Nibbles::from_bytes(&[0x00]))
486 .unwrap();
487
488 assert!(matches!(node, Some(NodeRemoveResult::New(Node::Leaf(_)))));
489 assert_eq!(value, Some(vec![0x00]));
490 }
491
492 #[test]
493 fn remove_choice() {
494 let trie = Trie::new_temp();
495 let mut node = pmt_node! { @(trie)
496 branch {
497 0 => leaf { vec![0, 16] => vec![0x00] },
498 1 => leaf { vec![0, 16] => vec![0x10] },
499 2 => leaf { vec![0, 16] => vec![0x10] },
500 }
501 };
502
503 let (node, value) = node
504 .remove(trie.db.as_ref(), Nibbles::from_bytes(&[0x00]))
505 .unwrap();
506
507 assert!(matches!(node, Some(NodeRemoveResult::Mutated)));
508 assert_eq!(value, Some(vec![0x00]));
509 }
510
511 #[test]
512 fn remove_choice_into_value() {
513 let trie = Trie::new_temp();
514 let mut node = pmt_node! { @(trie)
515 branch {
516 0 => leaf { vec![0, 16] => vec![0x00] },
517 } with_leaf { &[0x01] => vec![0xFF] }
518 };
519
520 let (node, value) = node
521 .remove(trie.db.as_ref(), Nibbles::from_bytes(&[0x00]))
522 .unwrap();
523
524 assert!(matches!(node, Some(NodeRemoveResult::New(Node::Leaf(_)))));
525 assert_eq!(value, Some(vec![0x00]));
526 }
527
528 #[test]
529 fn remove_value_into_inner() {
530 let trie = Trie::new_temp();
531 let mut node = pmt_node! { @(trie)
532 branch {
533 0 => leaf { vec![0, 16] => vec![0x00] },
534 } with_leaf { &[0x1] => vec![0xFF] }
535 };
536
537 let (node, value) = node
538 .remove(trie.db.as_ref(), Nibbles::from_bytes(&[]))
539 .unwrap();
540
541 assert!(matches!(node, Some(NodeRemoveResult::New(Node::Leaf(_)))));
542 assert_eq!(value, Some(vec![0xFF]));
543 }
544
545 #[test]
546 fn remove_value() {
547 let trie = Trie::new_temp();
548 let mut node = pmt_node! { @(trie)
549 branch {
550 0 => leaf { vec![0, 16] => vec![0x00] },
551 1 => leaf { vec![0, 16] => vec![0x10] },
552 } with_leaf { &[0x1] => vec![0xFF] }
553 };
554
555 let (node, value) = node
556 .remove(trie.db.as_ref(), Nibbles::from_bytes(&[]))
557 .unwrap();
558
559 assert!(matches!(node, Some(NodeRemoveResult::Mutated)));
560 assert_eq!(value, Some(vec![0xFF]));
561 }
562
563 #[test]
564 fn compute_hash_two_choices() {
565 let node = pmt_node! { @(trie)
566 branch {
567 2 => leaf { vec![0, 16] => vec![0x20] },
568 4 => leaf { vec![0, 16] => vec![0x40] },
569 }
570 };
571
572 assert_eq!(
573 node.compute_hash(&NativeCrypto).as_ref(),
574 &[
575 0xD5, 0x80, 0x80, 0xC2, 0x30, 0x20, 0x80, 0xC2, 0x30, 0x40, 0x80, 0x80, 0x80, 0x80,
576 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
577 ],
578 );
579 }
580
581 #[test]
582 fn compute_hash_all_choices() {
583 let node = pmt_node! { @(trie)
584 branch {
585 0x0 => leaf { vec![0, 16] => vec![0x00] },
586 0x1 => leaf { vec![0, 16] => vec![0x10] },
587 0x2 => leaf { vec![0, 16] => vec![0x20] },
588 0x3 => leaf { vec![0, 16] => vec![0x30] },
589 0x4 => leaf { vec![0, 16] => vec![0x40] },
590 0x5 => leaf { vec![0, 16] => vec![0x50] },
591 0x6 => leaf { vec![0, 16] => vec![0x60] },
592 0x7 => leaf { vec![0, 16] => vec![0x70] },
593 0x8 => leaf { vec![0, 16] => vec![0x80] },
594 0x9 => leaf { vec![0, 16] => vec![0x90] },
595 0xA => leaf { vec![0, 16] => vec![0xA0] },
596 0xB => leaf { vec![0, 16] => vec![0xB0] },
597 0xC => leaf { vec![0, 16] => vec![0xC0] },
598 0xD => leaf { vec![0, 16] => vec![0xD0] },
599 0xE => leaf { vec![0, 16] => vec![0xE0] },
600 0xF => leaf { vec![0, 16] => vec![0xF0] },
601 }
602 };
603
604 assert_eq!(
605 node.compute_hash(&NativeCrypto).as_ref(),
606 &[
607 0x0A, 0x3C, 0x06, 0x2D, 0x4A, 0xE3, 0x61, 0xEC, 0xC4, 0x82, 0x07, 0xB3, 0x2A, 0xDB,
608 0x6A, 0x3A, 0x3F, 0x3E, 0x98, 0x33, 0xC8, 0x9C, 0x9A, 0x71, 0x66, 0x3F, 0x4E, 0xB5,
609 0x61, 0x72, 0xD4, 0x9D,
610 ],
611 );
612 }
613
614 #[test]
615 fn compute_hash_one_choice_with_value() {
616 let node = pmt_node! { @(trie)
617 branch {
618 2 => leaf { vec![0, 16] => vec![0x20] },
619 4 => leaf { vec![0, 16] => vec![0x40] },
620 } with_leaf { &[0x1] => vec![0x1] }
621 };
622
623 assert_eq!(
624 node.compute_hash(&NativeCrypto).as_ref(),
625 &[
626 0xD5, 0x80, 0x80, 0xC2, 0x30, 0x20, 0x80, 0xC2, 0x30, 0x40, 0x80, 0x80, 0x80, 0x80,
627 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01,
628 ],
629 );
630 }
631
632 #[test]
633 fn compute_hash_all_choices_with_value() {
634 let node = pmt_node! { @(trie)
635 branch {
636 0x0 => leaf { vec![0, 16] => vec![0x00] },
637 0x1 => leaf { vec![0, 16] => vec![0x10] },
638 0x2 => leaf { vec![0, 16] => vec![0x20] },
639 0x3 => leaf { vec![0, 16] => vec![0x30] },
640 0x4 => leaf { vec![0, 16] => vec![0x40] },
641 0x5 => leaf { vec![0, 16] => vec![0x50] },
642 0x6 => leaf { vec![0, 16] => vec![0x60] },
643 0x7 => leaf { vec![0, 16] => vec![0x70] },
644 0x8 => leaf { vec![0, 16] => vec![0x80] },
645 0x9 => leaf { vec![0, 16] => vec![0x90] },
646 0xA => leaf { vec![0, 16] => vec![0xA0] },
647 0xB => leaf { vec![0, 16] => vec![0xB0] },
648 0xC => leaf { vec![0, 16] => vec![0xC0] },
649 0xD => leaf { vec![0, 16] => vec![0xD0] },
650 0xE => leaf { vec![0, 16] => vec![0xE0] },
651 0xF => leaf { vec![0, 16] => vec![0xF0] },
652 } with_leaf { &[0x1] => vec![0x1] }
653 };
654
655 assert_eq!(
656 node.compute_hash(&NativeCrypto).as_ref(),
657 &[
658 0x2A, 0x85, 0x67, 0xC5, 0x63, 0x4A, 0x87, 0xBA, 0x19, 0x6F, 0x2C, 0x65, 0x15, 0x16,
659 0x66, 0x37, 0xE0, 0x9A, 0x34, 0xE6, 0xC9, 0xB0, 0x4D, 0xA5, 0x6F, 0xC4, 0x70, 0x4E,
660 0x38, 0x61, 0x7D, 0x8E
661 ],
662 );
663 }
664
665 #[test]
666 fn symmetric_encoding_a() {
667 let node: Node = pmt_node! { @(trie)
668 branch {
669 0 => leaf { vec![0,16] => vec![0x12, 0x34, 0x56, 0x78] },
670 1 => leaf { vec![0,16] => vec![0x34, 0x56, 0x78, 0x9A] },
671 }
672 }
673 .into();
674 assert_eq!(Node::decode(&node.encode_to_vec()).unwrap(), node)
675 }
676
677 #[test]
678 fn symmetric_encoding_b() {
679 let node: Node = pmt_node! { @(trie)
680 branch {
681 0 => leaf { vec![0, 16] => vec![0x00] },
682 1 => leaf { vec![0, 16] => vec![0x10] },
683 3 => extension { [0], branch {
684 0 => leaf { vec![16] => vec![0x01, 0x00] },
685 1 => leaf { vec![16] => vec![0x01, 0x01] },
686 } },
687 }
688 }
689 .into();
690 assert_eq!(Node::decode(&node.encode_to_vec()).unwrap(), node)
691 }
692
693 #[test]
694 fn symmetric_encoding_c() {
695 let node: Node = pmt_node! { @(trie)
696 branch {
697 0x0 => leaf { vec![0, 16] => vec![0x00] },
698 0x1 => leaf { vec![0, 16] => vec![0x10] },
699 0x2 => leaf { vec![0, 16] => vec![0x20] },
700 0x3 => leaf { vec![0, 16] => vec![0x30] },
701 0x4 => leaf { vec![0, 16] => vec![0x40] },
702 0x5 => leaf { vec![0, 16] => vec![0x50] },
703 0x6 => leaf { vec![0, 16] => vec![0x60] },
704 0x7 => leaf { vec![0, 16] => vec![0x70] },
705 0x8 => leaf { vec![0, 16] => vec![0x80] },
706 0x9 => leaf { vec![0, 16] => vec![0x90] },
707 0xA => leaf { vec![0, 16] => vec![0xA0] },
708 0xB => leaf { vec![0, 16] => vec![0xB0] },
709 0xC => leaf { vec![0, 16] => vec![0xC0] },
710 0xD => leaf { vec![0, 16] => vec![0xD0] },
711 0xE => leaf { vec![0, 16] => vec![0xE0] },
712 0xF => leaf { vec![0, 16] => vec![0xF0] },
713 } with_leaf { &[0x1] => vec![0x1] }
714 }
715 .into();
716 assert_eq!(Node::decode(&node.encode_to_vec()).unwrap(), node)
717 }
718}