jmt/
tree.rs

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