1use crate::storage::TreeReader;
12
13use crate::SimpleHasher;
14use alloc::format;
15use alloc::vec::Vec;
16use alloc::{boxed::Box, vec};
17use anyhow::Context;
18use lencode::prelude::{Decode, DedupeDecoder, DedupeEncoder, Encode, Read, Write};
19#[cfg(test)]
20use proptest::prelude::*;
21#[cfg(test)]
22use proptest_derive::Arbitrary;
23use serde::{Deserialize, Serialize};
24
25use crate::proof::SparseMerkleNode;
26use crate::{
27 HashBytes, KeyHash, SPARSE_MERKLE_PLACEHOLDER_HASH, ValueHash,
28 types::{
29 Version,
30 nibble::{Nibble, nibble_path::NibblePath},
31 proof::{SparseMerkleInternalNode, SparseMerkleLeafNode},
32 },
33};
34
35#[derive(
37 Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Encode, Decode,
38)]
39#[cfg_attr(any(test), derive(Arbitrary))]
40pub struct NodeKey {
41 version: Version,
43 nibble_path: NibblePath,
45}
46
47impl NodeKey {
48 #[inline(always)]
50 pub const fn new(version: Version, nibble_path: NibblePath) -> Self {
51 Self {
52 version,
53 nibble_path,
54 }
55 }
56
57 #[inline(always)]
59 pub(crate) fn new_empty_path(version: Version) -> Self {
60 Self::new(version, NibblePath::new(vec![]))
61 }
62
63 #[inline(always)]
65 pub const fn version(&self) -> Version {
66 self.version
67 }
68
69 #[inline(always)]
71 pub const fn nibble_path(&self) -> &NibblePath {
72 &self.nibble_path
73 }
74
75 #[inline(always)]
77 pub(crate) fn gen_child_node_key(&self, version: Version, n: Nibble) -> Self {
78 let mut node_nibble_path = self.nibble_path().clone();
79 node_nibble_path.push(n);
80 Self::new(version, node_nibble_path)
81 }
82
83 #[inline(always)]
85 pub(crate) fn gen_parent_node_key(&self) -> Self {
86 let mut node_nibble_path = self.nibble_path().clone();
87 assert!(
88 node_nibble_path.pop().is_some(),
89 "Current node key is root.",
90 );
91 Self::new(self.version, node_nibble_path)
92 }
93
94 #[inline(always)]
96 pub(crate) fn set_version(&mut self, version: Version) {
97 self.version = version;
98 }
99}
100
101#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, Encode, Decode)]
102pub enum NodeType {
103 Leaf,
104 Internal { leaf_count: usize },
105}
106
107#[cfg(test)]
108impl Arbitrary for NodeType {
109 type Parameters = ();
110 type Strategy = BoxedStrategy<Self>;
111
112 fn arbitrary_with(_args: ()) -> Self::Strategy {
113 prop_oneof![
114 Just(NodeType::Leaf),
115 (2..100usize).prop_map(|leaf_count| NodeType::Internal { leaf_count })
116 ]
117 .boxed()
118 }
119}
120
121#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Encode, Decode)]
123#[cfg_attr(any(test), derive(Arbitrary))]
124pub struct Child {
125 #[serde(with = "crate::hash_bytes_serde")]
127 pub hash: HashBytes,
128 pub version: Version,
132 pub node_type: NodeType,
135}
136
137impl Child {
138 #[inline(always)]
139 pub const fn new(hash: HashBytes, version: Version, node_type: NodeType) -> Self {
140 Self {
141 hash,
142 version,
143 node_type,
144 }
145 }
146
147 #[inline(always)]
148 pub const fn is_leaf(&self) -> bool {
149 matches!(self.node_type, NodeType::Leaf)
150 }
151
152 #[inline(always)]
153 pub const fn leaf_count(&self) -> usize {
154 match self.node_type {
155 NodeType::Leaf => 1,
156 NodeType::Internal { leaf_count } => leaf_count,
157 }
158 }
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
164pub struct Children {
165 children: Box<[Option<Child>; 16]>,
168 num_children: usize,
169}
170
171#[cfg(test)]
172impl Arbitrary for Children {
173 type Parameters = ();
174 type Strategy = BoxedStrategy<Self>;
175
176 fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
177 (any::<Box<[Option<Child>; 16]>>().prop_map(|children| {
178 let num_children = children.iter().filter(|child| child.is_some()).count();
179 Self {
180 children,
181 num_children,
182 }
183 }))
184 .boxed()
185 }
186}
187
188impl Children {
189 #[inline(always)]
191 pub fn new() -> Self {
192 Default::default()
193 }
194
195 #[inline(always)]
197 pub fn insert(&mut self, nibble: Nibble, child: Child) {
198 let idx = nibble.as_usize();
199 if self.children[idx].is_none() {
200 self.num_children += 1;
201 }
202 self.children[idx] = Some(child);
203 }
204
205 #[inline(always)]
207 pub fn get(&self, nibble: Nibble) -> &Option<Child> {
208 &self.children[nibble.as_usize()]
209 }
210
211 #[inline(always)]
213 pub const fn is_empty(&self) -> bool {
214 self.num_children == 0
215 }
216
217 #[inline(always)]
219 pub fn remove(&mut self, nibble: Nibble) {
220 let idx = nibble.as_usize();
221 if self.children[idx].is_some() {
222 self.num_children -= 1;
223 }
224 self.children[idx] = None;
225 }
226
227 #[inline(always)]
229 pub fn values(&self) -> impl Iterator<Item = &Child> {
230 self.children.iter().flatten()
231 }
232
233 #[inline(always)]
235 pub fn iter(&self) -> impl Iterator<Item = (Nibble, &Child)> {
236 self.iter_sorted()
237 }
238
239 #[inline(always)]
241 pub fn iter_mut(&mut self) -> impl Iterator<Item = (Nibble, &mut Child)> {
242 self.children
243 .iter_mut()
244 .enumerate()
245 .filter_map(|(nibble, child)| {
246 child
247 .as_mut()
248 .map(|child| (Nibble::from(nibble as u8), child))
249 })
250 }
251
252 #[inline(always)]
254 pub const fn num_children(&self) -> usize {
255 self.num_children
256 }
257
258 #[inline(always)]
260 pub fn iter_sorted(&self) -> impl Iterator<Item = (Nibble, &Child)> {
261 self.children
262 .iter()
263 .enumerate()
264 .filter_map(|(nibble, child)| {
265 child
266 .as_ref()
267 .map(|child| (Nibble::from(nibble as u8), child))
268 })
269 }
270}
271
272impl Encode for Children {
273 fn encode_ext(
274 &self,
275 writer: &mut impl Write,
276 dedupe_encoder: Option<&mut DedupeEncoder>,
277 ) -> lencode::Result<usize> {
278 let mut total = 0;
279 let mut dedupe_encoder = dedupe_encoder;
280 total += self
281 .children
282 .as_ref()
283 .encode_ext(writer, dedupe_encoder.as_deref_mut())?;
284 total += self
285 .num_children
286 .encode_ext(writer, dedupe_encoder.as_deref_mut())?;
287 Ok(total)
288 }
289}
290
291impl Decode for Children {
292 fn decode_ext(
293 reader: &mut impl Read,
294 dedupe_decoder: Option<&mut DedupeDecoder>,
295 ) -> lencode::Result<Self> {
296 let mut dedupe_decoder = dedupe_decoder;
297 let children_arr =
298 <[Option<Child>; 16]>::decode_ext(reader, dedupe_decoder.as_deref_mut())?;
299 let num_children = usize::decode_ext(reader, dedupe_decoder.as_deref_mut())?;
300
301 Ok(Self {
302 children: Box::new(children_arr),
303 num_children,
304 })
305 }
306}
307
308#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Encode, Decode)]
314pub struct InternalNode {
315 children: Children,
317 leaf_count: usize,
319}
320
321impl SparseMerkleInternalNode {
322 fn from<H: SimpleHasher>(internal_node: InternalNode) -> Self {
323 let bitmaps = internal_node.generate_bitmaps();
324 SparseMerkleInternalNode::new(
325 internal_node.merkle_hash::<H>(0, 8, bitmaps),
326 internal_node.merkle_hash::<H>(8, 8, bitmaps),
327 )
328 }
329}
330
331#[cfg(test)]
378impl Arbitrary for InternalNode {
379 type Parameters = ();
380 type Strategy = BoxedStrategy<Self>;
381
382 fn arbitrary_with(_args: ()) -> Self::Strategy {
383 (any::<Children>().prop_filter(
384 "InternalNode constructor panics when its only child is a leaf.",
385 |children| {
386 !(children.num_children() == 1
387 && children.values().next().expect("Must exist.").is_leaf())
388 },
389 ))
390 .prop_map(InternalNode::new)
391 .boxed()
392 }
393}
394
395#[inline(always)]
397fn has_only_child(width: u8, range_existence_bitmap: u16, range_leaf_bitmap: u16) -> bool {
398 width == 1 || (range_existence_bitmap.is_power_of_two() && range_leaf_bitmap != 0)
399}
400
401#[inline(always)]
404fn has_child(
405 width: u8,
406 range_existence_bitmap: u16,
407 n_bitmap: u16,
408 range_leaf_bitmap: u16,
409) -> bool {
410 width == 1 || (range_existence_bitmap == n_bitmap && range_leaf_bitmap != 0)
411}
412
413impl InternalNode {
414 pub fn new(children: Children) -> Self {
416 assert!(!children.is_empty(), "Children must not be empty");
419 if children.num_children() == 1 {
420 assert!(
421 !children
422 .values()
423 .next()
424 .expect("Must have 1 element")
425 .is_leaf(),
426 "If there's only one child, it must not be a leaf."
427 );
428 }
429
430 let leaf_count = Self::sum_leaf_count(&children);
431 Self {
432 children,
433 leaf_count,
434 }
435 }
436
437 fn sum_leaf_count(children: &Children) -> usize {
438 let mut leaf_count = 0;
439 for child in children.values() {
440 let n = child.leaf_count();
441 leaf_count += n;
442 }
443 leaf_count
444 }
445
446 #[inline(always)]
447 pub const fn leaf_count(&self) -> usize {
448 self.leaf_count
449 }
450
451 #[inline(always)]
452 pub const fn node_type(&self) -> NodeType {
453 NodeType::Internal {
454 leaf_count: self.leaf_count,
455 }
456 }
457
458 pub fn hash<H: SimpleHasher>(&self) -> HashBytes {
459 self.merkle_hash::<H>(
460 0, 16, self.generate_bitmaps(),
463 )
464 }
465
466 pub fn children_sorted(&self) -> impl Iterator<Item = (Nibble, &Child)> {
467 self.children.iter_sorted()
471 }
472
473 pub fn children_unsorted(&self) -> impl Iterator<Item = (Nibble, &Child)> {
474 self.children.iter()
475 }
476
477 #[inline(always)]
479 pub fn child(&self, n: Nibble) -> Option<&Child> {
480 self.children.get(n).as_ref()
481 }
482
483 pub fn generate_bitmaps(&self) -> (u16, u16) {
487 let mut existence_bitmap = 0;
488 let mut leaf_bitmap = 0;
489 for (nibble, child) in self.children.iter() {
490 let i = u8::from(nibble);
491 existence_bitmap |= 1u16 << i;
492 if child.is_leaf() {
493 leaf_bitmap |= 1u16 << i;
494 }
495 }
496 assert_eq!(existence_bitmap | leaf_bitmap, existence_bitmap);
498 (existence_bitmap, leaf_bitmap)
499 }
500
501 fn range_bitmaps(start: u8, width: u8, bitmaps: (u16, u16)) -> (u16, u16) {
503 assert!(width > 0 && width <= 16 && width.is_power_of_two());
504 assert!(start < 16 && (start & (width - 1)) == 0 && (start + width) <= 16);
505 let mask = (((1u32 << width) - 1) << start) as u16;
508 (bitmaps.0 & mask, bitmaps.1 & mask)
509 }
510
511 fn build_sibling<H: SimpleHasher>(
515 &self,
516 tree_reader: &impl TreeReader,
517 node_key: &NodeKey,
518 start: u8,
519 width: u8,
520 (existence_bitmap, leaf_bitmap): (u16, u16),
521 ) -> SparseMerkleNode {
522 let (range_existence_bitmap, range_leaf_bitmap) =
524 Self::range_bitmaps(start, width, (existence_bitmap, leaf_bitmap));
525 if range_existence_bitmap == 0 {
526 SparseMerkleNode::Null
528 } else if has_only_child(width, range_existence_bitmap, range_leaf_bitmap) {
529 let only_child_index = Nibble::from(range_existence_bitmap.trailing_zeros() as u8);
531
532 let child = self
533 .child(only_child_index)
534 .with_context(|| {
535 format!(
536 "Corrupted internal node: existence_bitmap indicates \
537 the existence of a non-exist child at index {:x}",
538 only_child_index
539 )
540 })
541 .unwrap();
542
543 let child_node = tree_reader
544 .get_node(&node_key.gen_child_node_key(child.version, only_child_index))
545 .with_context(|| {
546 format!(
547 "Corruption error: the merkle tree reader supplied cannot find \
548 the child of version {:?} at index {:x}.",
549 child.version, only_child_index
550 )
551 })
552 .unwrap();
553
554 match child_node {
555 Node::Internal(node) => {
556 SparseMerkleNode::Internal(SparseMerkleInternalNode::from::<H>(node))
557 }
558 Node::Leaf(node) => SparseMerkleNode::Leaf(SparseMerkleLeafNode::from(node)),
559 Node::Null => unreachable!("Impossible to get a null node at this location"),
560 }
561 } else {
562 let left_child = self.merkle_hash::<H>(
563 start,
564 width / 2,
565 (range_existence_bitmap, range_leaf_bitmap),
566 );
567 let right_child = self.merkle_hash::<H>(
568 start + width / 2,
569 width / 2,
570 (range_existence_bitmap, range_leaf_bitmap),
571 );
572 SparseMerkleNode::Internal(SparseMerkleInternalNode::new(left_child, right_child))
573 }
574 }
575
576 fn merkle_hash<H: SimpleHasher>(
577 &self,
578 start: u8,
579 width: u8,
580 (existence_bitmap, leaf_bitmap): (u16, u16),
581 ) -> HashBytes {
582 let (range_existence_bitmap, range_leaf_bitmap) =
584 Self::range_bitmaps(start, width, (existence_bitmap, leaf_bitmap));
585 if range_existence_bitmap == 0 {
586 SPARSE_MERKLE_PLACEHOLDER_HASH
588 } else if has_only_child(width, range_existence_bitmap, range_leaf_bitmap) {
589 let only_child_index = Nibble::from(range_existence_bitmap.trailing_zeros() as u8);
591 self.child(only_child_index)
592 .with_context(|| {
593 format!(
594 "Corrupted internal node: existence_bitmap indicates \
595 the existence of a non-exist child at index {:x}",
596 only_child_index
597 )
598 })
599 .unwrap()
600 .hash
601 } else {
602 let left_child = self.merkle_hash::<H>(
603 start,
604 width / 2,
605 (range_existence_bitmap, range_leaf_bitmap),
606 );
607 let right_child = self.merkle_hash::<H>(
608 start + width / 2,
609 width / 2,
610 (range_existence_bitmap, range_leaf_bitmap),
611 );
612 SparseMerkleInternalNode::new(left_child, right_child).hash::<H>()
613 }
614 }
615
616 pub fn get_only_child_without_siblings(
620 &self,
621 node_key: &NodeKey,
622 n: Nibble,
623 ) -> Option<NodeKey> {
624 let (existence_bitmap, leaf_bitmap) = self.generate_bitmaps();
625
626 for h in (0..4).rev() {
628 let width = 1 << h;
631 let child_half_start = get_child_half_start(n, h);
632
633 let (range_existence_bitmap, range_leaf_bitmap) =
634 Self::range_bitmaps(child_half_start, width, (existence_bitmap, leaf_bitmap));
635
636 if range_existence_bitmap == 0 {
637 return None;
639 } else if has_only_child(width, range_existence_bitmap, range_leaf_bitmap) {
640 let only_child_index = Nibble::from(range_existence_bitmap.trailing_zeros() as u8);
645
646 let only_child_version = self
647 .child(only_child_index)
648 .with_context(|| {
650 format!(
651 "Corrupted internal node: child_bitmap indicates \
652 the existence of a non-exist child at index {:x}",
653 only_child_index
654 )
655 })
656 .unwrap()
657 .version;
658
659 return Some(node_key.gen_child_node_key(only_child_version, only_child_index));
660 }
661 }
662 unreachable!("Impossible to get here without returning even at the lowest level.")
663 }
664
665 fn get_child_with_siblings_helper<H: SimpleHasher>(
687 &self,
688 tree_reader: &impl TreeReader,
689 node_key: &NodeKey,
690 n: Nibble,
691 get_only_child: bool,
692 ) -> (Option<NodeKey>, Vec<SparseMerkleNode>) {
693 let mut siblings: Vec<SparseMerkleNode> = vec![];
694 let (existence_bitmap, leaf_bitmap) = self.generate_bitmaps();
695
696 let n_bitmap = 1 << n.as_usize();
697
698 for h in (0..4).rev() {
700 let width = 1 << h;
703 let (child_half_start, sibling_half_start) = get_child_and_sibling_half_start(n, h);
704 siblings.push(self.build_sibling::<H>(
706 tree_reader,
707 node_key,
708 sibling_half_start,
709 width,
710 (existence_bitmap, leaf_bitmap),
711 ));
712
713 let (range_existence_bitmap, range_leaf_bitmap) =
714 Self::range_bitmaps(child_half_start, width, (existence_bitmap, leaf_bitmap));
715
716 if range_existence_bitmap == 0 {
717 return (None, siblings);
719 } else if get_only_child
720 && (has_only_child(width, range_existence_bitmap, range_leaf_bitmap))
721 {
722 let only_child_index = Nibble::from(range_existence_bitmap.trailing_zeros() as u8);
727 return (
728 {
729 let only_child_version = self
730 .child(only_child_index)
731 .with_context(|| {
733 format!(
734 "Corrupted internal node: child_bitmap indicates \
735 the existence of a non-exist child at index {:x}",
736 only_child_index
737 )
738 })
739 .unwrap()
740 .version;
741 Some(node_key.gen_child_node_key(only_child_version, only_child_index))
742 },
743 siblings,
744 );
745 } else if !get_only_child
746 && (has_child(width, range_existence_bitmap, n_bitmap, range_leaf_bitmap))
747 {
748 return (
751 {
752 let only_child_version = self
753 .child(n)
754 .with_context(|| {
756 format!(
757 "Corrupted internal node: child_bitmap indicates \
758 the existence of a non-exist child at index {:x}",
759 n
760 )
761 })
762 .unwrap()
763 .version;
764 Some(node_key.gen_child_node_key(only_child_version, n))
765 },
766 siblings,
767 );
768 }
769 }
770 unreachable!("Impossible to get here without returning even at the lowest level.")
771 }
772
773 pub(crate) fn get_child_with_siblings<H: SimpleHasher>(
776 &self,
777 tree_cache: &impl TreeReader,
778 node_key: &NodeKey,
779 n: Nibble,
780 ) -> (Option<NodeKey>, Vec<SparseMerkleNode>) {
781 self.get_child_with_siblings_helper::<H>(tree_cache, node_key, n, false)
782 }
783
784 pub(crate) fn get_only_child_with_siblings<H: SimpleHasher>(
791 &self,
792 tree_reader: &impl TreeReader,
793 node_key: &NodeKey,
794 n: Nibble,
795 ) -> (Option<NodeKey>, Vec<SparseMerkleNode>) {
796 self.get_child_with_siblings_helper::<H>(tree_reader, node_key, n, true)
797 }
798
799 #[cfg(test)]
800 pub(crate) fn children(&self) -> &Children {
801 &self.children
802 }
803}
804
805#[inline(always)]
808pub(crate) fn get_child_and_sibling_half_start(n: Nibble, height: u8) -> (u8, u8) {
809 debug_assert!(height < 8);
813 let mask = u8::MAX.wrapping_shl(height.into());
814 let child_half_start = u8::from(n) & mask;
815
816 let sibling_half_start = child_half_start ^ (1u8.wrapping_shl(height.into()));
819
820 (child_half_start, sibling_half_start)
821}
822
823#[inline(always)]
825pub(crate) fn get_child_half_start(n: Nibble, height: u8) -> u8 {
826 get_child_and_sibling_half_start(n, height).0
827}
828
829#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Encode, Decode)]
833pub struct LeafNode {
834 key_hash: KeyHash,
836 value_hash: ValueHash,
838}
839
840impl LeafNode {
841 #[inline(always)]
843 pub const fn new(key_hash: KeyHash, value_hash: ValueHash) -> Self {
844 Self {
845 key_hash,
846 value_hash,
847 }
848 }
849
850 #[inline(always)]
852 pub const fn key_hash(&self) -> KeyHash {
853 self.key_hash
854 }
855
856 #[inline(always)]
858 pub(crate) const fn value_hash(&self) -> ValueHash {
859 self.value_hash
860 }
861
862 #[inline(always)]
863 pub fn hash<H: SimpleHasher>(&self) -> HashBytes {
864 SparseMerkleLeafNode::new(self.key_hash, self.value_hash).hash::<H>()
865 }
866}
867
868impl From<LeafNode> for SparseMerkleLeafNode {
869 fn from(leaf_node: LeafNode) -> Self {
870 Self::new(leaf_node.key_hash, leaf_node.value_hash)
871 }
872}
873
874#[derive(Clone, Debug, Eq, PartialEq, Encode, Decode, Serialize, Deserialize)]
876pub enum Node {
877 Null,
879 Internal(InternalNode),
881 Leaf(LeafNode),
883}
884
885impl From<InternalNode> for Node {
886 fn from(node: InternalNode) -> Self {
887 Node::Internal(node)
888 }
889}
890
891impl From<InternalNode> for Children {
892 fn from(node: InternalNode) -> Self {
893 node.children
894 }
895}
896
897impl From<LeafNode> for Node {
898 fn from(node: LeafNode) -> Self {
899 Node::Leaf(node)
900 }
901}
902
903impl Node {
904 #[inline(always)]
906 pub(crate) const fn new_null() -> Self {
907 Node::Null
908 }
909
910 #[cfg(test)]
912 #[inline(always)]
913 pub(crate) fn new_internal(children: Children) -> Self {
914 Node::Internal(InternalNode::new(children))
915 }
916
917 #[inline(always)]
919 pub(crate) const fn new_leaf(key_hash: KeyHash, value_hash: ValueHash) -> Self {
920 Node::Leaf(LeafNode::new(key_hash, value_hash))
921 }
922
923 #[cfg(test)]
925 #[inline(always)]
926 pub(crate) fn leaf_from_value<H: SimpleHasher>(
927 key_hash: KeyHash,
928 value: impl AsRef<[u8]>,
929 ) -> Self {
930 Node::Leaf(LeafNode::new(key_hash, ValueHash::with::<H>(value)))
931 }
932
933 #[inline(always)]
935 pub(crate) fn is_leaf(&self) -> bool {
936 matches!(self, Node::Leaf(_))
937 }
938
939 #[inline(always)]
941 pub(crate) fn node_type(&self) -> NodeType {
942 match self {
943 Self::Null => unreachable!(),
946 Self::Leaf(_) => NodeType::Leaf,
947 Self::Internal(n) => n.node_type(),
948 }
949 }
950
951 #[inline(always)]
953 pub(crate) fn leaf_count(&self) -> usize {
954 match self {
955 Node::Null => 0,
956 Node::Leaf(_) => 1,
957 Node::Internal(internal_node) => internal_node.leaf_count,
958 }
959 }
960
961 #[inline(always)]
963 pub(crate) fn hash<H: SimpleHasher>(&self) -> HashBytes {
964 match self {
965 Node::Null => SPARSE_MERKLE_PLACEHOLDER_HASH,
966 Node::Internal(internal_node) => internal_node.hash::<H>(),
967 Node::Leaf(leaf_node) => leaf_node.hash::<H>(),
968 }
969 }
970}