jmt_pq/
node_type.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Node types of [`JellyfishMerkleTree`](crate::JellyfishMerkleTree)
5//!
6//! This module defines two types of Jellyfish Merkle tree nodes: [`InternalNode`]
7//! and [`LeafNode`] as building blocks of a 512-bit
8//! [`JellyfishMerkleTree`](crate::JellyfishMerkleTree). [`InternalNode`] represents a 4-level
9//! binary tree to optimize for IOPS: it compresses a tree with 31 nodes into one node with 16
10//! chidren at the lowest level. [`LeafNode`] stores the full key and the value associated.
11use 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/// The unique key of each node.
36#[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    // The version at which the node is created.
42    version: Version,
43    // The nibble path this node represents in the tree.
44    nibble_path: NibblePath,
45}
46
47impl NodeKey {
48    /// Creates a new `NodeKey`.
49    #[inline(always)]
50    pub const fn new(version: Version, nibble_path: NibblePath) -> Self {
51        Self {
52            version,
53            nibble_path,
54        }
55    }
56
57    /// A shortcut to generate a node key consisting of a version and an empty nibble path.
58    #[inline(always)]
59    pub(crate) fn new_empty_path(version: Version) -> Self {
60        Self::new(version, NibblePath::new(vec![]))
61    }
62
63    /// Gets the version.
64    #[inline(always)]
65    pub const fn version(&self) -> Version {
66        self.version
67    }
68
69    /// Gets the nibble path.
70    #[inline(always)]
71    pub const fn nibble_path(&self) -> &NibblePath {
72        &self.nibble_path
73    }
74
75    /// Generates a child node key based on this node key.
76    #[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    /// Generates parent node key at the same version based on this node key.
84    #[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    /// Sets the version to the given version.
95    #[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/// Each child of [`InternalNode`] encapsulates a nibble forking at this node.
122#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Encode, Decode)]
123#[cfg_attr(any(test), derive(Arbitrary))]
124pub struct Child {
125    /// The hash value of this child node.
126    #[serde(with = "crate::hash_bytes_serde")]
127    pub hash: HashBytes,
128    /// `version`, the `nibble_path` of the ['NodeKey`] of this [`InternalNode`] the child belongs
129    /// to and the child's index constitute the [`NodeKey`] to uniquely identify this child node
130    /// from the storage. Used by `[`NodeKey::gen_child_node_key`].
131    pub version: Version,
132    /// Indicates if the child is a leaf, or if it's an internal node, the total number of leaves
133    /// under it.
134    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/// [`Children`] is just a collection of children belonging to a [`InternalNode`], indexed from 0 to
162/// 15, inclusive.
163#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
164pub struct Children {
165    /// The actual children. We box this array to avoid stack overflows, since the space consumed
166    /// is somewhat large
167    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    /// Create an empty set of children.
190    #[inline(always)]
191    pub fn new() -> Self {
192        Default::default()
193    }
194
195    /// Insert a new child. Insert is guaranteed not to allocate.
196    #[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    /// Get the child at the provided nibble.
206    #[inline(always)]
207    pub fn get(&self, nibble: Nibble) -> &Option<Child> {
208        &self.children[nibble.as_usize()]
209    }
210
211    /// Check if the struct contains any children.
212    #[inline(always)]
213    pub const fn is_empty(&self) -> bool {
214        self.num_children == 0
215    }
216
217    /// Remove the child at the provided nibble.
218    #[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    /// Returns a (possibly unsorted) iterator over the children.
228    #[inline(always)]
229    pub fn values(&self) -> impl Iterator<Item = &Child> {
230        self.children.iter().flatten()
231    }
232
233    /// Returns a (possibly unsorted) iterator over the children and their respective Nibbles.
234    #[inline(always)]
235    pub fn iter(&self) -> impl Iterator<Item = (Nibble, &Child)> {
236        self.iter_sorted()
237    }
238
239    /// Returns a (possibly unsorted) mutable iterator over the children, also yielding their respective nibbles.
240    #[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    /// Returns the number of children.
253    #[inline(always)]
254    pub const fn num_children(&self) -> usize {
255        self.num_children
256    }
257
258    /// Returns an iterator that yields the children and their respective Nibbles in sorted order.
259    #[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/// Represents a 4-level subtree with 16 children at the bottom level. Theoretically, this reduces
309/// IOPS to query a tree by 4x since we compress 4 levels in a standard Merkle tree into 1 node.
310/// Though we choose the same internal node structure as that of Patricia Merkle tree, the root hash
311/// computation logic is similar to a 4-level sparse Merkle tree except for some customizations. See
312/// the `CryptoHash` trait implementation below for details.
313#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Encode, Decode)]
314pub struct InternalNode {
315    /// Up to 16 children.
316    children: Children,
317    /// Total number of leaves under this internal node
318    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/// Computes the hash of internal node according to [`JellyfishTree`](crate::JellyfishTree)
332/// data structure in the logical view. `start` and `nibble_height` determine a subtree whose
333/// root hash we want to get. For an internal node with 16 children at the bottom level, we compute
334/// the root hash of it as if a full binary Merkle tree with 16 leaves as below:
335///
336/// ```text
337///   4 ->              +------ root hash ------+
338///                     |                       |
339///   3 ->        +---- # ----+           +---- # ----+
340///               |           |           |           |
341///   2 ->        #           #           #           #
342///             /   \       /   \       /   \       /   \
343///   1 ->     #     #     #     #     #     #     #     #
344///           / \   / \   / \   / \   / \   / \   / \   / \
345///   0 ->   0   1 2   3 4   5 6   7 8   9 A   B C   D E   F
346///   ^
347/// height
348/// ```
349///
350/// As illustrated above, at nibble height 0, `0..F` in hex denote 16 chidren hashes.  Each `#`
351/// means the hash of its two direct children, which will be used to generate the hash of its
352/// parent with the hash of its sibling. Finally, we can get the hash of this internal node.
353///
354/// However, if an internal node doesn't have all 16 chidren exist at height 0 but just a few of
355/// them, we have a modified hashing rule on top of what is stated above:
356///   1. From top to bottom, a node will be replaced by a leaf child if the subtree rooted at this
357///      node has only one child at height 0 and it is a leaf child.
358///   2. From top to bottom, a node will be replaced by the placeholder node if the subtree rooted at
359///      this node doesn't have any child at height 0. For example, if an internal node has 3 leaf
360///      children at index 0, 3, 8, respectively, and 1 internal node at index C, then the computation
361///      graph will be like:
362///
363/// ```text
364///   4 ->              +------ root hash ------+
365///                     |                       |
366///   3 ->        +---- # ----+           +---- # ----+
367///               |           |           |           |
368///   2 ->        #           @           8           #
369///             /   \                               /   \
370///   1 ->     0     3                             #     @
371///                                               / \
372///   0 ->                                       C   @
373///   ^
374/// height
375/// Note: @ denotes placeholder hash.
376/// ```
377#[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/// Helper for `InternalNode` implementations. Test if the leaf exaclty has one child within the width range specified
396#[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/// Helper for `InternalNode` implementations. Test if the leaf exactly has one child *at the position n*
402///  within the width range specified
403#[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    /// Creates a new Internal node.
415    pub fn new(children: Children) -> Self {
416        // Assert the internal node must have >= 1 children. If it only has one child, it cannot be
417        // a leaf node. Otherwise, the leaf node should be a child of this internal node's parent.
418        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,  /* start index */
461            16, /* the number of leaves in the subtree of which we want the hash of root */
462            self.generate_bitmaps(),
463        )
464    }
465
466    pub fn children_sorted(&self) -> impl Iterator<Item = (Nibble, &Child)> {
467        // Previously this used `.sorted_by_key()` directly on the iterator but this does not appear
468        // to be available in itertools (it does not seem to ever have existed???) for unknown
469        // reasons. This satisfies the same behavior. ¯\_(ツ)_/¯
470        self.children.iter_sorted()
471    }
472
473    pub fn children_unsorted(&self) -> impl Iterator<Item = (Nibble, &Child)> {
474        self.children.iter()
475    }
476
477    /// Gets the `n`-th child.
478    #[inline(always)]
479    pub fn child(&self, n: Nibble) -> Option<&Child> {
480        self.children.get(n).as_ref()
481    }
482
483    /// Generates `existence_bitmap` and `leaf_bitmap` as a pair of `u16`s: child at index `i`
484    /// exists if `existence_bitmap[i]` is set; child at index `i` is leaf node if
485    /// `leaf_bitmap[i]` is set.
486    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        // `leaf_bitmap` must be a subset of `existence_bitmap`.
497        assert_eq!(existence_bitmap | leaf_bitmap, existence_bitmap);
498        (existence_bitmap, leaf_bitmap)
499    }
500
501    /// Given a range [start, start + width), returns the sub-bitmap of that range.
502    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        // A range with `start == 8` and `width == 4` will generate a mask 0b0000111100000000.
506        // use as converting to smaller integer types when 'width == 16'
507        let mask = (((1u32 << width) - 1) << start) as u16;
508        (bitmaps.0 & mask, bitmaps.1 & mask)
509    }
510
511    /// [`build_sibling`] builds the sibling contained in the merkle tree between
512    /// [start; start+width) under the internal node (`self`) using the `TreeReader` as
513    /// a node reader to get the leaves/internal nodes at the bottom level of this internal node
514    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        // Given a bit [start, 1 << nibble_height], return the value of that range.
523        let (range_existence_bitmap, range_leaf_bitmap) =
524            Self::range_bitmaps(start, width, (existence_bitmap, leaf_bitmap));
525        if range_existence_bitmap == 0 {
526            // No child under this subtree
527            SparseMerkleNode::Null
528        } else if has_only_child(width, range_existence_bitmap, range_leaf_bitmap) {
529            // Only 1 leaf child under this subtree or reach the lowest level
530            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        // Given a bit [start, 1 << nibble_height], return the value of that range.
583        let (range_existence_bitmap, range_leaf_bitmap) =
584            Self::range_bitmaps(start, width, (existence_bitmap, leaf_bitmap));
585        if range_existence_bitmap == 0 {
586            // No child under this subtree
587            SPARSE_MERKLE_PLACEHOLDER_HASH
588        } else if has_only_child(width, range_existence_bitmap, range_leaf_bitmap) {
589            // Only 1 leaf child under this subtree or reach the lowest level
590            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    /// Gets the child without its corresponding siblings (like using
617    /// [`get_only_child_with_siblings`](InternalNode::get_only_child_with_siblings) and dropping the
618    /// siblings, but more efficient).
619    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        // Nibble height from 3 to 0.
627        for h in (0..4).rev() {
628            // Get the number of children of the internal node that each subtree at this height
629            // covers.
630            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                // No child in this range.
638                return None;
639            } else if has_only_child(width, range_existence_bitmap, range_leaf_bitmap) {
640                // Return the only 1 leaf child under this subtree or reach the lowest level
641                // Even this leaf child is not the n-th child, it should be returned instead of
642                // `None` because it's existence indirectly proves the n-th child doesn't exist.
643                // Please read proof format for details.
644                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                    // Should be guaranteed by the self invariants, but these are not easy to express at the moment
649                    .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    /// Gets the child and its corresponding siblings that are necessary to generate the proof for
666    /// the `n`-th child. This function will **either** return the child that matches the nibble n or the only
667    /// child in the largest width range pointed by n. If it is an existence proof, the returned child must be the `n`-th
668    /// child; otherwise, the returned child may be another child in the same nibble pointed by n.
669    /// See inline explanation for details. When calling this function with n = 11
670    ///  (node `b` in the following graph), the range at each level is illustrated as a pair of square brackets:
671    ///
672    /// ```text
673    ///     4      [f   e   d   c   b   a   9   8   7   6   5   4   3   2   1   0] -> root level
674    ///            ---------------------------------------------------------------
675    ///     3      [f   e   d   c   b   a   9   8] [7   6   5   4   3   2   1   0] width = 8
676    ///                                  chs <--┘                        shs <--┘
677    ///     2      [f   e   d   c] [b   a   9   8] [7   6   5   4] [3   2   1   0] width = 4
678    ///                  shs <--┘               └--> chs
679    ///     1      [f   e] [d   c] [b   a] [9   8] [7   6] [5   4] [3   2] [1   0] width = 2
680    ///                          chs <--┘       └--> shs
681    ///     0      [f] [e] [d] [c] [b] [a] [9] [8] [7] [6] [5] [4] [3] [2] [1] [0] width = 1
682    ///     ^                chs <--┘   └--> shs
683    ///     |   MSB|<---------------------- uint 16 ---------------------------->|LSB
684    ///  height    chs: `child_half_start`         shs: `sibling_half_start`
685    /// ```
686    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        // Nibble height from 3 to 0.
699        for h in (0..4).rev() {
700            // Get the number of children of the internal node that each subtree at this height
701            // covers.
702            let width = 1 << h;
703            let (child_half_start, sibling_half_start) = get_child_and_sibling_half_start(n, h);
704            // Compute the root hash of the subtree rooted at the sibling of `r`.
705            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                // No child in this range.
718                return (None, siblings);
719            } else if get_only_child
720                && (has_only_child(width, range_existence_bitmap, range_leaf_bitmap))
721            {
722                // Return the only 1 leaf child under this subtree or reach the lowest level
723                // Even this leaf child is not the n-th child, it should be returned instead of
724                // `None` because it's existence indirectly proves the n-th child doesn't exist.
725                // Please read proof format for details.
726                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                            // Should be guaranteed by the self invariants, but these are not easy to express at the moment
732                            .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                // Early return the child in that subtree iff it is the only child and the nibble points
749                // to it
750                return (
751                    {
752                        let only_child_version = self
753                            .child(n)
754                            // Should be guaranteed by the self invariants, but these are not easy to express at the moment
755                            .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    /// [`get_child_with_siblings`] will return the child from this subtree that matches the nibble n in addition
774    /// to building the list of its sibblings. This function has the same behavior as [`child`].
775    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    /// [`get_only_child_with_siblings`] will **either** return the child that matches the nibble n or the only
785    /// child in the largest width range pointed by n (see the helper function [`get_child_with_siblings_helper`] for more information).
786    ///
787    /// Even this leaf child is not the n-th child, it should be returned instead of
788    /// `None` because it's existence indirectly proves the n-th child doesn't exist.
789    /// Please read proof format for details.
790    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/// Given a nibble, computes the start position of its `child_half_start` and `sibling_half_start`
806/// at `height` level.
807#[inline(always)]
808pub(crate) fn get_child_and_sibling_half_start(n: Nibble, height: u8) -> (u8, u8) {
809    // Get the index of the first child belonging to the same subtree whose root, let's say `r` is
810    // at `height` that the n-th child belongs to.
811    // Note: `child_half_start` will be always equal to `n` at height 0.
812    debug_assert!(height < 8);
813    let mask = u8::MAX.wrapping_shl(height.into());
814    let child_half_start = u8::from(n) & mask;
815
816    // Get the index of the first child belonging to the subtree whose root is the sibling of `r`
817    // at `height`.
818    let sibling_half_start = child_half_start ^ (1u8.wrapping_shl(height.into()));
819
820    (child_half_start, sibling_half_start)
821}
822
823/// Given a nibble, computes the start position of its `child_half_start` at `height` level.
824#[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/// Represents a key-value pair in the map.
830///
831/// Note: this does not store the key itself.
832#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Encode, Decode)]
833pub struct LeafNode {
834    /// The hash of the key for this entry.
835    key_hash: KeyHash,
836    /// The hash of the value for this entry.
837    value_hash: ValueHash,
838}
839
840impl LeafNode {
841    /// Creates a new leaf node.
842    #[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    /// Gets the key hash.
851    #[inline(always)]
852    pub const fn key_hash(&self) -> KeyHash {
853        self.key_hash
854    }
855
856    /// Gets the associated value hash.
857    #[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/// The concrete node type of [`JellyfishMerkleTree`](crate::JellyfishMerkleTree).
875#[derive(Clone, Debug, Eq, PartialEq, Encode, Decode, Serialize, Deserialize)]
876pub enum Node {
877    /// Represents `null`.
878    Null,
879    /// A wrapper of [`InternalNode`].
880    Internal(InternalNode),
881    /// A wrapper of [`LeafNode`].
882    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    /// Creates the [`Null`](Node::Null) variant.
905    #[inline(always)]
906    pub(crate) const fn new_null() -> Self {
907        Node::Null
908    }
909
910    /// Creates the [`Internal`](Node::Internal) variant.
911    #[cfg(test)]
912    #[inline(always)]
913    pub(crate) fn new_internal(children: Children) -> Self {
914        Node::Internal(InternalNode::new(children))
915    }
916
917    /// Creates the [`Leaf`](Node::Leaf) variant.
918    #[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    /// Creates the [`Leaf`](Node::Leaf) variant by hashing a raw value.
924    #[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    /// Returns `true` if the node is a leaf node.
934    #[inline(always)]
935    pub(crate) fn is_leaf(&self) -> bool {
936        matches!(self, Node::Leaf(_))
937    }
938
939    /// Returns `NodeType`
940    #[inline(always)]
941    pub(crate) fn node_type(&self) -> NodeType {
942        match self {
943            // The returning value will be used to construct a `Child` of a internal node, while an
944            // internal node will never have a child of Node::Null.
945            Self::Null => unreachable!(),
946            Self::Leaf(_) => NodeType::Leaf,
947            Self::Internal(n) => n.node_type(),
948        }
949    }
950
951    /// Returns leaf count if known
952    #[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    /// Computes the hash of nodes.
962    #[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}