fuel_merkle/sparse/
merkle_tree.rs

1mod branch;
2mod node;
3
4use branch::{
5    merge_branches,
6    Branch,
7};
8use node::{
9    Node,
10    StorageNode,
11    StorageNodeError,
12};
13
14use crate::{
15    common::{
16        error::DeserializeError,
17        node::ChildError,
18        AsPathIterator,
19        Bytes32,
20    },
21    sparse::{
22        empty_sum,
23        proof::{
24            ExclusionLeaf,
25            ExclusionLeafData,
26            ExclusionProof,
27            InclusionProof,
28            Proof,
29        },
30        Primitive,
31    },
32    storage::{
33        Mappable,
34        StorageInspect,
35        StorageMutate,
36    },
37};
38use alloc::{
39    format,
40    vec::Vec,
41};
42use core::{
43    fmt::{
44        Debug,
45        Formatter,
46    },
47    iter,
48    marker::PhantomData,
49    ops::Deref,
50};
51
52#[derive(Debug, Clone, derive_more::Display)]
53pub enum MerkleTreeError<StorageError> {
54    #[display(
55        fmt = "cannot load node with key {}; the key is not found in storage",
56        "hex::encode(_0)"
57    )]
58    LoadError(Bytes32),
59
60    #[display(fmt = "{}", _0)]
61    StorageError(StorageError),
62
63    #[display(fmt = "{}", _0)]
64    DeserializeError(DeserializeError),
65
66    #[display(fmt = "{}", _0)]
67    ChildError(ChildError<Bytes32, StorageNodeError<StorageError>>),
68}
69
70impl<StorageError> From<StorageError> for MerkleTreeError<StorageError> {
71    fn from(err: StorageError) -> MerkleTreeError<StorageError> {
72        MerkleTreeError::StorageError(err)
73    }
74}
75
76/// The safe Merkle tree storage key prevents Merkle tree structure manipulations.
77/// The type contains only one constructor that hashes the storage key.
78#[derive(Clone, Copy, PartialEq, Eq, Hash)]
79#[cfg_attr(test, derive(proptest_derive::Arbitrary))]
80pub struct MerkleTreeKey(Bytes32);
81
82impl MerkleTreeKey {
83    /// The safe way to create a `Self`. It hashes the `storage_key`, making
84    /// it entirely random and preventing SMT structure manipulation.
85    pub fn new<B>(storage_key: B) -> Self
86    where
87        B: AsRef<[u8]>,
88    {
89        use digest::Digest;
90        let mut hash = sha2::Sha256::new();
91        hash.update(storage_key.as_ref());
92        let hash = hash.finalize().into();
93
94        Self(hash)
95    }
96
97    /// Unsafe analog to create a `Self` that doesn't hash the `storage_key` unlike
98    /// `Self::new`.
99    ///
100    /// # Safety
101    ///
102    /// It is safe to use this method if you know that `storage_key`
103    /// was randomly generated like `ContractId` or `AssetId`.
104    pub unsafe fn convert<B>(storage_key: B) -> Self
105    where
106        B: Into<Bytes32>,
107    {
108        Self(storage_key.into())
109    }
110
111    #[cfg(any(test, feature = "test-helpers"))]
112    pub fn new_without_hash<B>(storage_key: B) -> Self
113    where
114        B: Into<Bytes32>,
115    {
116        unsafe { Self::convert(storage_key) }
117    }
118}
119
120impl Debug for MerkleTreeKey {
121    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
122        f.write_str(&format!("MerkleTreeKey({})", hex::encode(self.0)))
123    }
124}
125
126impl From<MerkleTreeKey> for Bytes32 {
127    fn from(value: MerkleTreeKey) -> Self {
128        value.0
129    }
130}
131
132impl AsRef<[u8]> for MerkleTreeKey {
133    fn as_ref(&self) -> &[u8] {
134        self.0.as_ref()
135    }
136}
137
138impl AsRef<Bytes32> for MerkleTreeKey {
139    fn as_ref(&self) -> &Bytes32 {
140        &self.0
141    }
142}
143
144impl Deref for MerkleTreeKey {
145    type Target = Bytes32;
146
147    fn deref(&self) -> &Self::Target {
148        &self.0
149    }
150}
151
152#[cfg(any(test, feature = "test-helpers"))]
153impl From<Bytes32> for MerkleTreeKey {
154    fn from(value: Bytes32) -> Self {
155        Self::new_without_hash(value)
156    }
157}
158
159#[derive(Debug)]
160pub struct MerkleTree<TableType, StorageType> {
161    root_node: Node,
162    storage: StorageType,
163    phantom_table: PhantomData<TableType>,
164}
165
166impl<TableType, StorageType> MerkleTree<TableType, StorageType> {
167    pub const fn empty_root() -> &'static Bytes32 {
168        empty_sum()
169    }
170
171    pub fn root(&self) -> Bytes32 {
172        *self.root_node().hash()
173    }
174
175    pub fn into_storage(self) -> StorageType {
176        self.storage
177    }
178
179    pub fn storage(&self) -> &StorageType {
180        &self.storage
181    }
182
183    fn root_node(&self) -> &Node {
184        &self.root_node
185    }
186
187    fn set_root_node(&mut self, node: Node) {
188        debug_assert!(node.is_leaf() || node.height() == Node::max_height());
189        self.root_node = node;
190    }
191}
192
193impl<TableType, StorageType, StorageError> MerkleTree<TableType, StorageType>
194where
195    TableType: Mappable<Key = Bytes32, Value = Primitive, OwnedValue = Primitive>,
196    StorageType: StorageInspect<TableType, Error = StorageError>,
197{
198    pub fn new(storage: StorageType) -> Self {
199        Self {
200            root_node: Node::create_placeholder(),
201            storage,
202            phantom_table: Default::default(),
203        }
204    }
205
206    pub fn load(
207        storage: StorageType,
208        root: &Bytes32,
209    ) -> Result<Self, MerkleTreeError<StorageError>> {
210        if root == Self::empty_root() {
211            let tree = Self::new(storage);
212            Ok(tree)
213        } else {
214            let primitive = storage
215                .get(root)?
216                .ok_or_else(|| MerkleTreeError::LoadError(*root))?
217                .into_owned();
218            let tree = Self {
219                root_node: primitive
220                    .try_into()
221                    .map_err(MerkleTreeError::DeserializeError)?,
222                storage,
223                phantom_table: Default::default(),
224            };
225            Ok(tree)
226        }
227    }
228
229    fn path_set(
230        &self,
231        leaf_key: &Bytes32,
232    ) -> Result<(Vec<Node>, Vec<Bytes32>), MerkleTreeError<StorageError>> {
233        let root_node = self.root_node().clone();
234        let root_storage_node = StorageNode::new(&self.storage, root_node);
235        let (mut path_nodes, mut side_nodes): (Vec<Node>, Vec<Bytes32>) =
236            root_storage_node
237                .as_path_iter(leaf_key)
238                .map(|(path_node, side_node)| {
239                    Ok((
240                        path_node.map_err(MerkleTreeError::ChildError)?.into_node(),
241                        side_node.map_err(MerkleTreeError::ChildError)?,
242                    ))
243                })
244                .collect::<Result<Vec<_>, MerkleTreeError<StorageError>>>()?
245                .into_iter()
246                .unzip();
247        path_nodes.reverse();
248        side_nodes.reverse();
249        side_nodes.pop(); // The last element in the side nodes list is the
250                          // root; remove it.
251
252        Ok((path_nodes, side_nodes))
253    }
254}
255
256impl<TableType, StorageType, StorageError> MerkleTree<TableType, StorageType>
257where
258    TableType: Mappable<Key = Bytes32, Value = Primitive, OwnedValue = Primitive>,
259    StorageType: StorageMutate<TableType, Error = StorageError>,
260{
261    /// Build a sparse Merkle tree from a set of key-value pairs. This is
262    /// equivalent to creating an empty sparse Merkle tree and sequentially
263    /// calling [update](Self::update) for each key-value pair. This constructor
264    /// is more performant than calling individual sequential updates and is the
265    /// preferred approach when the key-values are known upfront. Leaves can be
266    /// appended to the returned tree using `update` to further accumulate leaf
267    /// data.
268    pub fn from_set<B, I, D>(
269        mut storage: StorageType,
270        set: I,
271    ) -> Result<Self, StorageError>
272    where
273        I: Iterator<Item = (B, D)>,
274        B: Into<Bytes32>,
275        D: AsRef<[u8]>,
276    {
277        let sorted = set
278            .into_iter()
279            .map(|(k, v)| (k.into(), v))
280            .collect::<alloc::collections::BTreeMap<Bytes32, D>>();
281        let mut branches = sorted
282            .iter()
283            .filter(|(_, value)| !value.as_ref().is_empty())
284            .map(|(key, data)| Node::create_leaf(key, data))
285            .map(Into::<Branch>::into)
286            .collect::<Vec<_>>();
287
288        for branch in branches.iter() {
289            let leaf = &branch.node;
290            storage.insert(leaf.hash(), &leaf.as_ref().into())?;
291        }
292
293        if branches.is_empty() {
294            let tree = Self::new(storage);
295            return Ok(tree)
296        }
297
298        if branches.len() == 1 {
299            let leaf = branches.pop().expect("Expected at least 1 leaf").node;
300            let mut tree = Self::new(storage);
301            tree.set_root_node(leaf);
302            return Ok(tree)
303        }
304
305        let mut nodes = Vec::<Branch>::with_capacity(branches.len());
306        let mut proximities = Vec::<u32>::with_capacity(branches.len());
307
308        // Building the tree starts by merging all leaf nodes where possible.
309        // Given a set of leaf nodes sorted left to right (i.e., keys are sorted
310        // in lexical order), we scan the leaf set right to left, and analyze a
311        // moving window of three leaves: a center (or "current") leaf, its left
312        // neighbor, and its right neighbor.
313        //
314        // When merging leaf nodes, we analyze this three-node window to
315        // determine if the condition for merging is met: When the current node
316        // is closer to its right neighbor than it is to its left neighbor, we
317        // merge the current node with its right neighbor. The merged node then
318        // becomes the center of the window, and we must check the merge
319        // condition again. We calculate proximity using the common path length
320        // between two nodes, which is also the depth of their shared ancestor
321        // in the tree.
322        //
323        // This three-node window is centered around a current node, and moves
324        // leftward: At the next iteration, the current node is now the right
325        // node, the left node is now the current node, and so on. When we have
326        // checked all windows, we know that we have merged all leaf nodes where
327        // possible.
328        while let Some(left) = branches.pop() {
329            if let Some(current) = nodes.last() {
330                #[allow(clippy::cast_possible_truncation)] // Key is 32 bytes
331                let left_proximity = current.node.common_path_length(&left.node) as u32;
332                while {
333                    // The current node's proximity to its right neighbor was
334                    // stored previously. We now compare the distances between
335                    // the current node's left and right neighbors. If, and only
336                    // if, the current node is closer to its right neighbor, we
337                    // merge these nodes to form an ancestor node. We then
338                    // reform the window, using the ancestor node in the center,
339                    // to check if we must merge again.
340                    //
341                    // If the current node is closer to its left, we do not have
342                    // enough information to merge nodes, and we must continue
343                    // scanning the leaf set leftwards to find a configuration
344                    // that satisfies the merge condition.
345                    if let Some(right_proximity) = proximities.last() {
346                        *right_proximity > left_proximity
347                    } else {
348                        false
349                    }
350                } {
351                    // The current node is closer to its right neighbor than its
352                    // left neighbor. We now merge the current node with its
353                    // right neighbor.
354                    let current =
355                        nodes.pop().expect("Expected current node to be present");
356                    let right = nodes.pop().expect("Expected right node to be present");
357                    let merged = merge_branches(&mut storage, current, right)?;
358                    nodes.push(merged);
359
360                    // Now that the current node and its right neighbour are
361                    // merged, the distance between them has collapsed and their
362                    // proximity is no longer needed.
363                    proximities.pop();
364                }
365                proximities.push(left_proximity);
366            }
367            nodes.push(left);
368        }
369
370        // Where possible, all the leaves have been merged. The remaining leaves
371        // and nodes are stacked in order of height descending. This means that
372        // they are also ordered with the leftmost leaves at the top and the
373        // rightmost nodes at the bottom. We can iterate through the stack and
374        // merge them left to right.
375        let top = {
376            let mut node = nodes
377                .pop()
378                .expect("Nodes stack must have at least 1 element");
379            while let Some(next) = nodes.pop() {
380                node = merge_branches(&mut storage, node, next)?;
381            }
382            node
383        };
384
385        // Lastly, all leaves and nodes are merged into one. The resulting node
386        // may still be an ancestor node below the root. To calculate the final
387        // root, we merge placeholder nodes along the path until the resulting
388        // node has the final height and forms the root node.
389        let mut node = top.node;
390        let path = top.bits;
391        let height = node.height();
392        #[allow(clippy::arithmetic_side_effects)] // height <= max_height
393        let depth = Node::max_height() - height;
394        let placeholders = iter::repeat(Node::create_placeholder()).take(depth as usize);
395        for placeholder in placeholders {
396            node = Node::create_node_on_path(&path, &node, &placeholder);
397            storage.insert(node.hash(), &node.as_ref().into())?;
398        }
399
400        let tree = Self {
401            root_node: node,
402            storage,
403            phantom_table: Default::default(),
404        };
405        Ok(tree)
406    }
407
408    pub fn update(
409        &mut self,
410        key: MerkleTreeKey,
411        data: &[u8],
412    ) -> Result<(), MerkleTreeError<StorageError>> {
413        if data.is_empty() {
414            // If the data is empty, this signifies a delete operation for the
415            // given key.
416            self.delete(key)?;
417            return Ok(())
418        }
419
420        let leaf_node = Node::create_leaf(key.as_ref(), data);
421        self.storage
422            .insert(leaf_node.hash(), &leaf_node.as_ref().into())?;
423
424        if self.root_node().is_placeholder() {
425            self.set_root_node(leaf_node);
426        } else {
427            let (path_nodes, side_nodes) = self.path_set(key.as_ref())?;
428            self.update_with_path_set(
429                &leaf_node,
430                path_nodes.as_slice(),
431                side_nodes.as_slice(),
432            )?;
433        }
434
435        Ok(())
436    }
437
438    pub fn delete(
439        &mut self,
440        key: MerkleTreeKey,
441    ) -> Result<(), MerkleTreeError<StorageError>> {
442        if self.root() == *Self::empty_root() {
443            // The zero root signifies that all leaves are empty, including the
444            // given key.
445            return Ok(())
446        }
447
448        let (path_nodes, side_nodes): (Vec<Node>, Vec<_>) =
449            self.path_set(key.as_ref())?;
450
451        match path_nodes.first() {
452            Some(node) if *node.leaf_key() == key.as_ref() => {
453                self.delete_with_path_set(path_nodes.as_slice(), side_nodes.as_slice())?;
454            }
455            _ => {}
456        };
457
458        Ok(())
459    }
460
461    fn update_with_path_set(
462        &mut self,
463        requested_leaf_node: &Node,
464        path_nodes: &[Node],
465        side_nodes: &[Bytes32],
466    ) -> Result<(), StorageError> {
467        let path = requested_leaf_node.leaf_key();
468        let actual_leaf_node = &path_nodes[0];
469
470        if requested_leaf_node == actual_leaf_node {
471            return Ok(())
472        }
473
474        // Build the tree upwards starting with the requested leaf node.
475        let mut current_node = requested_leaf_node.clone();
476
477        // If we are creating a new leaf node, the corresponding side node will
478        // be the first node in the path set. The side node will be the leaf
479        // node currently closest to the requested new leaf node. When creating
480        // a new leaf node, we must merge the leaf node with its corresponding
481        // side node to create a common ancestor. We then continue building the
482        // tree upwards from this ancestor node. This may require creating new
483        // placeholder side nodes, in addition to the existing side node set.
484        //
485        // If we are updating an existing leaf node, the leaf node we are
486        // updating is the first node in the path set. The side node set will
487        // already include all the side nodes needed to build up the tree from
488        // the requested leaf node, since these side nodes were already built
489        // during the creation of the leaf node.
490        //
491        // We can determine if we are updating an existing leaf node, or if we
492        // are creating a new leaf node, by comparing the paths of the requested
493        // leaf node and the leaf node at the start of the path set. When the
494        // paths are equal, it means the leaf nodes occupy the same location,
495        // and we are updating an existing leaf. Otherwise, it means we are
496        // adding a new leaf node.
497        if requested_leaf_node.leaf_key() != actual_leaf_node.leaf_key() {
498            // Merge leaves
499            if !actual_leaf_node.is_placeholder() {
500                current_node =
501                    Node::create_node_on_path(path, &current_node, actual_leaf_node);
502                self.storage
503                    .insert(current_node.hash(), &current_node.as_ref().into())?;
504            }
505
506            // Merge placeholders
507            let ancestor_depth = requested_leaf_node.common_path_length(actual_leaf_node);
508            #[allow(clippy::cast_possible_truncation)] // Key is 32 bytes
509            let placeholders_count =
510                (ancestor_depth as usize).saturating_sub(side_nodes.len());
511            let placeholders =
512                iter::repeat(Node::create_placeholder()).take(placeholders_count);
513            for placeholder in placeholders {
514                current_node =
515                    Node::create_node_on_path(path, &current_node, &placeholder);
516                self.storage
517                    .insert(current_node.hash(), &current_node.as_ref().into())?;
518            }
519        } else {
520            self.storage.remove(actual_leaf_node.hash())?;
521        }
522
523        // Merge side nodes
524        for (side_node, old_parent) in
525            side_nodes.iter().zip(path_nodes.iter().skip(1 /* leaf */))
526        {
527            let new_parent = if old_parent.bytes_lo() == side_node {
528                Node::create_node_from_hashes(
529                    *side_node,
530                    *current_node.hash(),
531                    old_parent.height(),
532                )
533            } else {
534                Node::create_node_from_hashes(
535                    *current_node.hash(),
536                    *side_node,
537                    old_parent.height(),
538                )
539            };
540
541            current_node = new_parent;
542            self.storage
543                .insert(current_node.hash(), &current_node.as_ref().into())?;
544            self.storage.remove(old_parent.hash())?;
545        }
546
547        self.set_root_node(current_node);
548
549        Ok(())
550    }
551
552    fn delete_with_path_set(
553        &mut self,
554        path_nodes: &[Node],
555        side_nodes: &[Bytes32],
556    ) -> Result<(), MerkleTreeError<StorageError>> {
557        for node in path_nodes {
558            self.storage.remove(node.hash())?;
559        }
560
561        let mut side_nodes_iter = side_nodes.iter();
562        let mut path_nodes_iter = path_nodes.iter();
563        path_nodes_iter.next(); // Skip the requested leaf node
564
565        // The deleted leaf is replaced by a placeholder. Build the tree upwards
566        // starting with the placeholder.
567        let mut current_node = Node::create_placeholder();
568
569        // If the first side node is a leaf, it means the ancestor node is now
570        // parent to a placeholder (the deleted leaf node) and a leaf node (the
571        // first side node). We can immediately discard the ancestor node from
572        // further calculation and attach the orphaned leaf node to its next
573        // ancestor. Any subsequent ancestor nodes composed of this leaf node
574        // and a placeholder must be similarly discarded from further
575        // calculation. We then create a valid ancestor node for the orphaned
576        // leaf node by joining it with the earliest non-placeholder side node.
577        if let Some(first_side_node) = side_nodes.first() {
578            let first_side_node: Node = self
579                .storage
580                .get(first_side_node)?
581                .ok_or(MerkleTreeError::LoadError(*first_side_node))?
582                .into_owned()
583                .try_into()
584                .map_err(MerkleTreeError::DeserializeError)?;
585
586            if first_side_node.is_leaf() {
587                side_nodes_iter.next();
588                current_node = first_side_node.clone();
589
590                // Advance the side node iterator to the next non-placeholder
591                // node. This may be either another leaf node or an internal
592                // node. If only placeholder nodes exist beyond the first leaf
593                // node, then that leaf node is, in fact, the new root node.
594                //
595                // Using `find(..)` advances the iterator beyond the next
596                // non-placeholder side node and returns it. Therefore, we must
597                // consume the side node at this point. If another non-
598                // placeholder node was found in the side node collection, merge
599                // it with the first side node. This guarantees that the current
600                // node will be an internal node, and not a leaf, by the time we
601                // start merging the remaining side nodes.
602                // See https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.find.
603                if let Some(side_node) = side_nodes_iter
604                    .find(|side_node| *side_node != Node::Placeholder.hash())
605                {
606                    // Skip parents until the parent of the first side node is found
607                    if let Some(old_parent) = path_nodes_iter.find(|parent| {
608                        parent.bytes_lo() == side_node || parent.bytes_hi() == side_node
609                    }) {
610                        let new_parent = if old_parent.bytes_lo() == side_node {
611                            Node::create_node_from_hashes(
612                                *side_node,
613                                *current_node.hash(),
614                                old_parent.height(),
615                            )
616                        } else {
617                            Node::create_node_from_hashes(
618                                *current_node.hash(),
619                                *side_node,
620                                old_parent.height(),
621                            )
622                        };
623                        current_node = new_parent;
624                        self.storage
625                            .insert(current_node.hash(), &current_node.as_ref().into())?;
626                    }
627                }
628            }
629        }
630
631        // Merge side nodes
632        for (side_node, old_parent) in side_nodes_iter.zip(path_nodes_iter) {
633            let new_parent = if old_parent.bytes_lo() == side_node {
634                Node::create_node_from_hashes(
635                    *side_node,
636                    *current_node.hash(),
637                    old_parent.height(),
638                )
639            } else {
640                Node::create_node_from_hashes(
641                    *current_node.hash(),
642                    *side_node,
643                    old_parent.height(),
644                )
645            };
646
647            current_node = new_parent;
648            self.storage
649                .insert(current_node.hash(), &current_node.as_ref().into())?;
650        }
651
652        self.set_root_node(current_node);
653
654        Ok(())
655    }
656}
657
658impl<TableType, StorageType, StorageError> MerkleTree<TableType, StorageType>
659where
660    TableType: Mappable<Key = Bytes32, Value = Primitive, OwnedValue = Primitive>,
661    StorageType: StorageInspect<TableType, Error = StorageError>,
662{
663    pub fn generate_proof(
664        &self,
665        key: &MerkleTreeKey,
666    ) -> Result<Proof, MerkleTreeError<StorageError>> {
667        let path = key.as_ref();
668        let (path_nodes, side_nodes) = self.path_set(path)?;
669        // Identify the closest leaf that is included in the tree to the
670        // requested leaf. The closest leaf, as returned by the path set
671        // corresponding to the requested leaf, will be the requested leaf
672        // itself, a different leaf than requested, or a placeholder.
673        //
674        // If the closest leaf is the requested leaf, then the requested leaf is
675        // included in the tree, and we are requesting an inclusion proof.
676        // Otherwise (i.e, the closest leaf is either another leaf or a
677        // placeholder), the requested leaf is not in the tree, and we are
678        // requesting an exclusion proof.
679        //
680        let actual_leaf = &path_nodes[0];
681        let proof_set = side_nodes;
682        let proof = if !actual_leaf.is_placeholder() && actual_leaf.leaf_key() == path {
683            // If the requested key is part of the tree, build an inclusion
684            // proof.
685            let inclusion_proof = InclusionProof { proof_set };
686            Proof::Inclusion(inclusion_proof)
687        } else {
688            // If the requested key is not part of the tree, we are verifying
689            // that the given key is a placeholder, and we must build an
690            // exclusion proof. When building an exclusion proof, the requested
691            // leaf is unset and is currently a placeholder. The path to this
692            // placeholder is designated by the requested leaf's key.
693            //
694            // If the closest leaf is a real leaf, and not a placeholder, we can
695            // build the root upwards using this leaf's key and value. If the
696            // closest leaf is a placeholder, it has a leaf key and a
697            // placeholder value (the zero sum). The leaf key of this
698            // placeholder leaf is unknown (since placeholders do not store
699            // their leaf key), and by extension, the path from the root to the
700            // placeholder is also unknown.
701            //
702            // However, in both cases, the path defined by the requested
703            // placeholder is sufficiently close: All branches stemming from the
704            // point where the paths of the requested placeholder and closest
705            // leaf diverge are saturated with the closest leaf's hash. In the
706            // case where the closest leaf is a placeholder, this hash is simply
707            // the zero sum. The hash of any placeholder under this point of
708            // divergence equates to this hash.
709            //
710            let leaf = if actual_leaf.is_placeholder() {
711                ExclusionLeaf::Placeholder
712            } else {
713                ExclusionLeaf::Leaf(ExclusionLeafData {
714                    leaf_key: *actual_leaf.leaf_key(),
715                    leaf_value: *actual_leaf.leaf_data(),
716                })
717            };
718
719            let exclusion_proof = ExclusionProof { proof_set, leaf };
720            Proof::Exclusion(exclusion_proof)
721        };
722        Ok(proof)
723    }
724}
725
726#[cfg(test)]
727#[allow(non_snake_case)]
728mod test {
729    use super::Node;
730    use crate::{
731        common::{
732            sum,
733            Bytes32,
734            StorageMap,
735        },
736        sparse::{
737            empty_sum,
738            MerkleTree,
739            MerkleTreeError,
740            MerkleTreeKey,
741            Primitive,
742        },
743    };
744    use fuel_storage::Mappable;
745    use hex;
746
747    fn random_bytes32<R>(rng: &mut R) -> Bytes32
748    where
749        R: rand::Rng + ?Sized,
750    {
751        let mut bytes = [0u8; 32];
752        rng.fill(bytes.as_mut());
753        bytes
754    }
755
756    #[derive(Debug)]
757    struct TestTable;
758
759    impl Mappable for TestTable {
760        type Key = Self::OwnedKey;
761        type OwnedKey = Bytes32;
762        type OwnedValue = Primitive;
763        type Value = Self::OwnedValue;
764    }
765
766    fn key<B: AsRef<[u8]>>(data: B) -> MerkleTreeKey {
767        MerkleTreeKey::new(data.as_ref())
768    }
769
770    #[test]
771    fn test_empty_root() {
772        let mut storage = StorageMap::<TestTable>::new();
773        let tree = MerkleTree::new(&mut storage);
774        let root = tree.root();
775        let expected_root =
776            "0000000000000000000000000000000000000000000000000000000000000000";
777        assert_eq!(hex::encode(root), expected_root);
778    }
779
780    #[test]
781    fn test_update_1() {
782        let mut storage = StorageMap::<TestTable>::new();
783        let mut tree = MerkleTree::new(&mut storage);
784
785        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
786
787        let root = tree.root();
788        let expected_root =
789            "39f36a7cb4dfb1b46f03d044265df6a491dffc1034121bc1071a34ddce9bb14b";
790        assert_eq!(hex::encode(root), expected_root);
791    }
792
793    #[test]
794    fn test_update_2() {
795        let mut storage = StorageMap::<TestTable>::new();
796        let mut tree = MerkleTree::new(&mut storage);
797
798        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
799        tree.update(key(b"\x00\x00\x00\x01"), b"DATA").unwrap();
800
801        let root = tree.root();
802        let expected_root =
803            "8d0ae412ca9ca0afcb3217af8bcd5a673e798bd6fd1dfacad17711e883f494cb";
804        assert_eq!(hex::encode(root), expected_root);
805    }
806
807    #[test]
808    fn test_update_3() {
809        let mut storage = StorageMap::<TestTable>::new();
810        let mut tree = MerkleTree::new(&mut storage);
811
812        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
813        tree.update(key(b"\x00\x00\x00\x01"), b"DATA").unwrap();
814        tree.update(key(b"\x00\x00\x00\x02"), b"DATA").unwrap();
815
816        let root = tree.root();
817        let expected_root =
818            "52295e42d8de2505fdc0cc825ff9fead419cbcf540d8b30c7c4b9c9b94c268b7";
819        assert_eq!(hex::encode(root), expected_root);
820    }
821
822    #[test]
823    fn test_update_5() {
824        let mut storage = StorageMap::<TestTable>::new();
825        let mut tree = MerkleTree::new(&mut storage);
826
827        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
828        tree.update(key(b"\x00\x00\x00\x01"), b"DATA").unwrap();
829        tree.update(key(b"\x00\x00\x00\x02"), b"DATA").unwrap();
830        tree.update(key(b"\x00\x00\x00\x03"), b"DATA").unwrap();
831        tree.update(key(b"\x00\x00\x00\x04"), b"DATA").unwrap();
832
833        let root = tree.root();
834        let expected_root =
835            "108f731f2414e33ae57e584dc26bd276db07874436b2264ca6e520c658185c6b";
836        assert_eq!(hex::encode(root), expected_root);
837    }
838
839    #[test]
840    fn test_update_10() {
841        let mut storage = StorageMap::<TestTable>::new();
842        let mut tree = MerkleTree::new(&mut storage);
843
844        for i in 0_u32..10 {
845            let key = key(i.to_be_bytes());
846            tree.update(key, b"DATA").unwrap();
847        }
848
849        let root = tree.root();
850        let expected_root =
851            "21ca4917e99da99a61de93deaf88c400d4c082991cb95779e444d43dd13e8849";
852        assert_eq!(hex::encode(root), expected_root);
853    }
854
855    #[test]
856    fn test_update_100() {
857        let mut storage = StorageMap::<TestTable>::new();
858        let mut tree = MerkleTree::new(&mut storage);
859
860        for i in 0_u32..100 {
861            let key = key(i.to_be_bytes());
862            tree.update(key, b"DATA").unwrap();
863        }
864
865        let root = tree.root();
866        let expected_root =
867            "82bf747d455a55e2f7044a03536fc43f1f55d43b855e72c0110c986707a23e4d";
868        assert_eq!(hex::encode(root), expected_root);
869    }
870
871    #[test]
872    fn test_update_with_repeated_inputs() {
873        let mut storage = StorageMap::<TestTable>::new();
874        let mut tree = MerkleTree::new(&mut storage);
875
876        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
877        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
878
879        let root = tree.root();
880        let expected_root =
881            "39f36a7cb4dfb1b46f03d044265df6a491dffc1034121bc1071a34ddce9bb14b";
882        assert_eq!(hex::encode(root), expected_root);
883    }
884
885    #[test]
886    fn test_update_overwrite_key() {
887        let mut storage = StorageMap::<TestTable>::new();
888        let mut tree = MerkleTree::new(&mut storage);
889
890        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
891        tree.update(key(b"\x00\x00\x00\x00"), b"CHANGE").unwrap();
892
893        let root = tree.root();
894        let expected_root =
895            "dd97174c80e5e5aa3a31c61b05e279c1495c8a07b2a08bca5dbc9fb9774f9457";
896        assert_eq!(hex::encode(root), expected_root);
897    }
898
899    #[test]
900    fn test_update_overwrite_key_2() {
901        let mut storage = StorageMap::<TestTable>::new();
902        let mut tree = MerkleTree::new(&mut storage);
903
904        for i in 0_u32..10 {
905            let key = key(i.to_be_bytes());
906            tree.update(key, b"DATA").unwrap();
907        }
908
909        let root_hash_before = tree.root();
910
911        for i in 3_u32..7 {
912            let key = key(i.to_be_bytes());
913            tree.update(key, b"DATA_2").unwrap();
914        }
915
916        for i in 3_u32..7 {
917            let key = key(i.to_be_bytes());
918            tree.update(key, b"DATA").unwrap();
919        }
920
921        let root_hash_after = tree.root();
922
923        assert_eq!(root_hash_before, root_hash_after);
924    }
925
926    #[test]
927    fn test_update_union() {
928        let mut storage = StorageMap::<TestTable>::new();
929        let mut tree = MerkleTree::new(&mut storage);
930
931        for i in 0_u32..5 {
932            let key = key(i.to_be_bytes());
933            tree.update(key, b"DATA").unwrap();
934        }
935
936        for i in 10_u32..15 {
937            let key = key(i.to_be_bytes());
938            tree.update(key, b"DATA").unwrap();
939        }
940
941        for i in 20_u32..25 {
942            let key = key(i.to_be_bytes());
943            tree.update(key, b"DATA").unwrap();
944        }
945
946        let root = tree.root();
947        let expected_root =
948            "7e6643325042cfe0fc76626c043b97062af51c7e9fc56665f12b479034bce326";
949        assert_eq!(hex::encode(root), expected_root);
950    }
951
952    #[test]
953    fn test_update_sparse_union() {
954        let mut storage = StorageMap::<TestTable>::new();
955        let mut tree = MerkleTree::new(&mut storage);
956
957        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
958        tree.update(key(b"\x00\x00\x00\x02"), b"DATA").unwrap();
959        tree.update(key(b"\x00\x00\x00\x04"), b"DATA").unwrap();
960        tree.update(key(b"\x00\x00\x00\x06"), b"DATA").unwrap();
961        tree.update(key(b"\x00\x00\x00\x08"), b"DATA").unwrap();
962
963        let root = tree.root();
964        let expected_root =
965            "e912e97abc67707b2e6027338292943b53d01a7fbd7b244674128c7e468dd696";
966        assert_eq!(hex::encode(root), expected_root);
967    }
968
969    #[test]
970    fn test_update_with_empty_data_does_not_change_root() {
971        let mut storage = StorageMap::<TestTable>::new();
972        let mut tree = MerkleTree::new(&mut storage);
973
974        tree.update(key(b"\x00\x00\x00\x00"), b"").unwrap();
975
976        let root = tree.root();
977        let expected_root =
978            "0000000000000000000000000000000000000000000000000000000000000000";
979        assert_eq!(hex::encode(root), expected_root);
980    }
981
982    #[test]
983    fn test_update_with_empty_data_performs_delete() {
984        let mut storage = StorageMap::<TestTable>::new();
985        let mut tree = MerkleTree::new(&mut storage);
986
987        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
988        tree.update(key(b"\x00\x00\x00\x00"), b"").unwrap();
989
990        let root = tree.root();
991        let expected_root =
992            "0000000000000000000000000000000000000000000000000000000000000000";
993        assert_eq!(hex::encode(root), expected_root);
994    }
995
996    #[test]
997    fn test_update_1_delete_1() {
998        let mut storage = StorageMap::<TestTable>::new();
999        let mut tree = MerkleTree::new(&mut storage);
1000
1001        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
1002        tree.delete(key(b"\x00\x00\x00\x00")).unwrap();
1003
1004        let root = tree.root();
1005        let expected_root =
1006            "0000000000000000000000000000000000000000000000000000000000000000";
1007        assert_eq!(hex::encode(root), expected_root);
1008    }
1009
1010    #[test]
1011    fn test_update_2_delete_1() {
1012        let mut storage = StorageMap::<TestTable>::new();
1013        let mut tree = MerkleTree::new(&mut storage);
1014
1015        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
1016        tree.update(key(b"\x00\x00\x00\x01"), b"DATA").unwrap();
1017        tree.delete(key(b"\x00\x00\x00\x01")).unwrap();
1018
1019        let root = tree.root();
1020        let expected_root =
1021            "39f36a7cb4dfb1b46f03d044265df6a491dffc1034121bc1071a34ddce9bb14b";
1022        assert_eq!(hex::encode(root), expected_root);
1023    }
1024
1025    #[test]
1026    fn test_update_10_delete_5() {
1027        let mut storage = StorageMap::<TestTable>::new();
1028        let mut tree = MerkleTree::new(&mut storage);
1029
1030        for i in 0_u32..10 {
1031            let key = key(i.to_be_bytes());
1032            tree.update(key, b"DATA").unwrap();
1033        }
1034
1035        for i in 5_u32..10 {
1036            let key = key(i.to_be_bytes());
1037            tree.delete(key).unwrap();
1038        }
1039
1040        let root = tree.root();
1041        let expected_root =
1042            "108f731f2414e33ae57e584dc26bd276db07874436b2264ca6e520c658185c6b";
1043        assert_eq!(hex::encode(root), expected_root);
1044    }
1045
1046    #[test]
1047    fn test_delete_non_existent_key() {
1048        let mut storage = StorageMap::<TestTable>::new();
1049        let mut tree = MerkleTree::new(&mut storage);
1050
1051        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
1052        tree.update(key(b"\x00\x00\x00\x01"), b"DATA").unwrap();
1053        tree.update(key(b"\x00\x00\x00\x02"), b"DATA").unwrap();
1054        tree.update(key(b"\x00\x00\x00\x03"), b"DATA").unwrap();
1055        tree.update(key(b"\x00\x00\x00\x04"), b"DATA").unwrap();
1056        tree.delete(key(b"\x00\x00\x04\x00")).unwrap();
1057
1058        let root = tree.root();
1059        let expected_root =
1060            "108f731f2414e33ae57e584dc26bd276db07874436b2264ca6e520c658185c6b";
1061        assert_eq!(hex::encode(root), expected_root);
1062    }
1063
1064    #[test]
1065    fn test_interleaved_update_delete() {
1066        let mut storage = StorageMap::<TestTable>::new();
1067        let mut tree = MerkleTree::new(&mut storage);
1068
1069        for i in 0_u32..10 {
1070            let key = key(i.to_be_bytes());
1071            tree.update(key, b"DATA").unwrap();
1072        }
1073
1074        for i in 5_u32..15 {
1075            let key = key(i.to_be_bytes());
1076            tree.delete(key).unwrap();
1077        }
1078
1079        for i in 10_u32..20 {
1080            let key = key(i.to_be_bytes());
1081            tree.update(key, b"DATA").unwrap();
1082        }
1083
1084        for i in 15_u32..25 {
1085            let key = key(i.to_be_bytes());
1086            tree.delete(key).unwrap();
1087        }
1088
1089        for i in 20_u32..30 {
1090            let key = key(i.to_be_bytes());
1091            tree.update(key, b"DATA").unwrap();
1092        }
1093
1094        for i in 25_u32..35 {
1095            let key = key(i.to_be_bytes());
1096            tree.delete(key).unwrap();
1097        }
1098
1099        let root = tree.root();
1100        let expected_root =
1101            "7e6643325042cfe0fc76626c043b97062af51c7e9fc56665f12b479034bce326";
1102        assert_eq!(hex::encode(root), expected_root);
1103    }
1104
1105    #[test]
1106    fn test_update_removes_old_entries() {
1107        let mut storage = StorageMap::<TestTable>::new();
1108        let mut tree = MerkleTree::new(&mut storage);
1109        let tenth_index = 9u32;
1110
1111        for i in 0_u32..tenth_index {
1112            let key = key(i.to_be_bytes());
1113            tree.update(key, b"DATA").unwrap();
1114        }
1115        let size_before_tenth = tree.storage().len();
1116        let tenth_key = key(tenth_index.to_be_bytes());
1117
1118        // Given
1119        tree.update(tenth_key, b"DATA").unwrap();
1120        let size_after_tenth = tree.storage().len();
1121        assert_ne!(size_after_tenth, size_before_tenth);
1122
1123        // When
1124        tree.update(tenth_key, b"ANOTHER_DATA").unwrap();
1125
1126        // Then
1127        assert_eq!(tree.storage().len(), size_after_tenth);
1128    }
1129
1130    #[test]
1131    fn test_update_with_the_same_value_does_not_remove_old_entries() {
1132        let mut storage = StorageMap::<TestTable>::new();
1133        let mut tree = MerkleTree::new(&mut storage);
1134        let tenth_index = 9u32;
1135
1136        for i in 0_u32..tenth_index {
1137            let key = key(i.to_be_bytes());
1138            tree.update(key, b"DATA").unwrap();
1139        }
1140        let size_before_tenth = tree.storage().len();
1141        let tenth_key = key(tenth_index.to_be_bytes());
1142
1143        // Given
1144        tree.update(tenth_key, b"DATA").unwrap();
1145        let size_after_tenth = tree.storage().len();
1146        assert_ne!(size_after_tenth, size_before_tenth);
1147
1148        // When
1149        tree.update(tenth_key, b"DATA").unwrap();
1150
1151        // Then
1152        assert_eq!(tree.storage().len(), size_after_tenth);
1153    }
1154
1155    #[test]
1156    fn test_delete_removes_path_entries() {
1157        let mut storage = StorageMap::<TestTable>::new();
1158        let mut tree = MerkleTree::new(&mut storage);
1159        let tenth_index = 9u32;
1160
1161        for i in 0_u32..tenth_index {
1162            let key = key(i.to_be_bytes());
1163            tree.update(key, b"DATA").unwrap();
1164        }
1165        let size_before_tenth = tree.storage().len();
1166        let tenth_key = key(tenth_index.to_be_bytes());
1167
1168        // Given
1169        tree.update(tenth_key, b"DATA").unwrap();
1170        let size_after_tenth = tree.storage().len();
1171        assert_ne!(size_after_tenth, size_before_tenth);
1172
1173        // When
1174        tree.delete(tenth_key).unwrap();
1175
1176        // Then
1177        assert_eq!(tree.storage().len(), size_before_tenth);
1178    }
1179
1180    #[test]
1181    fn test_delete_sparse_union() {
1182        let mut storage = StorageMap::<TestTable>::new();
1183        let mut tree = MerkleTree::new(&mut storage);
1184
1185        for i in 0_u32..10 {
1186            let key = key(i.to_be_bytes());
1187            tree.update(key, b"DATA").unwrap();
1188        }
1189
1190        for i in 0_u32..5 {
1191            let key = key((i * 2 + 1).to_be_bytes());
1192            tree.delete(key).unwrap();
1193        }
1194
1195        let root = tree.root();
1196        let expected_root =
1197            "e912e97abc67707b2e6027338292943b53d01a7fbd7b244674128c7e468dd696";
1198        assert_eq!(hex::encode(root), expected_root);
1199    }
1200
1201    #[test]
1202    fn test_override_hash_key() {
1203        use fuel_storage::StorageInspect;
1204        let mut storage = StorageMap::<TestTable>::new();
1205        let mut tree = MerkleTree::new(&mut storage);
1206
1207        let leaf_1_key = key(b"\x00\x00\x00\x00");
1208        let leaf_1_data = b"DATA_1";
1209        let leaf_1 = Node::create_leaf(&leaf_1_key.0, leaf_1_data);
1210
1211        let leaf_2_key = MerkleTreeKey::new_without_hash(*leaf_1.hash());
1212        let leaf_2_data = b"DATA_2";
1213        let leaf_2 = Node::create_leaf(&leaf_2_key.0, leaf_2_data);
1214
1215        tree.update(leaf_2_key, leaf_2_data).unwrap();
1216        tree.update(leaf_1_key, leaf_1_data).unwrap();
1217        assert_eq!(
1218            tree.storage
1219                .get(leaf_2.hash())
1220                .unwrap()
1221                .unwrap()
1222                .into_owned(),
1223            leaf_2.as_ref().into()
1224        );
1225        assert_eq!(
1226            tree.storage
1227                .get(leaf_1.hash())
1228                .unwrap()
1229                .unwrap()
1230                .into_owned(),
1231            leaf_1.as_ref().into()
1232        );
1233    }
1234
1235    #[test]
1236    fn test_load_returns_a_valid_tree() {
1237        // Instantiate a new key-value storage backing and populate it using a sparse
1238        // Merkle tree. The root of the Merkle tree is the key that maps to the buffer
1239        // of the root node in the storage. When loading a Merkle tree from storage, we
1240        // need a reference to the storage object, as well as the root that allows us to
1241        // look up the buffer of the root node. We will later use this storage backing
1242        // and root to load a Merkle tree.
1243        let (mut storage_to_load, root_to_load) = {
1244            let mut storage = StorageMap::<TestTable>::new();
1245            let mut tree = MerkleTree::new(&mut storage);
1246            tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
1247            tree.update(key(b"\x00\x00\x00\x01"), b"DATA").unwrap();
1248            tree.update(key(b"\x00\x00\x00\x02"), b"DATA").unwrap();
1249            tree.update(key(b"\x00\x00\x00\x03"), b"DATA").unwrap();
1250            tree.update(key(b"\x00\x00\x00\x04"), b"DATA").unwrap();
1251            let root = tree.root();
1252            (storage, root)
1253        };
1254
1255        // Generate an expected root for this test by using both the set of `update`
1256        // data used when generating the loadable storage above and an additional set of
1257        // `update` data.
1258        let expected_root = {
1259            let mut storage = StorageMap::<TestTable>::new();
1260            let mut tree = MerkleTree::new(&mut storage);
1261            tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
1262            tree.update(key(b"\x00\x00\x00\x01"), b"DATA").unwrap();
1263            tree.update(key(b"\x00\x00\x00\x02"), b"DATA").unwrap();
1264            tree.update(key(b"\x00\x00\x00\x03"), b"DATA").unwrap();
1265            tree.update(key(b"\x00\x00\x00\x04"), b"DATA").unwrap();
1266            tree.update(key(b"\x00\x00\x00\x05"), b"DATA").unwrap();
1267            tree.update(key(b"\x00\x00\x00\x06"), b"DATA").unwrap();
1268            tree.update(key(b"\x00\x00\x00\x07"), b"DATA").unwrap();
1269            tree.update(key(b"\x00\x00\x00\x08"), b"DATA").unwrap();
1270            tree.update(key(b"\x00\x00\x00\x09"), b"DATA").unwrap();
1271            tree.root()
1272        };
1273
1274        let root = {
1275            // Create a Merkle tree by loading the generated storage and root.
1276            let mut tree = MerkleTree::load(&mut storage_to_load, &root_to_load).unwrap();
1277            // Build up the loaded tree using the additional set of `update` data so its
1278            // root matches the expected root. This verifies that the loaded tree has
1279            // successfully wrapped the given storage backing and assumed the correct
1280            // state so that future updates can be made seamlessly.
1281            tree.update(key(b"\x00\x00\x00\x05"), b"DATA").unwrap();
1282            tree.update(key(b"\x00\x00\x00\x06"), b"DATA").unwrap();
1283            tree.update(key(b"\x00\x00\x00\x07"), b"DATA").unwrap();
1284            tree.update(key(b"\x00\x00\x00\x08"), b"DATA").unwrap();
1285            tree.update(key(b"\x00\x00\x00\x09"), b"DATA").unwrap();
1286            tree.root()
1287        };
1288
1289        assert_eq!(root, expected_root);
1290    }
1291
1292    #[test]
1293    fn test_load_returns_an_empty_tree_for_empty_sum_root() {
1294        let mut storage = StorageMap::<TestTable>::new();
1295        let tree = MerkleTree::load(&mut storage, empty_sum()).unwrap();
1296        let root = tree.root();
1297
1298        assert_eq!(root, *empty_sum());
1299    }
1300
1301    #[test]
1302    fn test_load_returns_a_load_error_if_the_storage_is_not_valid_for_the_root() {
1303        let mut storage = StorageMap::<TestTable>::new();
1304
1305        {
1306            let mut tree = MerkleTree::new(&mut storage);
1307            tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
1308            tree.update(key(b"\x00\x00\x00\x01"), b"DATA").unwrap();
1309            tree.update(key(b"\x00\x00\x00\x02"), b"DATA").unwrap();
1310            tree.update(key(b"\x00\x00\x00\x03"), b"DATA").unwrap();
1311            tree.update(key(b"\x00\x00\x00\x04"), b"DATA").unwrap();
1312        }
1313
1314        let root = &sum(b"\xff\xff\xff\xff");
1315        let err = MerkleTree::load(&mut storage, root)
1316            .expect_err("Expected load() to return Error; got Ok");
1317        assert!(matches!(err, MerkleTreeError::LoadError(_)));
1318    }
1319
1320    #[test]
1321    fn test_load_returns_a_deserialize_error_if_the_storage_is_corrupted() {
1322        use fuel_storage::StorageMutate;
1323
1324        let mut storage = StorageMap::<TestTable>::new();
1325
1326        let mut tree = MerkleTree::new(&mut storage);
1327        tree.update(key(b"\x00\x00\x00\x00"), b"DATA").unwrap();
1328        tree.update(key(b"\x00\x00\x00\x01"), b"DATA").unwrap();
1329        tree.update(key(b"\x00\x00\x00\x02"), b"DATA").unwrap();
1330        tree.update(key(b"\x00\x00\x00\x03"), b"DATA").unwrap();
1331        tree.update(key(b"\x00\x00\x00\x04"), b"DATA").unwrap();
1332        let root = tree.root();
1333
1334        // Overwrite the root key-value with an invalid primitive to create a
1335        // DeserializeError.
1336        let primitive = (0xff, 0xff, [0xff; 32], [0xff; 32]);
1337        storage.insert(&root, &primitive).unwrap();
1338
1339        let err = MerkleTree::load(&mut storage, &root)
1340            .expect_err("Expected load() to return Error; got Ok");
1341        assert!(matches!(err, MerkleTreeError::DeserializeError(_)));
1342    }
1343
1344    #[test]
1345    fn test_from_set_yields_expected_root() {
1346        let rng = &mut rand::thread_rng();
1347        let gen = || {
1348            Some((
1349                MerkleTreeKey::new_without_hash(random_bytes32(rng)),
1350                random_bytes32(rng),
1351            ))
1352        };
1353        let data = std::iter::from_fn(gen).take(1_000).collect::<Vec<_>>();
1354
1355        let expected_root = {
1356            let mut storage = StorageMap::<TestTable>::new();
1357            let mut tree = MerkleTree::new(&mut storage);
1358            let input = data.clone();
1359            for (key, value) in input.into_iter() {
1360                tree.update(key, &value).unwrap();
1361            }
1362            tree.root()
1363        };
1364
1365        let root = {
1366            let mut storage = StorageMap::<TestTable>::new();
1367            let tree = MerkleTree::from_set(&mut storage, data.into_iter()).unwrap();
1368            tree.root()
1369        };
1370
1371        assert_eq!(root, expected_root);
1372    }
1373
1374    #[test]
1375    fn test_from_empty_set_yields_expected_root() {
1376        let rng = &mut rand::thread_rng();
1377        let gen = || {
1378            Some((
1379                MerkleTreeKey::new_without_hash(random_bytes32(rng)),
1380                random_bytes32(rng),
1381            ))
1382        };
1383        let data = std::iter::from_fn(gen).take(0).collect::<Vec<_>>();
1384
1385        let expected_root = {
1386            let mut storage = StorageMap::<TestTable>::new();
1387            let mut tree = MerkleTree::new(&mut storage);
1388            let input = data.clone();
1389            for (key, value) in input.into_iter() {
1390                tree.update(key, &value).unwrap();
1391            }
1392            tree.root()
1393        };
1394
1395        let root = {
1396            let mut storage = StorageMap::<TestTable>::new();
1397            let tree = MerkleTree::from_set(&mut storage, data.into_iter()).unwrap();
1398            tree.root()
1399        };
1400
1401        assert_eq!(root, expected_root);
1402    }
1403
1404    #[test]
1405    fn test_from_unit_set_yields_expected_root() {
1406        let rng = &mut rand::thread_rng();
1407        let gen = || {
1408            Some((
1409                MerkleTreeKey::new_without_hash(random_bytes32(rng)),
1410                random_bytes32(rng),
1411            ))
1412        };
1413        let data = std::iter::from_fn(gen).take(1).collect::<Vec<_>>();
1414
1415        let expected_root = {
1416            let mut storage = StorageMap::<TestTable>::new();
1417            let mut tree = MerkleTree::new(&mut storage);
1418            let input = data.clone();
1419            for (key, value) in input.into_iter() {
1420                tree.update(key, &value).unwrap();
1421            }
1422            tree.root()
1423        };
1424
1425        let root = {
1426            let mut storage = StorageMap::<TestTable>::new();
1427            let tree = MerkleTree::from_set(&mut storage, data.into_iter()).unwrap();
1428            tree.root()
1429        };
1430
1431        assert_eq!(root, expected_root);
1432    }
1433
1434    #[test]
1435    fn test_from_set_with_duplicate_keys_yields_expected_root() {
1436        let rng = &mut rand::thread_rng();
1437        let keys = [
1438            key(b"\x00\x00\x00\x00"),
1439            key(b"\x00\x00\x00\x01"),
1440            key(b"\x00\x00\x00\x02"),
1441        ];
1442        let data = [
1443            (keys[0], random_bytes32(rng)),
1444            (keys[1], random_bytes32(rng)),
1445            (keys[2], random_bytes32(rng)),
1446            (keys[0], random_bytes32(rng)),
1447            (keys[1], random_bytes32(rng)),
1448            (keys[2], random_bytes32(rng)),
1449        ];
1450
1451        let expected_root = {
1452            let mut storage = StorageMap::<TestTable>::new();
1453            let mut tree = MerkleTree::new(&mut storage);
1454            let input = data;
1455            for (key, value) in input.into_iter() {
1456                tree.update(key, &value).unwrap();
1457            }
1458            tree.root()
1459        };
1460
1461        let root = {
1462            let mut storage = StorageMap::<TestTable>::new();
1463            let tree = MerkleTree::from_set(&mut storage, data.into_iter()).unwrap();
1464            tree.root()
1465        };
1466
1467        assert_eq!(root, expected_root);
1468    }
1469
1470    #[test]
1471    fn test_from_set_with_empty_data_yields_expected_root() {
1472        let rng = &mut rand::thread_rng();
1473        let keys = [
1474            key(b"\x00\x00\x00\x00"),
1475            key(b"\x00\x00\x00\x01"),
1476            key(b"\x00\x00\x00\x02"),
1477        ];
1478        let data = [
1479            (keys[0], random_bytes32(rng).to_vec()),
1480            (keys[1], random_bytes32(rng).to_vec()),
1481            (keys[2], random_bytes32(rng).to_vec()),
1482            (keys[0], b"".to_vec()),
1483            (keys[1], b"".to_vec()),
1484            (keys[2], b"".to_vec()),
1485        ];
1486
1487        let expected_root = {
1488            let mut storage = StorageMap::<TestTable>::new();
1489            let mut tree = MerkleTree::new(&mut storage);
1490            let input = data.clone();
1491            for (key, value) in input.into_iter() {
1492                tree.update(key, &value).unwrap();
1493            }
1494            tree.root()
1495        };
1496
1497        let root = {
1498            let mut storage = StorageMap::<TestTable>::new();
1499            let tree = MerkleTree::from_set(&mut storage, data.into_iter()).unwrap();
1500            tree.root()
1501        };
1502
1503        assert_eq!(root, expected_root);
1504    }
1505
1506    #[test]
1507    fn merkle_tree__generate_proof__returns_proof_with_proof_set_for_given_key() {
1508        // Given
1509        let mut storage = StorageMap::<TestTable>::new();
1510        let mut tree = MerkleTree::new(&mut storage);
1511
1512        // 256:           N4
1513        //               /  \
1514        // 255:         N3   \
1515        //             /  \   \
1516        // 254:       /   N2   \
1517        //           /   /  \   \
1518        // 253:     /   N1   \   \
1519        //         /   /  \   \   \
1520        // 252:   /   N0   \   \   \
1521        // ...   /   /  \   \   \   \
1522        //   0: L0  L1  L3  P1  L2  P0
1523        //      K0  K1  K3      K2
1524
1525        let k0 = [0u8; 32];
1526        let v0 = sum(b"DATA");
1527        tree.update(MerkleTreeKey::new_without_hash(k0), &v0)
1528            .expect("Expected successful update");
1529
1530        let mut k1 = [0u8; 32];
1531        k1[0] = 0b01000000;
1532        let v1 = sum(b"DATA");
1533        tree.update(MerkleTreeKey::new_without_hash(k1), &v1)
1534            .expect("Expected successful update");
1535
1536        let mut k2 = [0u8; 32];
1537        k2[0] = 0b01100000;
1538        let v2 = sum(b"DATA");
1539        tree.update(MerkleTreeKey::new_without_hash(k2), &v2)
1540            .expect("Expected successful update");
1541
1542        let mut k3 = [0u8; 32];
1543        k3[0] = 0b01001000;
1544        let v3 = sum(b"DATA");
1545        tree.update(MerkleTreeKey::new_without_hash(k3), &v3)
1546            .expect("Expected successful update");
1547
1548        let l0 = Node::create_leaf(&k0, v0);
1549        let l1 = Node::create_leaf(&k1, v1);
1550        let l2 = Node::create_leaf(&k2, v2);
1551        let l3 = Node::create_leaf(&k3, v3);
1552        let n0 = Node::create_node(&l1, &l3, 252);
1553        let n1 = Node::create_node(&n0, &Node::create_placeholder(), 253);
1554        let n2 = Node::create_node(&n1, &l2, 254);
1555        let n3 = Node::create_node(&l0, &n2, 255);
1556
1557        {
1558            // When
1559            let proof = tree.generate_proof(&k0.into()).expect("Expected proof");
1560            let expected_proof_set = [*n2.hash(), *Node::create_placeholder().hash()];
1561
1562            // Then
1563            assert_eq!(*proof.proof_set(), expected_proof_set);
1564        }
1565
1566        {
1567            // When
1568            let proof = tree.generate_proof(&k1.into()).expect("Expected proof");
1569            let expected_proof_set = [
1570                *l3.hash(),
1571                *Node::create_placeholder().hash(),
1572                *l2.hash(),
1573                *l0.hash(),
1574                *Node::create_placeholder().hash(),
1575            ];
1576
1577            // Then
1578            assert_eq!(*proof.proof_set(), expected_proof_set);
1579        }
1580
1581        {
1582            // When
1583            let proof = tree.generate_proof(&k2.into()).expect("Expected proof");
1584            let expected_proof_set =
1585                [*n1.hash(), *l0.hash(), *Node::create_placeholder().hash()];
1586
1587            // Then
1588            assert_eq!(*proof.proof_set(), expected_proof_set);
1589        }
1590
1591        {
1592            // When
1593            let proof = tree.generate_proof(&k3.into()).expect("Expected proof");
1594            let expected_proof_set = [
1595                *l1.hash(),
1596                *Node::create_placeholder().hash(),
1597                *l2.hash(),
1598                *l0.hash(),
1599                *Node::create_placeholder().hash(),
1600            ];
1601
1602            // Then
1603            assert_eq!(*proof.proof_set(), expected_proof_set);
1604        }
1605
1606        {
1607            // Test that supplying an arbitrary leaf "outside" the range of
1608            // leaves produces a valid proof set
1609
1610            // When
1611            let key = [255u8; 32];
1612            let proof = tree.generate_proof(&key.into()).expect("Expected proof");
1613            let expected_proof_set = [*n3.hash()];
1614
1615            // Then
1616            assert_eq!(*proof.proof_set(), expected_proof_set);
1617        }
1618    }
1619
1620    #[test]
1621    fn merkle_tree__generate_proof__returns_inclusion_proof_for_included_key() {
1622        // Given
1623        let mut storage = StorageMap::<TestTable>::new();
1624        let mut tree = MerkleTree::new(&mut storage);
1625
1626        // 256:           N4
1627        //               /  \
1628        // 255:         N3   \
1629        //             /  \   \
1630        // 254:       /   N2   \
1631        //           /   /  \   \
1632        // 253:     /   N1   \   \
1633        //         /   /  \   \   \
1634        // 252:   /   N0   \   \   \
1635        // ...   /   /  \   \   \   \
1636        //   0: L0  L1  L3  P1  L2  P0
1637        //      K0  K1  K3      K2
1638
1639        let k0 = [0u8; 32];
1640        let v0 = sum(b"DATA");
1641        tree.update(MerkleTreeKey::new_without_hash(k0), &v0)
1642            .expect("Expected successful update");
1643
1644        let mut k1 = [0u8; 32];
1645        k1[0] = 0b01000000;
1646        let v1 = sum(b"DATA");
1647        tree.update(MerkleTreeKey::new_without_hash(k1), &v1)
1648            .expect("Expected successful update");
1649
1650        let mut k2 = [0u8; 32];
1651        k2[0] = 0b01100000;
1652        let v2 = sum(b"DATA");
1653        tree.update(MerkleTreeKey::new_without_hash(k2), &v2)
1654            .expect("Expected successful update");
1655
1656        let mut k3 = [0u8; 32];
1657        k3[0] = 0b01001000;
1658        let v3 = sum(b"DATA");
1659        tree.update(MerkleTreeKey::new_without_hash(k3), &v3)
1660            .expect("Expected successful update");
1661
1662        // When
1663        let proof = tree.generate_proof(&k1.into()).expect("Expected proof");
1664
1665        // Then
1666        assert!(proof.is_inclusion());
1667    }
1668
1669    #[test]
1670    fn merkle_tree__generate_proof__returns_exclusion_proof_for_excluded_key() {
1671        // Given
1672        let mut storage = StorageMap::<TestTable>::new();
1673        let mut tree = MerkleTree::new(&mut storage);
1674
1675        // 256:           N4
1676        //               /  \
1677        // 255:         N3   \
1678        //             /  \   \
1679        // 254:       /   N2   \
1680        //           /   /  \   \
1681        // 253:     /   N1   \   \
1682        //         /   /  \   \   \
1683        // 252:   /   N0   \   \   \
1684        // ...   /   /  \   \   \   \
1685        //   0: L0  L1  L3  P1  L2  P0
1686        //      K0  K1  K3      K2
1687
1688        let k0 = [0u8; 32];
1689        let v0 = sum(b"DATA");
1690        tree.update(MerkleTreeKey::new_without_hash(k0), &v0)
1691            .expect("Expected successful update");
1692
1693        let mut k1 = [0u8; 32];
1694        k1[0] = 0b01000000;
1695        let v1 = sum(b"DATA");
1696        tree.update(MerkleTreeKey::new_without_hash(k1), &v1)
1697            .expect("Expected successful update");
1698
1699        let mut k2 = [0u8; 32];
1700        k2[0] = 0b01100000;
1701        let v2 = sum(b"DATA");
1702        tree.update(MerkleTreeKey::new_without_hash(k2), &v2)
1703            .expect("Expected successful update");
1704
1705        let mut k3 = [0u8; 32];
1706        k3[0] = 0b01001000;
1707        let v3 = sum(b"DATA");
1708        tree.update(MerkleTreeKey::new_without_hash(k3), &v3)
1709            .expect("Expected successful update");
1710
1711        // When
1712        let key = [255u8; 32];
1713        let proof = tree.generate_proof(&key.into()).expect("Expected proof");
1714
1715        // Then
1716        assert!(proof.is_exclusion());
1717    }
1718}