Skip to main content

jmt_pq/
tree.rs

1use crate::SPARSE_MERKLE_PLACEHOLDER_HASH;
2use crate::storage::Node::Leaf;
3use alloc::{collections::BTreeMap, vec::Vec};
4use alloc::{format, vec};
5use anyhow::{Context, Result, bail, ensure, format_err};
6use core::marker::PhantomData;
7use core::{cmp::Ordering, convert::TryInto};
8#[cfg(not(feature = "std"))]
9use hashbrown::HashMap;
10#[cfg(feature = "std")]
11use std::collections::HashMap;
12
13use crate::proof::definition::UpdateMerkleProof;
14use crate::proof::{SparseMerkleLeafNode, SparseMerkleNode};
15use crate::{
16    Bytes32Ext, HashBytes, KeyHash, MissingRootError, OwnedValue, RootHash, SimpleHasher,
17    ValueHash,
18    node_type::{Child, Children, InternalNode, LeafNode, Node, NodeKey, NodeType},
19    storage::{TreeReader, TreeUpdateBatch},
20    tree_cache::TreeCache,
21    types::{
22        Version,
23        nibble::{
24            Nibble, NibbleRangeIterator, ROOT_NIBBLE_HEIGHT,
25            nibble_path::{NibbleIterator, NibblePath, skip_common_prefix},
26        },
27        proof::{SparseMerkleProof, SparseMerkleRangeProof},
28    },
29};
30
31type RootProofs<H> = Vec<(RootHash, UpdateMerkleProof<H>)>;
32type PutNodeResult = PutResult<(NodeKey, Node)>;
33type PutOutcome<H> = Result<(PutNodeResult, Option<SparseMerkleProof<H>>)>;
34type ProofQueryResult<H> = Result<(OwnedValue, SparseMerkleProof<H>), ExclusionProof<H>>;
35
36/// A [`JellyfishMerkleTree`] instantiated using the `sha2::Sha512` hasher.
37/// This is a sensible default choice for most applications.
38#[cfg(any(test, feature = "sha2"))]
39pub type Sha512Jmt<'a, R> = JellyfishMerkleTree<'a, R, sha2::Sha512>;
40
41/// A Jellyfish Merkle tree data structure, parameterized by a [`TreeReader`] `R`
42/// and a [`SimpleHasher`] `H`. See [`crate`] for description.
43pub struct JellyfishMerkleTree<'a, R, H: SimpleHasher> {
44    reader: &'a R,
45    _phantom_hasher: PhantomData<H>,
46}
47
48#[cfg(feature = "ics23")]
49pub mod ics23_impl;
50
51impl<'a, R, H> JellyfishMerkleTree<'a, R, H>
52where
53    R: 'a + TreeReader,
54    H: SimpleHasher,
55{
56    /// The root of this tree when empty.
57    pub const EMPTY_ROOT: RootHash = RootHash(SPARSE_MERKLE_PLACEHOLDER_HASH);
58
59    /// Creates a `JellyfishMerkleTree` backed by the given [`TreeReader`].
60    pub fn new(reader: &'a R) -> Self {
61        Self {
62            reader,
63            _phantom_hasher: Default::default(),
64        }
65    }
66
67    /// Get the node hash from the cache if exists, otherwise compute it.
68    fn get_hash(
69        node_key: &NodeKey,
70        node: &Node,
71        hash_cache: &Option<&HashMap<NibblePath, HashBytes>>,
72    ) -> HashBytes {
73        if let Some(cache) = hash_cache {
74            match cache.get(node_key.nibble_path()) {
75                Some(hash) => *hash,
76                None => unreachable!("{:?} can not be found in hash cache", node_key),
77            }
78        } else {
79            node.hash::<H>()
80        }
81    }
82
83    /// The batch version of `put_value_sets`.
84    pub fn batch_put_value_sets(
85        &self,
86        value_sets: Vec<Vec<(KeyHash, OwnedValue)>>,
87        node_hashes: Option<Vec<&HashMap<NibblePath, HashBytes>>>,
88        first_version: Version,
89    ) -> Result<(Vec<RootHash>, TreeUpdateBatch)> {
90        let mut tree_cache = TreeCache::new(self.reader, first_version)?;
91        let hash_sets: Vec<_> = match node_hashes {
92            Some(hashes) => hashes.into_iter().map(Some).collect(),
93            None => (0..value_sets.len()).map(|_| None).collect(),
94        };
95
96        for (idx, (value_set, hash_set)) in
97            itertools::zip_eq(value_sets.into_iter(), hash_sets.into_iter()).enumerate()
98        {
99            assert!(
100                !value_set.is_empty(),
101                "Transactions that output empty write set should not be included.",
102            );
103            let version = first_version + idx as u64;
104            let deduped_and_sorted_kvs = value_set
105                .into_iter()
106                .collect::<BTreeMap<_, _>>()
107                .into_iter()
108                .map(|(key, value)| {
109                    let value_hash = ValueHash::with::<H>(value.as_slice());
110                    tree_cache.put_value(version, key, Some(value));
111                    (key, value_hash)
112                })
113                .collect::<Vec<_>>();
114            let root_node_key = tree_cache.get_root_node_key().clone();
115            let (new_root_node_key, _) = self.batch_insert_at(
116                root_node_key,
117                version,
118                deduped_and_sorted_kvs.as_slice(),
119                0,
120                &hash_set,
121                &mut tree_cache,
122            )?;
123            tree_cache.set_root_node_key(new_root_node_key);
124
125            // Freezes the current cache to make all contents in the current cache immutable.
126            tree_cache.freeze::<H>()?;
127        }
128
129        Ok(tree_cache.into())
130    }
131
132    fn batch_insert_at(
133        &self,
134        mut node_key: NodeKey,
135        version: Version,
136        kvs: &[(KeyHash, ValueHash)],
137        depth: usize,
138        hash_cache: &Option<&HashMap<NibblePath, HashBytes>>,
139        tree_cache: &mut TreeCache<R>,
140    ) -> Result<(NodeKey, Node)> {
141        assert!(!kvs.is_empty());
142
143        let node = tree_cache.get_node(&node_key)?;
144        Ok(match node {
145            Node::Internal(internal_node) => {
146                // We always delete the existing internal node here because it will not be referenced anyway
147                // since this version.
148                tree_cache.delete_node(&node_key, false /* is_leaf */);
149
150                // Reuse the current `InternalNode` in memory to create a new internal node.
151                let mut children: Children = internal_node.clone().into();
152
153                // Traverse all the path touched by `kvs` from this internal node.
154                for (left, right) in NibbleRangeIterator::new(kvs, depth) {
155                    // Traverse downwards from this internal node recursively by splitting the updates into
156                    // each child index
157                    let child_index = kvs[left].0.0.get_nibble(depth);
158
159                    let (new_child_node_key, new_child_node) =
160                        match internal_node.child(child_index) {
161                            Some(child) => {
162                                let child_node_key =
163                                    node_key.gen_child_node_key(child.version, child_index);
164                                self.batch_insert_at(
165                                    child_node_key,
166                                    version,
167                                    &kvs[left..=right],
168                                    depth + 1,
169                                    hash_cache,
170                                    tree_cache,
171                                )?
172                            }
173                            None => {
174                                let new_child_node_key =
175                                    node_key.gen_child_node_key(version, child_index);
176                                self.batch_create_subtree(
177                                    new_child_node_key,
178                                    version,
179                                    &kvs[left..=right],
180                                    depth + 1,
181                                    hash_cache,
182                                    tree_cache,
183                                )?
184                            }
185                        };
186
187                    children.insert(
188                        child_index,
189                        Child::new(
190                            Self::get_hash(&new_child_node_key, &new_child_node, hash_cache),
191                            version,
192                            new_child_node.node_type(),
193                        ),
194                    );
195                }
196                let new_internal_node = InternalNode::new(children);
197
198                node_key.set_version(version);
199
200                // Cache this new internal node.
201                tree_cache.put_node(node_key.clone(), new_internal_node.clone().into())?;
202                (node_key, new_internal_node.into())
203            }
204            Node::Leaf(leaf_node) => {
205                // We are on a leaf node but trying to insert another node, so we may diverge.
206                // We always delete the existing leaf node here because it will not be referenced anyway
207                // since this version.
208                tree_cache.delete_node(&node_key, true /* is_leaf */);
209                node_key.set_version(version);
210                self.batch_create_subtree_with_existing_leaf(
211                    node_key, version, leaf_node, kvs, depth, hash_cache, tree_cache,
212                )?
213            }
214            Node::Null => {
215                if !node_key.nibble_path().is_empty() {
216                    bail!(
217                        "Null node exists for non-root node with node_key {:?}",
218                        node_key
219                    );
220                }
221
222                if node_key.version() == version {
223                    tree_cache.delete_node(&node_key, false /* is_leaf */);
224                }
225                self.batch_create_subtree(
226                    NodeKey::new_empty_path(version),
227                    version,
228                    kvs,
229                    depth,
230                    hash_cache,
231                    tree_cache,
232                )?
233            }
234        })
235    }
236
237    #[allow(clippy::too_many_arguments)]
238    fn batch_create_subtree_with_existing_leaf(
239        &self,
240        node_key: NodeKey,
241        version: Version,
242        existing_leaf_node: LeafNode,
243        kvs: &[(KeyHash, ValueHash)],
244        depth: usize,
245        hash_cache: &Option<&HashMap<NibblePath, HashBytes>>,
246        tree_cache: &mut TreeCache<R>,
247    ) -> Result<(NodeKey, Node)> {
248        let existing_leaf_key = existing_leaf_node.key_hash();
249
250        if kvs.len() == 1 && kvs[0].0 == existing_leaf_key {
251            let new_leaf_node = Node::Leaf(LeafNode::new(existing_leaf_key, kvs[0].1));
252            tree_cache.put_node(node_key.clone(), new_leaf_node.clone())?;
253            Ok((node_key, new_leaf_node))
254        } else {
255            let existing_leaf_bucket = existing_leaf_key.0.get_nibble(depth);
256            let mut isolated_existing_leaf = true;
257            let mut children = Children::new();
258            for (left, right) in NibbleRangeIterator::new(kvs, depth) {
259                let child_index = kvs[left].0.0.get_nibble(depth);
260                let child_node_key = node_key.gen_child_node_key(version, child_index);
261                let (new_child_node_key, new_child_node) = if existing_leaf_bucket == child_index {
262                    isolated_existing_leaf = false;
263                    self.batch_create_subtree_with_existing_leaf(
264                        child_node_key,
265                        version,
266                        existing_leaf_node.clone(),
267                        &kvs[left..=right],
268                        depth + 1,
269                        hash_cache,
270                        tree_cache,
271                    )?
272                } else {
273                    self.batch_create_subtree(
274                        child_node_key,
275                        version,
276                        &kvs[left..=right],
277                        depth + 1,
278                        hash_cache,
279                        tree_cache,
280                    )?
281                };
282                children.insert(
283                    child_index,
284                    Child::new(
285                        Self::get_hash(&new_child_node_key, &new_child_node, hash_cache),
286                        version,
287                        new_child_node.node_type(),
288                    ),
289                );
290            }
291            if isolated_existing_leaf {
292                let existing_leaf_node_key =
293                    node_key.gen_child_node_key(version, existing_leaf_bucket);
294                children.insert(
295                    existing_leaf_bucket,
296                    Child::new(existing_leaf_node.hash::<H>(), version, NodeType::Leaf),
297                );
298
299                tree_cache.put_node(existing_leaf_node_key, existing_leaf_node.into())?;
300            }
301
302            let new_internal_node = InternalNode::new(children);
303
304            tree_cache.put_node(node_key.clone(), new_internal_node.clone().into())?;
305            Ok((node_key, new_internal_node.into()))
306        }
307    }
308
309    #[allow(clippy::only_used_in_recursion)]
310    fn batch_create_subtree(
311        &self,
312        node_key: NodeKey,
313        version: Version,
314        kvs: &[(KeyHash, ValueHash)],
315        depth: usize,
316        hash_cache: &Option<&HashMap<NibblePath, HashBytes>>,
317        tree_cache: &mut TreeCache<R>,
318    ) -> Result<(NodeKey, Node)> {
319        if kvs.len() == 1 {
320            let new_leaf_node = Node::Leaf(LeafNode::new(kvs[0].0, kvs[0].1));
321            tree_cache.put_node(node_key.clone(), new_leaf_node.clone())?;
322            Ok((node_key, new_leaf_node))
323        } else {
324            let mut children = Children::new();
325            for (left, right) in NibbleRangeIterator::new(kvs, depth) {
326                let child_index = kvs[left].0.0.get_nibble(depth);
327                let child_node_key = node_key.gen_child_node_key(version, child_index);
328                let (new_child_node_key, new_child_node) = self.batch_create_subtree(
329                    child_node_key,
330                    version,
331                    &kvs[left..=right],
332                    depth + 1,
333                    hash_cache,
334                    tree_cache,
335                )?;
336                children.insert(
337                    child_index,
338                    Child::new(
339                        Self::get_hash(&new_child_node_key, &new_child_node, hash_cache),
340                        version,
341                        new_child_node.node_type(),
342                    ),
343                );
344            }
345            let new_internal_node = InternalNode::new(children);
346
347            tree_cache.put_node(node_key.clone(), new_internal_node.clone().into())?;
348            Ok((node_key, new_internal_node.into()))
349        }
350    }
351
352    /// This is a convenient function that calls
353    /// [`put_value_sets`](struct.JellyfishMerkleTree.html#method.put_value_sets) with a single
354    /// `keyed_value_set`.
355    pub fn put_value_set(
356        &self,
357        value_set: impl IntoIterator<Item = (KeyHash, Option<OwnedValue>)>,
358        version: Version,
359    ) -> Result<(RootHash, TreeUpdateBatch)> {
360        let (root_hashes, tree_update_batch) = self.put_value_sets(vec![value_set], version)?;
361        assert_eq!(
362            root_hashes.len(),
363            1,
364            "root_hashes must consist of a single value.",
365        );
366        Ok((root_hashes[0], tree_update_batch))
367    }
368
369    /// This is a convenient function that calls
370    /// [`put_value_sets_with_proof`](struct.JellyfishMerkleTree.html#method.put_value_sets) with a single
371    /// `keyed_value_set`.
372    pub fn put_value_set_with_proof(
373        &self,
374        value_set: impl IntoIterator<Item = (KeyHash, Option<OwnedValue>)>,
375        version: Version,
376    ) -> Result<(RootHash, UpdateMerkleProof<H>, TreeUpdateBatch)> {
377        let (mut hash_and_proof, batch_update) =
378            self.put_value_sets_with_proof(vec![value_set], version)?;
379        assert_eq!(
380            hash_and_proof.len(),
381            1,
382            "root_hashes must consist of a single value.",
383        );
384
385        let (hash, proof) = hash_and_proof.pop().unwrap();
386
387        Ok((hash, proof, batch_update))
388    }
389
390    /// Returns the new nodes and values in a batch after applying `value_set`. For
391    /// example, if after transaction `T_i` the committed state of tree in the persistent storage
392    /// looks like the following structure:
393    ///
394    /// ```text
395    ///              S_i
396    ///             /   \
397    ///            .     .
398    ///           .       .
399    ///          /         \
400    ///         o           x
401    ///        / \
402    ///       A   B
403    ///        storage (disk)
404    /// ```
405    ///
406    /// where `A` and `B` denote the states of two adjacent accounts, and `x` is a sibling subtree
407    /// of the path from root to A and B in the tree. Then a `value_set` produced by the next
408    /// transaction `T_{i+1}` modifies other accounts `C` and `D` exist in the subtree under `x`, a
409    /// new partial tree will be constructed in memory and the structure will be:
410    ///
411    /// ```text
412    ///                 S_i      |      S_{i+1}
413    ///                /   \     |     /       \
414    ///               .     .    |    .         .
415    ///              .       .   |   .           .
416    ///             /         \  |  /             \
417    ///            /           x | /               x'
418    ///           o<-------------+-               / \
419    ///          / \             |               C   D
420    ///         A   B            |
421    ///           storage (disk) |    cache (memory)
422    /// ```
423    ///
424    /// With this design, we are able to query the global state in persistent storage and
425    /// generate the proposed tree delta based on a specific root hash and `value_set`. For
426    /// example, if we want to execute another transaction `T_{i+1}'`, we can use the tree `S_i` in
427    /// storage and apply the `value_set` of transaction `T_{i+1}`. Then if the storage commits
428    /// the returned batch, the state `S_{i+1}` is ready to be read from the tree by calling
429    /// [`get_with_proof`](struct.JellyfishMerkleTree.html#method.get_with_proof). Anything inside
430    /// the batch is not reachable from public interfaces before being committed.
431    pub fn put_value_sets(
432        &self,
433        value_sets: impl IntoIterator<Item = impl IntoIterator<Item = (KeyHash, Option<OwnedValue>)>>,
434        first_version: Version,
435    ) -> Result<(Vec<RootHash>, TreeUpdateBatch)> {
436        let mut tree_cache = TreeCache::new(self.reader, first_version)?;
437        for (idx, value_set) in value_sets.into_iter().enumerate() {
438            let version = first_version + idx as u64;
439            for (i, (key, value)) in value_set.into_iter().enumerate() {
440                let action = if value.is_some() { "insert" } else { "delete" };
441                let value_hash = value.as_ref().map(|v| ValueHash::with::<H>(v));
442                tree_cache.put_value(version, key, value);
443                self.put(key, value_hash, version, &mut tree_cache, false)
444                    .with_context(|| {
445                        format!(
446                            "failed to {} key {} for version {}, key = {:?}",
447                            action, i, version, key
448                        )
449                    })?;
450            }
451
452            // Freezes the current cache to make all contents in the current cache immutable.
453            tree_cache.freeze::<H>()?;
454        }
455
456        Ok(tree_cache.into())
457    }
458
459    #[cfg(feature = "migration")]
460    /// Append value sets to the latest version of the tree, without incrementing its version.
461    pub fn append_value_set(
462        &self,
463        value_set: impl IntoIterator<Item = (KeyHash, Option<OwnedValue>)>,
464        latest_version: Version,
465    ) -> Result<(RootHash, TreeUpdateBatch)> {
466        let mut tree_cache = TreeCache::new_overwrite(self.reader, latest_version)?;
467        for (i, (key, value)) in value_set.into_iter().enumerate() {
468            let action = if value.is_some() { "insert" } else { "delete" };
469            let value_hash = value.as_ref().map(|v| ValueHash::with::<H>(v));
470            tree_cache.put_value(latest_version, key, value);
471            self.put(key, value_hash, latest_version, &mut tree_cache, false)
472                .with_context(|| {
473                    format!(
474                        "failed to {} key {} for version {}, key = {:?}",
475                        action, i, latest_version, key
476                    )
477                })?;
478        }
479
480        // Freezes the current cache to make all contents in the current cache immutable.
481        tree_cache.freeze::<H>()?;
482        let (root_hash_vec, tree_batch) = tree_cache.into();
483        if root_hash_vec.len() != 1 {
484            bail!(
485                "appending a value set failed, we expected a single root hash, but got {}",
486                root_hash_vec.len()
487            );
488        }
489        Ok((root_hash_vec[0], tree_batch))
490    }
491
492    /// Same as [`put_value_sets`], this method returns a Merkle proof for every update of the Merkle tree.
493    /// The proofs can be verified using the [`verify_update`] method, which requires the old `root_hash`, the `merkle_proof` and the new `root_hash`
494    /// The first argument contains all the root hashes that were stored in the tree cache so far. The last one is the new root hash of the tree.
495    pub fn put_value_sets_with_proof(
496        &self,
497        value_sets: impl IntoIterator<Item = impl IntoIterator<Item = (KeyHash, Option<OwnedValue>)>>,
498        first_version: Version,
499    ) -> Result<(RootProofs<H>, TreeUpdateBatch)> {
500        let mut tree_cache = TreeCache::new(self.reader, first_version)?;
501        let mut batch_proofs = Vec::new();
502        for (idx, value_set) in value_sets.into_iter().enumerate() {
503            let version = first_version + idx as u64;
504            let mut proofs = Vec::new();
505            for (i, (key, value)) in value_set.into_iter().enumerate() {
506                let action = if value.is_some() { "insert" } else { "delete" };
507                let value_hash = value.as_ref().map(|v| ValueHash::with::<H>(v));
508                tree_cache.put_value(version, key, value.clone());
509                let merkle_proof = self
510                    .put(key, value_hash, version, &mut tree_cache, true)
511                    .with_context(|| {
512                        format!(
513                            "failed to {} key {} for version {}, key = {:?}",
514                            action, i, version, key
515                        )
516                    })?
517                    .unwrap();
518
519                proofs.push(merkle_proof);
520            }
521
522            batch_proofs.push(UpdateMerkleProof::new(proofs));
523
524            // Freezes the current cache to make all contents in the current cache immutable.
525            tree_cache.freeze::<H>()?;
526        }
527
528        let (root_hashes, update_batch): (Vec<RootHash>, TreeUpdateBatch) = tree_cache.into();
529
530        let zipped_hashes_proofs = root_hashes.into_iter().zip(batch_proofs).collect();
531
532        Ok((zipped_hashes_proofs, update_batch))
533    }
534
535    fn put(
536        &self,
537        key: KeyHash,
538        value: Option<ValueHash>,
539        version: Version,
540        tree_cache: &mut TreeCache<R>,
541        with_proof: bool,
542    ) -> Result<Option<SparseMerkleProof<H>>> {
543        // tree_cache.ensure_initialized()?;
544
545        let nibble_path = NibblePath::new(key.0.to_vec());
546
547        // Get the root node. If this is the first operation, it would get the root node from the
548        // underlying db. Otherwise it most likely would come from `cache`.
549        let root_node_key = tree_cache.get_root_node_key().clone();
550        let mut nibble_iter = nibble_path.nibbles();
551
552        let (put_result, merkle_proof) = self.insert_at(
553            root_node_key,
554            version,
555            &mut nibble_iter,
556            value,
557            tree_cache,
558            with_proof,
559        )?;
560
561        // Start insertion from the root node.
562        match put_result {
563            PutResult::Updated((new_root_node_key, _)) => {
564                tree_cache.set_root_node_key(new_root_node_key);
565            }
566            PutResult::NotChanged => {
567                // Nothing has changed, so do nothing
568            }
569            PutResult::Removed => {
570                // root node becomes empty, insert a null node at root
571                let genesis_root_key = NodeKey::new_empty_path(version);
572                tree_cache.set_root_node_key(genesis_root_key.clone());
573                tree_cache.put_node(genesis_root_key, Node::new_null())?;
574            }
575        }
576
577        Ok(merkle_proof)
578    }
579
580    /// Helper function for recursive insertion into the subtree that starts from the current
581    /// [`NodeKey`](node_type/struct.NodeKey.html). Returns the newly inserted node.
582    /// It is safe to use recursion here because the max depth is limited by the key length which
583    /// for this tree is the length of the hash of account addresses.
584    fn insert_at(
585        &self,
586        root_node_key: NodeKey,
587        version: Version,
588        nibble_iter: &mut NibbleIterator,
589        value: Option<ValueHash>,
590        tree_cache: &mut TreeCache<R>,
591        with_proof: bool,
592    ) -> PutOutcome<H> {
593        // Because deletions could cause the root node not to exist, we try to get the root node,
594        // and if it doesn't exist, we synthesize a `Null` node, noting that it hasn't yet been
595        // committed anywhere (we need to track this because the tree cache will panic if we try to
596        // delete a node that it doesn't know about).
597        let (node, node_already_exists) = tree_cache
598            .get_node_option(&root_node_key)?
599            .map(|node| (node, true))
600            .unwrap_or((Node::Null, false));
601
602        match node {
603            Node::Internal(internal_node) => self.insert_at_internal_node(
604                root_node_key,
605                internal_node,
606                version,
607                nibble_iter,
608                value,
609                tree_cache,
610                with_proof,
611            ),
612            Node::Leaf(leaf_node) => self.insert_at_leaf_node(
613                root_node_key,
614                leaf_node,
615                version,
616                nibble_iter,
617                value,
618                tree_cache,
619                with_proof,
620            ),
621            Node::Null => {
622                let merkle_proof_null = if with_proof {
623                    Some(SparseMerkleProof::new(None, vec![]))
624                } else {
625                    None
626                };
627
628                if !root_node_key.nibble_path().is_empty() {
629                    bail!(
630                        "Null node exists for non-root node with node_key {:?}",
631                        root_node_key
632                    );
633                }
634                // Delete the old null node if the at the same version
635                if root_node_key.version() == version && node_already_exists {
636                    tree_cache.delete_node(&root_node_key, false /* is_leaf */);
637                }
638                if let Some(value) = value {
639                    // If we're inserting into the null root node, we should change it to be a leaf node
640                    let (new_root_node_key, new_root_node) = Self::create_leaf_node(
641                        NodeKey::new_empty_path(version),
642                        nibble_iter,
643                        value,
644                        tree_cache,
645                    )?;
646                    Ok((
647                        PutResult::Updated((new_root_node_key, new_root_node)),
648                        merkle_proof_null,
649                    ))
650                } else {
651                    // If we're deleting from the null root node, nothing needs to change
652                    Ok((PutResult::NotChanged, merkle_proof_null))
653                }
654            }
655        }
656    }
657
658    /// Helper function for recursive insertion into the subtree that starts from the current
659    /// `internal_node`. Returns the newly inserted node with its
660    /// [`NodeKey`](node_type/struct.NodeKey.html).
661    #[allow(clippy::too_many_arguments)]
662    fn insert_at_internal_node(
663        &self,
664        mut node_key: NodeKey,
665        internal_node: InternalNode,
666        version: Version,
667        nibble_iter: &mut NibbleIterator,
668        value: Option<ValueHash>,
669        tree_cache: &mut TreeCache<R>,
670        with_proof: bool,
671    ) -> PutOutcome<H> {
672        // Find the next node to visit following the next nibble as index.
673        let child_index = nibble_iter.next().expect("Ran out of nibbles");
674
675        // Traverse downwards from this internal node recursively to get the `node_key` of the child
676        // node at `child_index`.
677        let (put_result, merkle_proof) = match internal_node.child(child_index) {
678            Some(child) => {
679                let (child_node_key, mut siblings) = if with_proof {
680                    let (child_key, siblings) = internal_node.get_child_with_siblings::<H>(
681                        tree_cache,
682                        &node_key,
683                        child_index,
684                    );
685                    (child_key.unwrap(), siblings)
686                } else {
687                    (
688                        node_key.gen_child_node_key(child.version, child_index),
689                        vec![],
690                    )
691                };
692
693                let (update_result, proof_opt) = self.insert_at(
694                    child_node_key,
695                    version,
696                    nibble_iter,
697                    value,
698                    tree_cache,
699                    with_proof,
700                )?;
701
702                let new_proof_opt = proof_opt.map(|proof| {
703                    // The move siblings function allows zero copy moves for proof
704                    let proof_leaf = proof.leaf();
705                    let mut new_siblings = proof.take_siblings();
706                    // We need to reverse the siblings
707                    siblings.reverse();
708                    new_siblings.append(&mut siblings);
709                    SparseMerkleProof::new(proof_leaf, new_siblings)
710                });
711
712                (update_result, new_proof_opt)
713            }
714            None => {
715                // In that case we couldn't find a child for this node at the nibble's position.
716                // We have to traverse down the virtual 4-level tree (which is the compressed
717                // representation of the jellyfish merkle tree) to get the closest leaf of the nibble
718                // we are looking for.
719                let merkle_proof = if with_proof {
720                    let (child_key_opt, mut siblings) = internal_node
721                        .get_only_child_with_siblings::<H>(tree_cache, &node_key, child_index);
722
723                    let leaf: Option<SparseMerkleLeafNode> = child_key_opt.map(|child_key|
724                    {
725                        // We should be able to find the node in the case
726                        let node = tree_cache.get_node(&child_key).expect("this node should be in the cache");
727                        match node {
728                            Leaf(leaf_node) => {
729                                leaf_node.into()
730                            },
731                            _ => unreachable!("get_only_child_with_siblings should return a leaf node in that case")
732                        }
733                    });
734
735                    siblings.reverse();
736                    Some(SparseMerkleProof::new(leaf, siblings))
737                } else {
738                    None
739                };
740
741                if let Some(value) = value {
742                    // insert
743                    let new_child_node_key = node_key.gen_child_node_key(version, child_index);
744
745                    // The Merkle proof doesn't have a leaf
746                    (
747                        PutResult::Updated(Self::create_leaf_node(
748                            new_child_node_key,
749                            nibble_iter,
750                            value,
751                            tree_cache,
752                        )?),
753                        merkle_proof,
754                    )
755                } else {
756                    // If there was no changes, don't generate a proof
757                    (
758                        PutResult::NotChanged,
759                        if with_proof {
760                            Some(SparseMerkleProof::new(None, vec![]))
761                        } else {
762                            None
763                        },
764                    )
765                }
766            }
767        };
768
769        // Reuse the current `InternalNode` in memory to create a new internal node.
770        let mut children: Children = internal_node.into();
771        match put_result {
772            PutResult::NotChanged => {
773                return Ok((
774                    PutResult::NotChanged,
775                    if with_proof {
776                        Some(SparseMerkleProof::new(None, vec![]))
777                    } else {
778                        None
779                    },
780                ));
781            }
782            PutResult::Updated((_, new_node)) => {
783                // update child
784                children.insert(
785                    child_index,
786                    Child::new(new_node.hash::<H>(), version, new_node.node_type()),
787                );
788            }
789            PutResult::Removed => {
790                // remove child
791                children.remove(child_index);
792            }
793        }
794
795        // We always delete the existing internal node here because it will not be referenced anyway
796        // since this version.
797        tree_cache.delete_node(&node_key, false /* is_leaf */);
798
799        let mut it = children.iter();
800        if let Some((child_nibble, child)) = it.next() {
801            if it.next().is_none() && child.is_leaf() {
802                // internal node has only one child left and it's leaf node, replace it with the leaf node
803                let child_key = node_key.gen_child_node_key(child.version, child_nibble);
804                let child_node = tree_cache.get_node(&child_key)?;
805                tree_cache.delete_node(&child_key, true /* is_leaf */);
806
807                node_key.set_version(version);
808                tree_cache.put_node(node_key.clone(), child_node.clone())?;
809                Ok((PutResult::Updated((node_key, child_node)), merkle_proof))
810            } else {
811                drop(it);
812                let new_internal_node: InternalNode = InternalNode::new(children);
813
814                node_key.set_version(version);
815
816                // Cache this new internal node.
817                tree_cache.put_node(node_key.clone(), new_internal_node.clone().into())?;
818                Ok((
819                    PutResult::Updated((node_key, new_internal_node.into())),
820                    merkle_proof,
821                ))
822            }
823        } else {
824            // internal node becomes empty, remove it
825            Ok((PutResult::Removed, merkle_proof))
826        }
827    }
828
829    /// Helper function for recursive insertion into the subtree that starts from the
830    /// `existing_leaf_node`. Returns the newly inserted node with its
831    /// [`NodeKey`](node_type/struct.NodeKey.html).
832    #[allow(clippy::too_many_arguments)]
833    fn insert_at_leaf_node(
834        &self,
835        /* the root of the subtree we are inserting into */
836        mut node_key: NodeKey,
837        /* the leaf node that we are inserting at */
838        existing_leaf_node: LeafNode,
839        version: Version,
840        /* the nibble iterator of the key hash we are inserting */
841        nibble_iter: &mut NibbleIterator,
842        value_hash: Option<ValueHash>,
843        tree_cache: &mut TreeCache<R>,
844        with_proof: bool,
845    ) -> PutOutcome<H> {
846        // We are inserting a new key that shares a common prefix with the existing leaf node.
847        // This check is to make sure that the visited nibble path of the inserted key is a
848        // subpath of the existing leaf node's nibble path.
849        let mut visited_path = nibble_iter.visited_nibbles();
850        let path_to_leaf_node = NibblePath::new(existing_leaf_node.key_hash().0.to_vec());
851        let mut path_to_leaf = path_to_leaf_node.nibbles();
852        skip_common_prefix(&mut visited_path, &mut path_to_leaf);
853
854        assert!(
855            visited_path.is_finished(),
856            "Inserting a key at the wrong leaf node (no common prefix - index={})",
857            path_to_leaf.visited_nibbles().num_nibbles()
858        );
859
860        // We have established that the visited nibble path of the inserted key is a prefix of the
861        // leaf node's nibble path. Now, we can check if the unvisited nibble path of the inserted
862        // key overlaps with more the leaf node's nibble path.
863        let mut path_to_leaf_remaining = path_to_leaf.remaining_nibbles();
864        // To do this, we skip the common prefix between the remaining nibbles of the inserted key and
865        // and those of the leaf node.
866        let common_nibbles = skip_common_prefix(nibble_iter, &mut path_to_leaf_remaining);
867        let mut common_nibble_path = nibble_iter.visited_nibbles().collect::<NibblePath>();
868
869        // If we have exhausted the nibble iterator of the inserted key, this means that the
870        // inserted key and leaf node have the same path. In this case, we just need to update the
871        // value of the leaf node.
872        if nibble_iter.is_finished() {
873            assert!(path_to_leaf_remaining.is_finished());
874            tree_cache.delete_node(&node_key, true /* is_leaf */);
875
876            let merkle_proof = if with_proof {
877                Some(SparseMerkleProof::new(
878                    Some(existing_leaf_node.into()),
879                    vec![],
880                ))
881            } else {
882                None
883            };
884
885            if let Some(value_hash) = value_hash {
886                // The new leaf node will have the same nibble_path with a new version as node_key.
887                node_key.set_version(version);
888                // Create the new leaf node with the same address but new blob content.
889                return Ok((
890                    PutResult::Updated(Self::create_leaf_node(
891                        node_key,
892                        nibble_iter,
893                        value_hash,
894                        tree_cache,
895                    )?),
896                    merkle_proof,
897                ));
898            } else {
899                // deleted
900                return Ok((PutResult::Removed, merkle_proof));
901            };
902        }
903
904        // If skipping the common prefix leaves us with some remaining nibbles, this means that the
905        // two nibble paths do overlap, but are not identical. In this case, we need to create an internal
906        // node to represent the common prefix, and two leaf nodes to represent each leaves.
907        if let Some(value) = value_hash {
908            tree_cache.delete_node(&node_key, true /* is_leaf */);
909
910            // 2.2. both are unfinished(They have keys with same length so it's impossible to have one
911            // finished and the other not). This means the incoming key forks at some point between the
912            // position where step 1 ends and the last nibble, inclusive. Then create a seris of
913            // internal nodes the number of which equals to the length of the extra part of the
914            // common prefix in step 2, a new leaf node for the incoming key, and update the
915            // [`NodeKey`] of existing leaf node. We create new internal nodes in a bottom-up
916            // order.
917            let existing_leaf_index = path_to_leaf_remaining.next().expect("Ran out of nibbles");
918            let new_leaf_index = nibble_iter.next().expect("Ran out of nibbles");
919            assert_ne!(existing_leaf_index, new_leaf_index);
920
921            let mut children = Children::new();
922            children.insert(
923                existing_leaf_index,
924                Child::new(existing_leaf_node.hash::<H>(), version, NodeType::Leaf),
925            );
926            node_key = NodeKey::new(version, common_nibble_path.clone());
927            tree_cache.put_node(
928                node_key.gen_child_node_key(version, existing_leaf_index),
929                existing_leaf_node.clone().into(),
930            )?;
931
932            let (_, new_leaf_node) = Self::create_leaf_node(
933                node_key.gen_child_node_key(version, new_leaf_index),
934                nibble_iter,
935                value,
936                tree_cache,
937            )?;
938            children.insert(
939                new_leaf_index,
940                Child::new(new_leaf_node.hash::<H>(), version, NodeType::Leaf),
941            );
942
943            let internal_node = InternalNode::new(children);
944            let mut next_internal_node = internal_node.clone();
945            tree_cache.put_node(node_key.clone(), internal_node.into())?;
946
947            for _i in 0..common_nibbles {
948                // Pop a nibble from the end of path.
949                let nibble = common_nibble_path
950                    .pop()
951                    .expect("Common nibble_path below internal node ran out of nibble");
952                node_key = NodeKey::new(version, common_nibble_path.clone());
953                let mut children = Children::new();
954                children.insert(
955                    nibble,
956                    Child::new(
957                        next_internal_node.hash::<H>(),
958                        version,
959                        next_internal_node.node_type(),
960                    ),
961                );
962                let internal_node = InternalNode::new(children);
963                next_internal_node = internal_node.clone();
964                tree_cache.put_node(node_key.clone(), internal_node.into())?;
965            }
966
967            Ok((
968                PutResult::Updated((node_key, next_internal_node.into())),
969                if with_proof {
970                    Some(SparseMerkleProof::new(
971                        Some(existing_leaf_node.into()),
972                        vec![],
973                    ))
974                } else {
975                    None
976                },
977            ))
978        } else {
979            // delete not found
980            Ok((
981                PutResult::NotChanged,
982                if with_proof {
983                    Some(SparseMerkleProof::new(None, vec![]))
984                } else {
985                    None
986                },
987            ))
988        }
989    }
990
991    /// Helper function for creating leaf nodes. Returns the newly created leaf node.
992    fn create_leaf_node(
993        node_key: NodeKey,
994        nibble_iter: &NibbleIterator,
995        value_hash: ValueHash,
996        tree_cache: &mut TreeCache<R>,
997    ) -> Result<(NodeKey, Node)> {
998        // Get the underlying bytes of nibble_iter which must be a key, i.e., hashed account address
999        // with `HashValue::LENGTH` bytes.
1000        let new_leaf_node = Node::new_leaf(
1001            KeyHash(
1002                nibble_iter
1003                    .get_nibble_path()
1004                    .bytes()
1005                    .try_into()
1006                    .expect("LeafNode must have full nibble path."),
1007            ),
1008            value_hash,
1009        );
1010
1011        tree_cache.put_node(node_key.clone(), new_leaf_node.clone())?;
1012        Ok((node_key, new_leaf_node))
1013    }
1014
1015    /// Returns the value (if applicable) and the corresponding merkle proof.
1016    pub fn get_with_proof(
1017        &self,
1018        key: KeyHash,
1019        version: Version,
1020    ) -> Result<(Option<OwnedValue>, SparseMerkleProof<H>)> {
1021        // Empty tree just returns proof with no sibling hash.
1022        let mut next_node_key = NodeKey::new_empty_path(version);
1023        let mut siblings: Vec<SparseMerkleNode> = vec![];
1024        let nibble_path = NibblePath::new(key.0.to_vec());
1025        let mut nibble_iter = nibble_path.nibbles();
1026
1027        // We limit the number of loops here deliberately to avoid potential cyclic graph bugs
1028        // in the tree structure.
1029        for nibble_depth in 0..=ROOT_NIBBLE_HEIGHT {
1030            let next_node = self.reader.get_node(&next_node_key).map_err(|err| {
1031                if nibble_depth == 0 {
1032                    anyhow::anyhow!(MissingRootError { version })
1033                } else {
1034                    err
1035                }
1036            })?;
1037            match next_node {
1038                Node::Internal(internal_node) => {
1039                    let queried_child_index = nibble_iter
1040                        .next()
1041                        .ok_or_else(|| format_err!("ran out of nibbles"))?;
1042
1043                    let (child_node_key, mut siblings_in_internal) = internal_node
1044                        .get_only_child_with_siblings::<H>(
1045                            self.reader,
1046                            &next_node_key,
1047                            queried_child_index,
1048                        );
1049
1050                    siblings.append(&mut siblings_in_internal);
1051                    next_node_key = match child_node_key {
1052                        Some(node_key) => node_key,
1053                        None => {
1054                            return Ok((
1055                                None,
1056                                SparseMerkleProof::new(None, {
1057                                    siblings.reverse();
1058                                    siblings
1059                                }),
1060                            ));
1061                        }
1062                    };
1063                }
1064                Node::Leaf(leaf_node) => {
1065                    return Ok((
1066                        if leaf_node.key_hash() == key {
1067                            Some(self.reader.get_value(version, leaf_node.key_hash())?)
1068                        } else {
1069                            None
1070                        },
1071                        SparseMerkleProof::new(Some(leaf_node.into()), {
1072                            siblings.reverse();
1073                            siblings
1074                        }),
1075                    ));
1076                }
1077                Node::Null => {
1078                    if nibble_depth == 0 {
1079                        return Ok((None, SparseMerkleProof::new(None, vec![])));
1080                    } else {
1081                        bail!(
1082                            "Non-root null node exists with node key {:?}",
1083                            next_node_key
1084                        );
1085                    }
1086                }
1087            }
1088        }
1089        bail!("Jellyfish Merkle tree has cyclic graph inside.");
1090    }
1091
1092    fn search_closest_extreme_node(
1093        &self,
1094        version: Version,
1095        extreme: Extreme,
1096        to: NibblePath,
1097        parents: Vec<InternalNode>,
1098    ) -> Result<Option<KeyHash>> {
1099        fn neighbor_nibble(
1100            node: &InternalNode,
1101            child_index: Nibble,
1102            extreme: Extreme,
1103        ) -> Option<(Nibble, Version)> {
1104            match extreme {
1105                // Rightmost left neighbor
1106                Extreme::Left => node
1107                    .children_unsorted()
1108                    .filter(|(nibble, _)| nibble < &child_index)
1109                    .max_by_key(|(nibble, _)| *nibble)
1110                    .map(|p| (p.0, p.1.version)),
1111                // Leftmost right neighbor
1112                Extreme::Right => node
1113                    .children_unsorted()
1114                    .filter(|(nibble, _)| nibble > &child_index)
1115                    .min_by_key(|(nibble, _)| *nibble)
1116                    .map(|p| (p.0, p.1.version)),
1117            }
1118        }
1119        let mut parents = parents;
1120        let mut path = to;
1121
1122        while let (Some(index), Some(parent)) = (path.pop(), parents.pop()) {
1123            if let Some((neighbor, found_version)) = neighbor_nibble(&parent, index, extreme) {
1124                // nibble path will represent the left nibble path. this is currently at
1125                // the parent of the leaf for `key`
1126                path.push(neighbor);
1127                return Ok(Some(self.get_extreme_key_hash(
1128                    version,
1129                    NodeKey::new(found_version, path.clone()),
1130                    path.num_nibbles(),
1131                    extreme.opposite(),
1132                )?));
1133            }
1134        }
1135        Ok(None)
1136    }
1137
1138    // given a search_key,
1139    fn search_for_closest_node(
1140        &self,
1141        version: Version,
1142        search_key: KeyHash,
1143    ) -> Result<SearchResult> {
1144        let search_path = NibblePath::new(search_key.0.to_vec());
1145        let mut search_nibbles = search_path.nibbles();
1146        let mut next_node_key = NodeKey::new_empty_path(version);
1147        let mut internal_nodes = vec![];
1148
1149        for nibble_depth in 0..=ROOT_NIBBLE_HEIGHT {
1150            let next_node = self.reader.get_node(&next_node_key).map_err(|err| {
1151                if nibble_depth == 0 {
1152                    anyhow::anyhow!(MissingRootError { version })
1153                } else {
1154                    err
1155                }
1156            })?;
1157
1158            match next_node {
1159                Node::Internal(node) => {
1160                    internal_nodes.push(node.clone());
1161                    let queried_child_index = search_nibbles
1162                        .next()
1163                        .ok_or_else(|| format_err!("ran out of nibbles"))?;
1164
1165                    let child_node_key =
1166                        node.get_only_child_without_siblings(&next_node_key, queried_child_index);
1167
1168                    match child_node_key {
1169                        Some(node_key) => {
1170                            next_node_key = node_key;
1171                        }
1172                        None => {
1173                            return Ok(SearchResult::FoundInternal {
1174                                path_to_internal: search_nibbles
1175                                    .visited_nibbles()
1176                                    .get_nibble_path(),
1177                                parents: internal_nodes,
1178                            });
1179                        }
1180                    }
1181                }
1182                Node::Leaf(node) => {
1183                    let key_hash = node.key_hash();
1184                    return Ok(SearchResult::FoundLeaf {
1185                        ordering: key_hash.cmp(&search_key),
1186                        leaf_hash: key_hash,
1187                        path_to_leaf: search_nibbles.visited_nibbles().get_nibble_path(),
1188                        parents: internal_nodes,
1189                    });
1190                }
1191                Node::Null => {
1192                    if nibble_depth == 0 {
1193                        bail!(
1194                            "Cannot manufacture nonexistence proof by exclusion for the empty tree"
1195                        );
1196                    } else {
1197                        bail!(
1198                            "Non-root null node exists with node key {:?}",
1199                            next_node_key
1200                        );
1201                    }
1202                }
1203            }
1204        }
1205
1206        bail!("Jellyfish Merkle tree has cyclic graph inside.");
1207    }
1208
1209    fn get_bounding_path(
1210        &self,
1211        search_key: KeyHash,
1212        version: Version,
1213    ) -> Result<(Option<KeyHash>, Option<KeyHash>)> {
1214        let search_result = self.search_for_closest_node(version, search_key)?;
1215
1216        match search_result {
1217            SearchResult::FoundLeaf {
1218                ordering,
1219                leaf_hash,
1220                path_to_leaf,
1221                parents,
1222            } => {
1223                match ordering {
1224                    Ordering::Less => {
1225                        // found the closest leaf to the left of the search key.
1226                        // find the other bound (the leftmost right keyhash)
1227                        let leftmost_right_keyhash = self.search_closest_extreme_node(
1228                            version,
1229                            Extreme::Right,
1230                            path_to_leaf,
1231                            parents,
1232                        )?;
1233
1234                        Ok((Some(leaf_hash), leftmost_right_keyhash))
1235                    }
1236                    Ordering::Greater => {
1237                        // found the closest leaf to the right of the search key
1238                        let rightmost_left_keyhash = self.search_closest_extreme_node(
1239                            version,
1240                            Extreme::Left,
1241                            path_to_leaf,
1242                            parents,
1243                        )?;
1244
1245                        Ok((rightmost_left_keyhash, Some(leaf_hash)))
1246                    }
1247                    Ordering::Equal => {
1248                        bail!(
1249                            "found exact key when searching for bounding path for nonexistence proof"
1250                        )
1251                    }
1252                }
1253            }
1254            SearchResult::FoundInternal {
1255                path_to_internal,
1256                parents,
1257            } => {
1258                let leftmost_right_keyhash = self.search_closest_extreme_node(
1259                    version,
1260                    Extreme::Right,
1261                    path_to_internal.clone(),
1262                    parents.clone(),
1263                )?;
1264                let rightmost_left_keyhash = self.search_closest_extreme_node(
1265                    version,
1266                    Extreme::Left,
1267                    path_to_internal,
1268                    parents,
1269                )?;
1270
1271                Ok((rightmost_left_keyhash, leftmost_right_keyhash))
1272            }
1273        }
1274    }
1275
1276    /// Returns the value (if applicable) and the corresponding merkle proof.
1277    pub fn get_with_exclusion_proof(
1278        &self,
1279        key_hash: KeyHash,
1280        version: Version,
1281    ) -> Result<ProofQueryResult<H>> {
1282        // Optimistically attempt get_with_proof, if that succeeds, we're done.
1283        if let (Some(value), proof) = self.get_with_proof(key_hash, version)? {
1284            return Ok(Ok((value, proof)));
1285        }
1286
1287        // Otherwise, we know this key doesn't exist, so construct an exclusion proof.
1288
1289        // first, find out what are its bounding path, i.e. the greatest key that is strictly less
1290        // than the non-present search key and/or the smallest key that is strictly greater than
1291        // the search key.
1292        let (left_bound, right_bound) = self.get_bounding_path(key_hash, version)?;
1293
1294        match (left_bound, right_bound) {
1295            (Some(left_bound), Some(right_bound)) => {
1296                let left_proof = self.get_with_proof(left_bound, version)?.1;
1297                let right_proof = self.get_with_proof(right_bound, version)?.1;
1298
1299                Ok(Err(ExclusionProof::Middle {
1300                    rightmost_left_proof: left_proof,
1301                    leftmost_right_proof: right_proof,
1302                }))
1303            }
1304            (Some(left_bound), None) => {
1305                let left_proof = self.get_with_proof(left_bound, version)?.1;
1306                Ok(Err(ExclusionProof::Rightmost {
1307                    rightmost_left_proof: left_proof,
1308                }))
1309            }
1310            (None, Some(right_bound)) => {
1311                let right_proof = self.get_with_proof(right_bound, version)?.1;
1312                Ok(Err(ExclusionProof::Leftmost {
1313                    leftmost_right_proof: right_proof,
1314                }))
1315            }
1316            _ => bail!("Invalid exclusion proof"),
1317        }
1318    }
1319
1320    fn get_extreme_key_hash(
1321        &self,
1322        version: Version,
1323        mut node_key: NodeKey,
1324        nibble_depth: usize,
1325        extreme: Extreme,
1326    ) -> Result<KeyHash> {
1327        // Depending on the extreme specified, get either the least nibble or the most nibble
1328        let min_or_max = |internal_node: &InternalNode| {
1329            match extreme {
1330                Extreme::Left => internal_node.children_unsorted().min_by_key(|c| c.0),
1331                Extreme::Right => internal_node.children_unsorted().max_by_key(|c| c.0),
1332            }
1333            .map(|(nibble, _)| nibble)
1334        };
1335
1336        for nibble_depth in nibble_depth..=ROOT_NIBBLE_HEIGHT {
1337            let node = self.reader.get_node(&node_key).map_err(|err| {
1338                if nibble_depth == 0 {
1339                    anyhow::anyhow!(MissingRootError { version })
1340                } else {
1341                    err
1342                }
1343            })?;
1344            match node {
1345                Node::Internal(internal_node) => {
1346                    // Find the leftmost nibble in the children
1347                    let queried_child_index =
1348                        min_or_max(&internal_node).expect("a child always exists");
1349                    let child_node_key = internal_node
1350                        .get_only_child_without_siblings(&node_key, queried_child_index);
1351                    // Proceed downwards
1352                    node_key = match child_node_key {
1353                        Some(node_key) => node_key,
1354                        None => {
1355                            bail!("Internal node has no children");
1356                        }
1357                    };
1358                }
1359                Node::Leaf(leaf_node) => {
1360                    return Ok(leaf_node.key_hash());
1361                }
1362                Node::Null => bail!("Null node cannot have children"),
1363            }
1364        }
1365        bail!("Jellyfish Merkle tree has cyclic graph inside.");
1366    }
1367
1368    fn get_without_proof(&self, key: KeyHash, version: Version) -> Result<Option<OwnedValue>> {
1369        self.reader.get_value_option(version, key)
1370    }
1371
1372    /// Gets the proof that shows a list of keys up to `rightmost_key_to_prove` exist at `version`.
1373    pub fn get_range_proof(
1374        &self,
1375        rightmost_key_to_prove: KeyHash,
1376        version: Version,
1377    ) -> Result<SparseMerkleRangeProof<H>> {
1378        let (account, proof) = self.get_with_proof(rightmost_key_to_prove, version)?;
1379        ensure!(account.is_some(), "rightmost_key_to_prove must exist.");
1380
1381        let siblings = proof
1382            .siblings()
1383            .iter()
1384            .rev()
1385            .zip(rightmost_key_to_prove.0.iter_bits())
1386            .filter_map(|(sibling, bit)| {
1387                // We only need to keep the siblings on the right.
1388                if !bit { Some(*sibling) } else { None }
1389            })
1390            .rev()
1391            .collect();
1392        Ok(SparseMerkleRangeProof::new(siblings))
1393    }
1394
1395    /// Returns the value (if applicable), without any proof.
1396    ///
1397    /// Equivalent to [`get_with_proof`](JellyfishMerkleTree::get_with_proof) and dropping the
1398    /// proof, but more efficient.
1399    pub fn get(&self, key: KeyHash, version: Version) -> Result<Option<OwnedValue>> {
1400        self.get_without_proof(key, version)
1401    }
1402
1403    fn get_root_node(&self, version: Version) -> Result<Node> {
1404        self.get_root_node_option(version)?
1405            .ok_or_else(|| format_err!("Root node not found for version {}.", version))
1406    }
1407
1408    pub(crate) fn get_root_node_option(&self, version: Version) -> Result<Option<Node>> {
1409        let root_node_key = NodeKey::new_empty_path(version);
1410        self.reader.get_node_option(&root_node_key)
1411    }
1412
1413    pub fn get_root_hash(&self, version: Version) -> Result<RootHash> {
1414        self.get_root_node(version).map(|n| RootHash(n.hash::<H>()))
1415    }
1416
1417    pub fn get_root_hash_option(&self, version: Version) -> Result<Option<RootHash>> {
1418        Ok(self
1419            .get_root_node_option(version)?
1420            .map(|n| RootHash(n.hash::<H>())))
1421    }
1422
1423    // TODO: should this be public? seems coupled to tests?
1424    pub fn get_leaf_count(&self, version: Version) -> Result<usize> {
1425        self.get_root_node(version).map(|n| n.leaf_count())
1426    }
1427}
1428
1429/// The result of putting a single key-value pair into the tree, or deleting a key.
1430enum PutResult<T> {
1431    // Put a key-value pair successfully.
1432    Updated(T),
1433    // Deleted a key successfully.
1434    Removed,
1435    // Key to delete not found.
1436    NotChanged,
1437}
1438
1439/// A proof of non-existence by exclusion between two adjacent neighbors.
1440#[derive(Debug)]
1441pub enum ExclusionProof<H: SimpleHasher> {
1442    Leftmost {
1443        leftmost_right_proof: SparseMerkleProof<H>,
1444    },
1445    Middle {
1446        leftmost_right_proof: SparseMerkleProof<H>,
1447        rightmost_left_proof: SparseMerkleProof<H>,
1448    },
1449    Rightmost {
1450        rightmost_left_proof: SparseMerkleProof<H>,
1451    },
1452}
1453
1454#[derive(Debug, Clone, Copy)]
1455enum Extreme {
1456    Left,
1457    Right,
1458}
1459
1460impl Extreme {
1461    fn opposite(&self) -> Self {
1462        match self {
1463            Extreme::Left => Extreme::Right,
1464            Extreme::Right => Extreme::Left,
1465        }
1466    }
1467}
1468
1469#[derive(Debug)]
1470enum SearchResult {
1471    FoundLeaf {
1472        ordering: Ordering,
1473        leaf_hash: KeyHash,
1474        path_to_leaf: NibblePath,
1475        parents: Vec<InternalNode>,
1476    },
1477    FoundInternal {
1478        path_to_internal: NibblePath,
1479        parents: Vec<InternalNode>,
1480    },
1481}