Skip to main content

midnight_transient_crypto/
merkle_tree.rs

1// This file is part of midnight-ledger.
2// Copyright (C) Midnight Foundation
3// SPDX-License-Identifier: Apache-2.0
4// Licensed under the Apache License, Version 2.0 (the "License");
5// You may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7// http://www.apache.org/licenses/LICENSE-2.0
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14//! Sparse, fixed-depth Merkle trees.
15
16use crate::curve::Fr;
17use crate::hash::{degrade_to_transient, transient_hash};
18use crate::repr::FieldRepr;
19use base_crypto::hash::{HashOutput, persistent_hash};
20use base_crypto::repr::{BinaryHashRepr, MemWrite};
21use derive_where::derive_where;
22use fake::Dummy;
23#[cfg(feature = "proptest")]
24use proptest::arbitrary::Arbitrary;
25#[cfg(feature = "proptest")]
26use proptest_derive::Arbitrary;
27use rand::Rng;
28use rand::distributions::{Distribution, Standard};
29use serde::{Deserialize, Deserializer, Serialize, Serializer, ser::SerializeTuple};
30#[cfg(feature = "proptest")]
31use serialize::NoStrategy;
32use serialize::{Deserializable, Serializable, Tagged, tag_enforcement_test};
33use std::error::Error;
34use std::fmt::{self, Debug, Display, Formatter};
35use std::hash::Hash;
36#[cfg(feature = "proptest")]
37use std::marker::PhantomData;
38use std::ops::{Bound, Deref, RangeBounds, RangeInclusive};
39use storage_core as storage;
40use storage_core::DefaultDB;
41use storage_core::Storable;
42use storage_core::arena::{ArenaKey, Sp};
43use storage_core::db::DB;
44#[cfg(test)]
45use storage_core::db::InMemoryDB;
46use storage_core::storable::Loader;
47
48/// A `Storable` wrapper around `HashOutput`
49#[derive(PartialEq, Eq, PartialOrd, Hash, Clone, Debug, Ord, Serializable)]
50pub struct MerkleTreeHash(HashOutput);
51
52/// A path in a Merkle tree
53#[derive(Debug, Clone, FieldRepr, Serializable)]
54pub struct MerklePath<T> {
55    /// The leaf this path is pointing at. This is the contained element, not its hash!
56    pub leaf: T,
57    /// How to reach the tree root from this leaf.
58    pub path: Vec<MerklePathEntry>,
59}
60
61/// The domain separator used in leaf commitments.
62pub const LEAF_HASH_DOMAIN_SEP: &[u8] = b"mdn:lh";
63
64fn range_sub(range: (Bound<u64>, Bound<u64>), sub: u64) -> Option<(Bound<u64>, Bound<u64>)> {
65    // For the start, if subtraction were to overflow, the start becomes unbounded
66    let start = match range.0 {
67        Bound::Unbounded => Bound::Unbounded,
68        Bound::Included(n) => match n.checked_sub(sub) {
69            Some(m) => Bound::Included(m),
70            None => Bound::Unbounded,
71        },
72        Bound::Excluded(n) => match n.checked_sub(sub) {
73            Some(m) => Bound::Excluded(m),
74            None => Bound::Unbounded,
75        },
76    };
77    // For the end, if subtraction were to overflow, the range is empty
78    // Note that Included/Excluded can be handled the same, it just allows a corner-case where we
79    // return an empty range of Some(..=0) instead of None
80    let end = match range.1 {
81        Bound::Unbounded => Bound::Unbounded,
82        Bound::Included(n) => Bound::Included(n.checked_sub(sub)?),
83        Bound::Excluded(n) => Bound::Excluded(n.checked_sub(sub)?),
84    };
85    if range_empty((start, end)) {
86        None
87    } else {
88        Some((start, end))
89    }
90}
91
92fn range_empty(range: (Bound<u64>, Bound<u64>)) -> bool {
93    if let Some((start, end)) = range_force_inclusive(range) {
94        start > end
95    } else {
96        true
97    }
98}
99
100fn range_force_inclusive(range: (Bound<u64>, Bound<u64>)) -> Option<(u64, u64)> {
101    let inclusive_start = match range.0 {
102        Bound::Unbounded => 0,
103        Bound::Included(n) => n,
104        Bound::Excluded(u64::MAX) => return None,
105        Bound::Excluded(n) => n + 1,
106    };
107    let inclusive_end = match range.1 {
108        Bound::Unbounded => u64::MAX,
109        Bound::Included(n) => n,
110        Bound::Excluded(0) => return None,
111        Bound::Excluded(n) => n - 1,
112    };
113    Some((inclusive_start, inclusive_end))
114}
115
116fn overlap(a: (Bound<u64>, Bound<u64>), b: impl RangeBounds<u64>) -> Option<RangeInclusive<u64>> {
117    let b = (b.start_bound().cloned(), b.end_bound().cloned());
118    let a_inclusive = range_force_inclusive(a)?;
119    let b_inclusive = range_force_inclusive(b)?;
120    let start = u64::max(a_inclusive.0, b_inclusive.0);
121    let end = u64::min(a_inclusive.1, b_inclusive.1);
122    if start <= end {
123        Some(start..=end)
124    } else {
125        None
126    }
127}
128
129/// An index into a Merkle tree which could not be resolved, as there is no item
130/// there, or the path was deliberately collapsed.
131#[derive(Debug, Clone)]
132pub struct InvalidIndex(pub u64);
133
134impl Display for InvalidIndex {
135    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
136        write!(f, "invalid index into sparse merkle tree: {}", self.0)
137    }
138}
139
140impl Error for InvalidIndex {}
141
142/// An index into a Merkle tree which could not be resolved, as there is no item
143/// there, or the path was deliberately collapsed.
144#[derive(Debug, Copy, Clone, PartialEq, Eq)]
145#[non_exhaustive]
146pub enum InvalidUpdate {
147    /// The given index, for the given tree height, was collapsed, but needed
148    /// for an update.
149    CollapsedIndex(u128, u8),
150    /// The given index, for the given tree height, was stubbed, but needed to
151    /// produce an update.
152    StubUpdate(u128, u8),
153    /// The update range end is before the range start.
154    EndBeforeStart(u64, u64),
155    /// The update range end is not in the tree bounds.
156    EndOutOfTree(u64),
157    /// The update index is not in the tree bounds.
158    IndexOutOfTree(u64),
159    /// The update contained a different number of segments than expected.
160    WrongNumberOfSegments(usize, usize),
161    /// Attempted to build an update over a not-fully rehashed tree
162    NotFullyRehashed,
163    /// An update path didn't make sense (e.g. too many entries)
164    BadUpdatePath,
165}
166
167impl Display for InvalidUpdate {
168    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
169        use InvalidUpdate::*;
170        match self {
171            CollapsedIndex(idx, height) => write!(
172                f,
173                "attempted update on collapsed sub-tree at {idx}/{height}"
174            ),
175            StubUpdate(idx, height) => {
176                write!(f, "attempted update on updated sub-tree at {idx}/{height}")
177            }
178            EndBeforeStart(start, end) => write!(
179                f,
180                "attempted update with end ({end}) after before ({start})"
181            ),
182            EndOutOfTree(end) => write!(f, "attempted update with end ({end}) outside of the tree"),
183            IndexOutOfTree(index) => {
184                write!(f, "attempted update at index ({index}) outside of the tree")
185            }
186            WrongNumberOfSegments(..) => write!(f, "attempted update with mismatch segment count"),
187            NotFullyRehashed => write!(f, "attempted update without the tree being fully rehashed"),
188            BadUpdatePath => write!(
189                f,
190                "attempted to apply an update path that wasn't compatible with the tree"
191            ),
192        }
193    }
194}
195
196impl Error for InvalidUpdate {}
197
198/// The hash of any given leaf.
199pub fn leaf_hash<T: BinaryHashRepr + ?Sized>(value: &T) -> HashOutput {
200    let mut data = Vec::with_capacity(value.binary_len() + LEAF_HASH_DOMAIN_SEP.len());
201    data.extend(LEAF_HASH_DOMAIN_SEP);
202    value.binary_repr(&mut data);
203    persistent_hash(&data)
204}
205
206impl<T: BinaryHashRepr> MerklePath<T> {
207    /// The tree root that matches a Merkle path.
208    pub fn root(&self) -> MerkleTreeDigest {
209        MerkleTreeDigest(self.path.iter().fold(
210            degrade_to_transient(leaf_hash(&self.leaf)),
211            |acc, entry| {
212                if entry.goes_left {
213                    transient_hash(&[acc, entry.sibling.0])
214                } else {
215                    transient_hash(&[entry.sibling.0, acc])
216                }
217            },
218        ))
219    }
220}
221
222/// One entry in the Merkle path.
223#[derive(Debug, Clone, FieldRepr, Serializable)]
224pub struct MerklePathEntry {
225    /// The hash of the sibling element.
226    pub sibling: MerkleTreeDigest,
227    /// Whether the path went left at this branch.
228    pub goes_left: bool,
229}
230
231/// A part describing a specific tree insertion, together with intermediate hashes.
232/// This allows replaying this insertion, even against collapsed trees.
233/// The intermediate hashes may be missing, in case the tree was not fully
234/// rehashed, in which case its success depends on the non-rehashed parts not
235/// being collapsed in the target for insertion.
236#[derive(Debug, Clone, PartialEq, Eq, Serializable, Storable)]
237#[tag = "tree-insertion-path[v1]"]
238#[storable(base)]
239pub struct TreeInsertionPath<A>
240where
241    A: Serializable + Deserializable + Clone + Sync + Send + 'static,
242{
243    /// The leaf that was ultimately inserted
244    pub leaf: (HashOutput, A),
245    /// The path itself, from the leaf up
246    pub path: Vec<TreeInsertionPathEntry>,
247}
248tag_enforcement_test!(TreeInsertionPath<()>);
249
250/// An item in [`TreeInsertionPath`].
251#[derive(Debug, Clone, PartialEq, Eq, Serializable)]
252#[tag = "tree-insertion-path-entry[v1]"]
253pub struct TreeInsertionPathEntry {
254    /// The hash of the element along the path (*not* the sibling!), if available.
255    pub hash: Option<MerkleTreeDigest>,
256    /// Whether the path went left at this branch.
257    pub goes_left: bool,
258}
259tag_enforcement_test!(TreeInsertionPathEntry);
260
261/// The hash of a Merkle tree node.
262#[derive(
263    Copy,
264    Clone,
265    Hash,
266    Default,
267    PartialEq,
268    Eq,
269    PartialOrd,
270    Ord,
271    FieldRepr,
272    Serializable,
273    Serialize,
274    Dummy,
275    Storable,
276)]
277#[storable(base)]
278#[cfg_attr(feature = "proptest", derive(Arbitrary))]
279#[tag = "merkle-tree-digest[v1]"]
280pub struct MerkleTreeDigest(pub Fr);
281tag_enforcement_test!(MerkleTreeDigest);
282
283impl rand::distributions::Distribution<MerkleTreeDigest> for rand::distributions::Standard {
284    fn sample<R: rand::Rng + ?Sized>(&self, rng: &mut R) -> MerkleTreeDigest {
285        MerkleTreeDigest(rng.r#gen())
286    }
287}
288
289impl From<Fr> for MerkleTreeDigest {
290    fn from(field: Fr) -> MerkleTreeDigest {
291        MerkleTreeDigest(field)
292    }
293}
294
295impl From<MerkleTreeDigest> for Fr {
296    fn from(digest: MerkleTreeDigest) -> Fr {
297        digest.0
298    }
299}
300impl Debug for MerkleTreeDigest {
301    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
302        write!(formatter, "{}", self.0)
303    }
304}
305
306/// A concise update skipping for a range of the tree, in collapsed form.
307#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Serializable)]
308#[tag = "merkle-tree-collapsed-update[v1]"]
309pub struct MerkleTreeCollapsedUpdate {
310    /// The first index covered by the update range.
311    pub start: u64,
312    /// The last index covered by the update range.
313    pub end: u64,
314    hashes: Vec<MerkleTreeDigest>,
315}
316tag_enforcement_test!(MerkleTreeCollapsedUpdate);
317
318impl Debug for MerkleTreeCollapsedUpdate {
319    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
320        f.debug_struct("MerkleTreeCollapsedUpdate")
321            .field("start", &self.start)
322            .field("end", &self.end)
323            .finish()
324    }
325}
326
327impl MerkleTreeCollapsedUpdate {
328    fn step_sizes(mut a: u64, b: u64) -> Vec<u8> {
329        // A hash of height 0 can step from x to x+1
330        // A hash of height h can step from x to x+(2^h) IF 2^h | x
331        // We want to step from a to b in the fewest number of steps
332        // Ex: 010110 -> 011101
333        //   - 010110 -> 011000 (+ 10)
334        //   - 011000 -> 011100 (+ 100)
335        //   - 011100 -> 011101 (+ 1)
336        // Two stages:
337        // 1. Get the MSB that differs flipped, by adding increasing powers of
338        //    two when possible
339        // 2. Cascade down, decreasing powers of two until equal to b.
340        let msb_diff = (b ^ a).ilog2() as u8;
341        let mut res = Vec::with_capacity(u8::max(1, msb_diff) as usize * 2 - 1);
342        // Stage 1: Flip increasing
343        for bit in 0..msb_diff {
344            let shifted = 1 << bit as u64;
345            if (a & shifted) != 0 {
346                a += shifted;
347                res.push(bit);
348            }
349        }
350        // Stage 1.5: Flip msb
351        if a & (1 << msb_diff) == 0 {
352            res.push(msb_diff);
353        }
354        // Stage 2: Flip decreasing
355        for bit in (0..msb_diff).rev() {
356            if (b & (1 << bit as u64)) != 0 {
357                res.push(bit);
358            }
359        }
360        res
361    }
362
363    fn partial_index<A: Storable<D>, D: DB>(
364        tree: &MerkleTree<A, D>,
365        idx: u128,
366        height: u8,
367    ) -> Result<MerkleTreeDigest, InvalidUpdate> {
368        let hdiff = tree.height() - height;
369        let mut curr = tree.0.deref();
370        for i in 0..hdiff {
371            let go_left = (idx & (1u128 << (tree.height() - i - 1))) == 0;
372            match curr {
373                Leaf { .. } => unreachable!(),
374                Node { left, right, .. } => curr = if go_left { left } else { right },
375                Collapsed { .. } => return Err(InvalidUpdate::CollapsedIndex(idx, height)),
376                Stub { .. } => return Err(InvalidUpdate::StubUpdate(idx, height)),
377            }
378        }
379        Ok(MerkleTreeDigest(
380            curr.root().ok_or(InvalidUpdate::NotFullyRehashed)?,
381        ))
382    }
383
384    /// Creates a new collapsed update slice, starting from a given index, and
385    /// ending (inclusively) at a given index.
386    ///
387    /// The source tree should either not be collapsed, or collapse exactly
388    /// between these indices, and not further. It should also not include stub
389    /// entries (that is, be a sparse part of the tree).
390    pub fn new<A: Storable<D>, D: DB>(
391        tree: &MerkleTree<A, D>,
392        start: u64,
393        end: u64,
394    ) -> Result<Self, InvalidUpdate> {
395        if end < start {
396            return Err(InvalidUpdate::EndBeforeStart(start, end));
397        }
398        if (end as u128) >= (1u128 << tree.height()) {
399            return Err(InvalidUpdate::EndOutOfTree(end));
400        }
401        let step_sizes = Self::step_sizes(start, end + 1);
402        let mut hashes = Vec::with_capacity(step_sizes.len());
403        let mut curr = start as u128;
404        for step in step_sizes.into_iter() {
405            hashes.push(Self::partial_index(tree, curr, step)?);
406            curr += 1u128 << step as u128;
407        }
408        Ok(MerkleTreeCollapsedUpdate { start, end, hashes })
409    }
410}
411
412/// A Merkle tree, represented sparsely.
413///
414/// Unless otherwise specified, operations are O(height), excepting
415/// serialization. All operations are safe, unless parts of the tree are
416/// collapsed.
417///
418/// The tree is indexed as if it were an array of length `2^height`: data leaves
419/// only occur at the end of paths of length `height` bits.
420#[derive_where(Clone, PartialOrd, PartialEq, Ord, Eq; A)]
421#[derive(Storable)]
422#[storable(db = D)]
423#[tag = "merkle-tree[v1]"]
424pub struct MerkleTree<A: Storable<D>, D: DB = DefaultDB>(
425    #[cfg(feature = "public-internal-structure")] pub Sp<MerkleTreeNode<A, D>, D>,
426    #[cfg(not(feature = "public-internal-structure"))] Sp<MerkleTreeNode<A, D>, D>,
427);
428tag_enforcement_test!(MerkleTree<(), InMemoryDB>);
429
430impl<A: Storable<D>, D: DB> Hash for MerkleTree<A, D> {
431    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
432        Hash::hash(&self.0.hash(), state)
433    }
434}
435
436impl<A: Debug + Storable<D>, D: DB> Debug for MerkleTree<A, D> {
437    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
438        f.write_fmt(format_args!("MerkleTree(root = {:?}) ", self.root()))?;
439        self.0.fmt(f)
440    }
441}
442
443struct SerdeMerkleTreeMap<'a, A: Storable<D>, D: DB>(&'a MerkleTree<A, D>);
444
445impl<A: Serialize + Storable<D>, D: DB> Serialize for MerkleTree<A, D> {
446    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
447        let mut pair = ser.serialize_tuple(2)?;
448        pair.serialize_element(&self.height())?;
449        pair.serialize_element(&SerdeMerkleTreeMap(self))?;
450        pair.end()
451    }
452}
453
454impl<A: Serialize + Storable<D>, D: DB> Serialize for SerdeMerkleTreeMap<'_, A, D> {
455    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
456        ser.collect_map(self.0.iter_aux())
457    }
458}
459
460impl<'de, A: Deserialize<'de> + Storable<D>, D: DB> Deserialize<'de> for MerkleTree<A, D> {
461    fn deserialize<D2: Deserializer<'de>>(de: D2) -> Result<Self, D2::Error> {
462        let (height, data): (u8, std::collections::HashMap<u64, (HashOutput, A)>) =
463            Deserialize::deserialize(de)?;
464        data.into_iter()
465            .try_fold(MerkleTree::blank(height), |mt, (k, (v, a))| {
466                MerkleTree::try_update_hash(&mt, k, v, a)
467                    .map_err(<D2::Error as serde::de::Error>::custom)
468            })
469            .map(|mt| mt.rehash())
470    }
471}
472
473/// Inner Merkle tree node type
474#[derive_where(Clone, Hash, Ord, PartialOrd, Eq, PartialEq; A)]
475#[derive(Storable)]
476#[storable(db = D, invariant = MerkleTreeNode::invariant)]
477#[tag = "merkle-tree-node[v1]"]
478pub enum MerkleTreeNode<A: Storable<D>, D: DB> {
479    /// Leaf node
480    Leaf {
481        /// Stored hash
482        hash: HashOutput,
483        /// Auxiliary data
484        aux: A,
485    },
486    /// Collapsed
487    Collapsed {
488        /// Intermediate hash
489        hash: Fr,
490        /// Height of collapsed section
491        height: u8,
492    },
493    /// Stub
494    Stub {
495        /// Height
496        height: u8,
497    },
498    /// Branching node
499    Node {
500        /// Intermediate hash
501        hash: Option<Sp<Fr, D>>,
502        /// Left node
503        #[storable(child)]
504        left: Sp<MerkleTreeNode<A, D>, D>,
505        /// Right node
506        #[storable(child)]
507        right: Sp<MerkleTreeNode<A, D>, D>,
508        /// Height
509        height: u8,
510    },
511}
512tag_enforcement_test!(MerkleTreeNode<(), InMemoryDB>);
513
514impl<Faker, D: DB> fake::Dummy<Faker> for MerkleTree<(), D> {
515    fn dummy(_config: &Faker) -> Self {
516        // TODO: make random trees!
517        let mut mt = MerkleTree::<(), D>::blank(32);
518        if let Ok(updated) = mt
519            .try_update(0, &Fr::from(42u64), ())
520            .and_then(|mt| mt.try_update(0, &Fr::from(41u64), ()))
521            .and_then(|mt| mt.try_update(3, &Fr::from(43u64), ()))
522            .and_then(|mt| mt.try_update(62, &Fr::from(12u64), ()))
523        {
524            mt = updated;
525        }
526        mt
527    }
528
529    fn dummy_with_rng<R: rand::Rng + ?Sized>(config: &Faker, _rng: &mut R) -> Self {
530        Self::dummy(config)
531    }
532}
533
534struct DebugCollapsed;
535
536impl Debug for DebugCollapsed {
537    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
538        write!(f, "<collapsed>")
539    }
540}
541
542struct DebugEntry<'a, A>(HashOutput, &'a A);
543
544impl<A: Debug> Debug for DebugEntry<'_, A> {
545    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
546        write!(f, "({:?}, {:?})", self.0, self.1)
547    }
548}
549
550impl<A: Debug + Storable<D>, D: DB> Debug for MerkleTreeNode<A, D> {
551    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
552        use LeafOrCollapsed::*;
553        let mut map = f.debug_map();
554        let mut current_collapsed_range = None;
555        for leaf in self.leaves().into_iter() {
556            match (leaf, current_collapsed_range) {
557                (Leaf { index, hash, aux }, None) => {
558                    map.entry(&index, &DebugEntry(hash, aux));
559                }
560                (Leaf { index, hash, aux }, Some((start, end))) => {
561                    map.entry(&(start..=end), &DebugCollapsed);
562                    current_collapsed_range = None;
563                    map.entry(&index, &DebugEntry(hash, aux));
564                }
565                (Collapsed { start, end }, Some((start2, end2))) if end2 + 1 == start => {
566                    current_collapsed_range = Some((start2, end));
567                }
568                (Collapsed { start, end }, Some((start2, end2))) => {
569                    map.entry(&(start2..=end2), &DebugCollapsed);
570                    current_collapsed_range = Some((start, end));
571                }
572                (Collapsed { start, end }, None) => {
573                    current_collapsed_range = Some((start, end));
574                }
575            }
576        }
577        if let Some((start, end)) = current_collapsed_range {
578            map.entry(&(start..=end), &DebugCollapsed);
579        }
580        map.finish()
581    }
582}
583
584enum LeafOrCollapsed<'a, A> {
585    Leaf {
586        index: u64,
587        hash: HashOutput,
588        aux: &'a A,
589    },
590    Collapsed {
591        start: u64,
592        end: u64,
593    },
594}
595
596impl<A> LeafOrCollapsed<'_, A> {
597    fn upgrade(self, shift: u64) -> Self {
598        use LeafOrCollapsed::*;
599        match self {
600            Leaf { index, hash, aux } => Leaf {
601                index: index + shift,
602                hash,
603                aux,
604            },
605            Collapsed { start, end } => Collapsed {
606                start: start + shift,
607                end: end + shift,
608            },
609        }
610    }
611}
612
613impl<A: Storable<D>, D: DB> MerkleTreeNode<A, D> {
614    fn invariant(&self) -> std::io::Result<()> {
615        if let Node {
616            left,
617            right,
618            height,
619            hash,
620        } = self
621        {
622            if *height == 0 || *height - 1 != left.height() || *height - 1 != right.height() {
623                return Err(std::io::Error::new(
624                    std::io::ErrorKind::InvalidData,
625                    "MerkleTree inconsistent height on deserialization",
626                ));
627            }
628            // NOTE: WARN: we *cannot* check the hash invariant on deserialization!
629            // This is because deserialization is *severely* compute-time limited, and hashing is
630            // compute-heavy.
631            //
632            // What does this mean? Well, it means that untrusted Merkle trees could be internally
633            // invalid, which in turn means they may accept membership proofs for elements that do
634            // not appear to be present, until they are updated and rehashed.
635            //
636            // The only places untrusted Merkle trees can appear as of the time of writing are in
637            // Impact `push` operations, and contract initial deployments. Either case is within
638            // language and dApp bounds, and it is therefore on the language to ensure that these
639            // are computed sensibly.
640            //
641            //   if hash != transient_hash(&[left.root(), right.root()]) {
642            //       // ...
643            //   }
644
645            // If we *do* have a computed hash, children need to as well!
646            if hash.is_some() && (left.root().is_none() || right.root().is_none()) {
647                return Err(std::io::Error::new(
648                    std::io::ErrorKind::InvalidData,
649                    "MerkleTree children not rehashed, but parent claiming to be",
650                ));
651            }
652        }
653        Ok(())
654    }
655
656    fn leaves_in_range(&self, range: (Bound<u64>, Bound<u64>)) -> Vec<LeafOrCollapsed<'_, A>> {
657        match self {
658            Leaf { hash, aux } if range.contains(&0) => vec![LeafOrCollapsed::Leaf {
659                index: 0,
660                hash: *hash,
661                aux,
662            }],
663            Stub { .. } | Leaf { .. } => Vec::new(),
664            Collapsed { .. } => {
665                if let Some(range) = overlap(range, 0..(1 << self.height())) {
666                    vec![LeafOrCollapsed::Collapsed {
667                        start: *range.start(),
668                        end: *range.end(),
669                    }]
670                } else {
671                    Vec::new()
672                }
673            }
674            Node { left, right, .. } => left
675                .leaves_in_range(range)
676                .into_iter()
677                .chain(
678                    range_sub(range, 1 << left.height())
679                        .into_iter()
680                        .flat_map(|sub_range| right.leaves_in_range(sub_range).into_iter())
681                        .map(|leaf| leaf.upgrade(1 << left.height())),
682                )
683                .collect(),
684        }
685    }
686
687    fn leaves(&self) -> Vec<LeafOrCollapsed<'_, A>> {
688        self.leaves_in_range((Bound::Unbounded, Bound::Unbounded))
689    }
690
691    fn new(height: u8) -> Self {
692        Stub { height }
693    }
694
695    fn height(&self) -> u8 {
696        match self {
697            Leaf { .. } => 0,
698            Stub { height, .. } => *height,
699            Collapsed { height, .. } => *height,
700            Node { height, .. } => *height,
701        }
702    }
703
704    fn root(&self) -> Option<Fr> {
705        match self {
706            Leaf { hash, .. } => Some(degrade_to_transient(*hash)),
707            Stub { .. } => Some(Fr::default()),
708            Collapsed { hash, .. } => Some(*hash),
709            Node { hash, .. } => hash.as_ref().map(|h| **h),
710        }
711    }
712
713    #[allow(clippy::wrong_self_convention)]
714    fn is_collapsed(&self) -> bool {
715        matches!(self, Collapsed { .. })
716    }
717
718    fn update_from_evidence_internal(
719        &self,
720        leaf: (HashOutput, A),
721        path: &[TreeInsertionPathEntry],
722    ) -> Result<Self, InvalidUpdate> {
723        if let Collapsed { height, .. } = self {
724            let hash = if path.is_empty() {
725                degrade_to_transient(leaf.0)
726            } else {
727                path.last()
728                    .expect("non-empty")
729                    .hash
730                    .ok_or(InvalidUpdate::BadUpdatePath)?
731                    .0
732            };
733            return Ok(Collapsed {
734                hash,
735                height: *height,
736            });
737        }
738        if path.is_empty() {
739            return Ok(Leaf {
740                hash: leaf.0,
741                aux: leaf.1,
742            });
743        }
744        let entry = path.last().expect("non-empty");
745        Ok(match self {
746            Node {
747                left,
748                right,
749                height,
750                ..
751            } => {
752                if entry.goes_left {
753                    Node {
754                        hash: None,
755                        left: Sp::new(
756                            left.update_from_evidence_internal(leaf, &path[..path.len() - 1])?,
757                        ),
758                        right: right.clone(),
759                        height: *height,
760                    }
761                } else {
762                    Node {
763                        hash: None,
764                        left: left.clone(),
765                        right: Sp::new(
766                            right.update_from_evidence_internal(leaf, &path[..path.len() - 1])?,
767                        ),
768                        height: *height,
769                    }
770                }
771            }
772            Stub { .. } | Leaf { .. } | Collapsed { .. } => {
773                return Err(InvalidUpdate::BadUpdatePath);
774            }
775        })
776    }
777
778    /// Retrieves the leaf hash value at a given index, if available.
779    /// `index` *must* be within range of the tree height. Returns `None` if the
780    /// leaf is absent (a stub) or has been collapsed away.
781    pub fn index(&self, index: u64) -> Option<(HashOutput, &A)> {
782        match self {
783            Leaf { hash, aux, .. } => Some((*hash, aux)),
784            Stub { .. } => None,
785            Collapsed { .. } => None,
786            Node {
787                left,
788                right,
789                height,
790                ..
791            } => {
792                let cmp = 1 << (height - 1);
793                if index < cmp {
794                    left.index(index)
795                } else {
796                    right.index(index - cmp)
797                }
798            }
799        }
800    }
801}
802
803impl<A: Storable<D>, D: DB> MerkleTreeNode<A, D> {
804    fn partial_insert(
805        &self,
806        idx: u128,
807        height: u8,
808        digest: MerkleTreeDigest,
809    ) -> Result<Sp<Self, D>, InvalidUpdate> {
810        let hdiff = self.height() - height;
811        #[allow(clippy::type_complexity)]
812        let mut stack: Vec<(Sp<MerkleTreeNode<A, D>, D>, bool)> =
813            Vec::with_capacity(hdiff as usize);
814        let theight = self.height();
815        let mut curr: Sp<MerkleTreeNode<A, D>, D> = Sp::new(self.clone());
816        for i in 0..hdiff {
817            let go_left = idx & (1u128 << (theight - i - 1)) == 0;
818            match curr.clone().deref() {
819                Leaf { .. } => unreachable!(),
820                Node { left, right, .. } => {
821                    curr = if go_left { left.clone() } else { right.clone() };
822                    stack.push((if go_left { right.clone() } else { left.clone() }, go_left));
823                }
824                Stub { height } => {
825                    curr = Sp::new(Stub { height: height - 1 });
826                    stack.push((Sp::new(Stub { height: height - 1 }), go_left));
827                }
828                Collapsed { .. } => return Err(InvalidUpdate::CollapsedIndex(idx, height)),
829            }
830        }
831        Ok(stack.into_iter().rev().enumerate().fold(
832            Sp::new(Collapsed {
833                hash: digest.0,
834                height,
835            }),
836            |acc, (i, (sibling, goes_left))| {
837                let (left, right) = if goes_left {
838                    (acc, sibling)
839                } else {
840                    (sibling, acc)
841                };
842                Sp::new(Node {
843                    left,
844                    right,
845                    height: height + 1 + i as u8,
846                    hash: None,
847                })
848            },
849        ))
850    }
851
852    /// Force rehash this node and its children
853    pub fn rehash(&self) -> Self {
854        match self {
855            Leaf { .. } | Collapsed { .. } | Stub { .. } | Node { hash: Some(_), .. } => {
856                self.clone()
857            }
858            Node {
859                hash: None,
860                left,
861                right,
862                height,
863            } => {
864                let left = Sp::new(left.rehash());
865                let right = Sp::new(right.rehash());
866                let hash = Some(Sp::new(transient_hash(&[
867                    left.root().expect("rehashed tree must have root"),
868                    right.root().expect("rehashed tree must have root"),
869                ])));
870                Node {
871                    hash,
872                    left,
873                    right,
874                    height: *height,
875                }
876            }
877        }
878    }
879
880    fn collapse(&self, start: u64, end: u64) -> Sp<Self, D> {
881        match self {
882            Leaf { hash, .. } => {
883                return Sp::new(Collapsed {
884                    hash: degrade_to_transient(*hash),
885                    height: 0,
886                });
887            }
888            Collapsed { .. } => return Sp::new(self.clone()),
889            _ => {}
890        }
891        let h = self.height();
892        if start == 0 && end == (1 << h) - 1 {
893            return Sp::new(Collapsed {
894                hash: self.rehash().root().expect("rehashed tree must have root"),
895                height: h,
896            });
897        }
898        let self2 = if let Stub { height } = self {
899            let new = Sp::new(MerkleTreeNode::<A, D>::new(*height - 1));
900            Some(Node {
901                hash: Some(Sp::new(Fr::default())),
902                left: new.clone(),
903                right: new,
904                height: *height,
905            })
906        } else {
907            None
908        };
909        if let Node {
910            left,
911            right,
912            height,
913            hash,
914            ..
915        } = self2.as_ref().unwrap_or(self)
916        {
917            let cmp = 1 << (h - 1);
918            let left = if start < cmp {
919                left.collapse(start, u64::min(end, cmp - 1))
920            } else {
921                left.clone()
922            };
923            let right = if end >= cmp {
924                right.collapse(start.saturating_sub(cmp), end - cmp)
925            } else {
926                right.clone()
927            };
928            if left.is_collapsed() && right.is_collapsed() {
929                return Sp::new(Collapsed {
930                    hash: self.rehash().root().expect("rehashed node must have root"),
931                    height: *height,
932                });
933            }
934            Sp::new(Node {
935                left,
936                right,
937                // NOTE: Collapsing leaves the hash invariant!
938                hash: hash.clone(),
939                height: *height,
940            })
941        } else {
942            unreachable!()
943        }
944    }
945
946    /// Inserts a hash value at a specific index, returning the resulting tree.
947    /// `index` *must* be within range of the tree height.
948    #[deprecated = "This version panics rather than throwing errors. Prefer `try_update_hash`."]
949    pub fn update_hash(&self, index: u64, new_leaf: HashOutput, new_aux: A) -> Sp<Self, D> {
950        self.try_update_hash(index, new_leaf, new_aux)
951            .expect("attempted update into collapsed tree")
952    }
953
954    /// Inserts a hash value at a specific index, returning the resulting tree.
955    /// `index` *must* be within range of the tree height.
956    pub fn try_update_hash(
957        &self,
958        index: u64,
959        new_leaf: HashOutput,
960        new_aux: A,
961    ) -> Result<Sp<Self, D>, InvalidUpdate> {
962        if (index as u128) >= (1u128 << self.height()) {
963            return Err(InvalidUpdate::IndexOutOfTree(index));
964        }
965        let h = self.height();
966        if self.is_collapsed() {
967            return Err(InvalidUpdate::CollapsedIndex(index as u128, h));
968        }
969        if self.height() == 0 {
970            return Ok(Sp::new(Leaf {
971                hash: new_leaf,
972                aux: new_aux,
973            }));
974        }
975        let self2 = if let Stub { height } = self {
976            let new = Sp::new(MerkleTreeNode::new(*height - 1));
977            Some(Node {
978                hash: None,
979                left: new.clone(),
980                right: new,
981                height: *height,
982            })
983        } else {
984            None
985        };
986        if let Node {
987            left,
988            right,
989            height,
990            ..
991        } = self2.as_ref().unwrap_or(self)
992        {
993            let cmp = 1 << (h - 1);
994            // Here `index < cmp` is the same as `index & cmp == 0`, i.e. we're
995            // checking if the height `h` bit in the path is set or not.
996            let (left, right) = if index < cmp {
997                (
998                    left.try_update_hash(index, new_leaf, new_aux)?,
999                    right.clone(),
1000                )
1001            } else {
1002                (
1003                    left.clone(),
1004                    right.try_update_hash(index - cmp, new_leaf, new_aux)?,
1005                )
1006            };
1007            Ok(Sp::new(Node {
1008                left,
1009                right,
1010                hash: None,
1011                height: *height,
1012            }))
1013        } else {
1014            unreachable!()
1015        }
1016    }
1017}
1018
1019use MerkleTreeNode::*;
1020
1021/// An iterator over Merkle tree leaf indices and hashes.
1022pub struct MerkleTreeIter(std::vec::IntoIter<(u64, HashOutput)>);
1023
1024impl Iterator for MerkleTreeIter {
1025    type Item = (u64, HashOutput);
1026
1027    fn next(&mut self) -> Option<Self::Item> {
1028        self.0.next()
1029    }
1030}
1031
1032/// An iterator over Merkle tree leaf indices, hashes, and auxiliary data
1033pub struct MerkleTreeIterAux<A>(std::vec::IntoIter<(u64, (HashOutput, A))>);
1034
1035impl<A> Iterator for MerkleTreeIterAux<A> {
1036    type Item = (u64, (HashOutput, A));
1037
1038    fn next(&mut self) -> Option<Self::Item> {
1039        self.0.next()
1040    }
1041}
1042
1043impl<A: Storable<D>, D: DB> MerkleTree<A, D> {
1044    /// Create an empty Merkle tree with a given height. Must be O(1).
1045    pub fn blank(height: u8) -> Self {
1046        MerkleTree(Sp::new(Stub { height }))
1047    }
1048
1049    /// Inserts a hash value at a specific index, returning the resulting tree.
1050    /// `index` *must* be within range of the tree height.
1051    #[deprecated = "This version panics rather than throwing errors. Prefer `try_update_hash`."]
1052    pub fn update_hash(&self, index: u64, new_leaf: HashOutput, aux: A) -> Self {
1053        #[allow(deprecated)]
1054        MerkleTree(self.0.update_hash(index, new_leaf, aux))
1055    }
1056
1057    /// Inserts a hash value at a specific index, returning the resulting tree.
1058    /// `index` *must* be within range of the tree height.
1059    pub fn try_update_hash(
1060        &self,
1061        index: u64,
1062        new_leaf: HashOutput,
1063        aux: A,
1064    ) -> Result<Self, InvalidUpdate> {
1065        Ok(MerkleTree(self.0.try_update_hash(index, new_leaf, aux)?))
1066    }
1067
1068    /// Inserts a value into a specific index of the tree.
1069    ///
1070    /// # Panics
1071    ///
1072    /// May panic if this index was previously in a range passed to
1073    /// [`collapse`](crate::merkle_tree::MerkleTree::collapse).
1074    #[deprecated = "This version panics rather than throwing errors. Prefer `try_update_hash`."]
1075    pub fn update<T: BinaryHashRepr + ?Sized>(&self, index: u64, value: &T, aux: A) -> Self {
1076        #[allow(deprecated)]
1077        self.update_hash(index, crate::merkle_tree::leaf_hash(value), aux)
1078    }
1079
1080    /// Inserts a value into a specific index of the tree.
1081    pub fn try_update<T: BinaryHashRepr + ?Sized>(
1082        &self,
1083        index: u64,
1084        value: &T,
1085        aux: A,
1086    ) -> Result<Self, InvalidUpdate> {
1087        self.try_update_hash(index, crate::merkle_tree::leaf_hash(value), aux)
1088    }
1089
1090    /// Collapses the tree between `start` and `end` (inclusive) into their
1091    /// hashes. This prevents future `update`s to this portion of the tree.
1092    pub fn collapse(&self, start: u64, end: u64) -> Self {
1093        MerkleTree(self.0.collapse(start, end))
1094    }
1095
1096    fn partial_insert(
1097        self,
1098        idx: u128,
1099        height: u8,
1100        digest: MerkleTreeDigest,
1101    ) -> Result<Self, InvalidUpdate> {
1102        Ok(MerkleTree(self.0.partial_insert(idx, height, digest)?))
1103    }
1104
1105    /// Apply a collapsed update to the current tree. This update should *not*
1106    /// touch any collapsed part of the current tree, and should be well-formed.
1107    pub fn apply_collapsed_update(
1108        &self,
1109        update: &MerkleTreeCollapsedUpdate,
1110    ) -> Result<Self, InvalidUpdate> {
1111        let segments = MerkleTreeCollapsedUpdate::step_sizes(update.start, update.end + 1);
1112        if segments.len() != update.hashes.len() {
1113            return Err(InvalidUpdate::WrongNumberOfSegments(
1114                segments.len(),
1115                update.hashes.len(),
1116            ));
1117        }
1118        let mut curr_idx = update.start as u128;
1119        let mut curr = self.clone();
1120        for (segment, hash) in segments.into_iter().zip(update.hashes.iter()) {
1121            curr = curr.partial_insert(curr_idx, segment, *hash)?.clone();
1122            curr_idx += 1u128 << segment as u128;
1123        }
1124        Ok(curr)
1125    }
1126}
1127
1128impl<A: Storable<D>, D: DB> MerkleTree<A, D> {
1129    /// Retrieves the height of this tree. Must be O(1).
1130    pub fn height(&self) -> u8 {
1131        self.0.height()
1132    }
1133
1134    /// Retrieves the Merkle root of this tree. Must be O(1).
1135    ///
1136    /// This returns `Some` iff the underlying tree has been rehashed.
1137    pub fn root(&self) -> Option<MerkleTreeDigest> {
1138        self.0.root().map(MerkleTreeDigest)
1139    }
1140
1141    /// Rehashes the Merkle tree, computing the new root and intermediate hashes.
1142    /// This is a separate operation as it amortizes costs across sequential
1143    /// insertions to `O(n + h)` instead of `O(nh)`.
1144    pub fn rehash(&self) -> Self {
1145        MerkleTree(Sp::new(self.0.rehash()))
1146    }
1147
1148    /// Retrieves the leaf hash value at a given index, if available.
1149    /// `index` *must* be within range of the tree height.
1150    pub fn index(&self, index: u64) -> Option<(HashOutput, &A)> {
1151        self.0.index(index)
1152    }
1153
1154    /// Iterate over the leaves and leaf indices of the tree.
1155    pub fn iter(&self) -> MerkleTreeIter {
1156        MerkleTreeIter(
1157            self.0
1158                .leaves()
1159                .into_iter()
1160                .filter_map(|leaf| match leaf {
1161                    LeafOrCollapsed::Leaf { index, hash, .. } => Some((index, hash)),
1162                    _ => None,
1163                })
1164                .collect::<Vec<_>>()
1165                .into_iter(),
1166        )
1167    }
1168
1169    /// Iterate over the leaves and leaf indices of the tree, includes aux data
1170    pub fn iter_aux(&self) -> MerkleTreeIterAux<A> {
1171        MerkleTreeIterAux(
1172            self.0
1173                .leaves()
1174                .into_iter()
1175                .filter_map(|leaf| match leaf {
1176                    LeafOrCollapsed::Leaf { index, hash, aux } => {
1177                        Some((index, (hash, aux.clone())))
1178                    }
1179                    _ => None,
1180                })
1181                .collect::<Vec<_>>()
1182                .into_iter(),
1183        )
1184    }
1185
1186    /// Generate an iterator over leaves, including indices, hashes, and auxiliary data
1187    /// Does a linear search for a given leaf.
1188    ///
1189    /// `O(2^height)` worst-case behavior, this should only be used for small trees.
1190    ///
1191    /// May panic if the Merkle tree has not been rehashed.
1192    pub fn find_path_for_leaf<T: BinaryHashRepr>(&self, leaf: T) -> Option<MerklePath<T>> {
1193        self.find_path_for_leaf_inner(leaf_hash(&leaf), leaf, ..)
1194    }
1195
1196    /// Acts as [`find_path_for_leaf`], but limits search to a specified range.
1197    pub fn find_path_for_leaf_within_range<T: BinaryHashRepr>(
1198        &self,
1199        leaf: T,
1200        range: impl RangeBounds<u64>,
1201    ) -> Option<MerklePath<T>> {
1202        self.find_path_for_leaf_inner(leaf_hash(&leaf), leaf, range)
1203    }
1204
1205    /// Acts as [`find_path_for_leaf_within_range`], but takes the leaf to be pre-hashed.
1206    pub fn find_path_for_hashed_leaf_within_range(
1207        &self,
1208        leaf_hash: HashOutput,
1209        range: impl RangeBounds<u64>,
1210    ) -> Option<MerklePath<HashOutput>> {
1211        self.find_path_for_leaf_inner(leaf_hash, leaf_hash, range)
1212    }
1213
1214    fn find_path_for_leaf_inner<T>(
1215        &self,
1216        leaf_hash: HashOutput,
1217        leaf: T,
1218        range: impl RangeBounds<u64>,
1219    ) -> Option<MerklePath<T>> {
1220        for (index, hash) in self
1221            .0
1222            .leaves_in_range((range.start_bound().cloned(), range.end_bound().cloned()))
1223            .into_iter()
1224            .filter_map(|leaf| match leaf {
1225                LeafOrCollapsed::Leaf { index, hash, .. } => Some((index, hash)),
1226                _ => None,
1227            })
1228        {
1229            if leaf_hash == hash {
1230                return self.path_for_leaf(index, leaf).ok();
1231            }
1232        }
1233        None
1234    }
1235
1236    /// Attempts to replay a piece of insertion evidence against this tree.
1237    /// Note that this requires the insertion to be from a trusted source, as
1238    /// hashes may not be checkable.
1239    pub fn update_from_evidence(
1240        &self,
1241        insertion: TreeInsertionPath<A>,
1242    ) -> Result<Self, InvalidUpdate>
1243    where
1244        A: Serializable + Deserializable + Clone + Sync + Send + 'static,
1245    {
1246        Ok(MerkleTree(Sp::new(self.0.update_from_evidence_internal(
1247            insertion.leaf,
1248            &insertion.path,
1249        )?)))
1250    }
1251
1252    /// Produces insertion evidence for a specific index; this index must be
1253    /// present and not collapsed.
1254    pub fn insertion_evidence(&self, index: u64) -> Result<TreeInsertionPath<A>, InvalidIndex>
1255    where
1256        A: Serializable + Deserializable + Clone + Sync + Send + 'static,
1257    {
1258        if self.height() == 0 {
1259            return Err(InvalidIndex(index));
1260        }
1261        let (path, lefts) = self.path_for_index_internal(index, false)?;
1262        let leaf = self.index(index).ok_or(InvalidIndex(index))?;
1263        Ok(TreeInsertionPath {
1264            leaf: (leaf.0, leaf.1.clone()),
1265            path: path
1266                .into_iter()
1267                .zip(lefts)
1268                .map(|(hash, goes_left)| {
1269                    Ok(TreeInsertionPathEntry {
1270                        hash: hash.map(MerkleTreeDigest),
1271                        goes_left,
1272                    })
1273                })
1274                .rev()
1275                .collect::<Result<_, _>>()?,
1276        })
1277    }
1278
1279    /// Given a leaf at a specific index, produces a [`MerklePath`] for it.
1280    ///
1281    /// May panic if the Merkle tree has not been rehashed.
1282    pub fn path_for_leaf<T>(&self, index: u64, leaf: T) -> Result<MerklePath<T>, InvalidIndex> {
1283        if self.height() == 0 {
1284            return if index == 0 {
1285                Ok(MerklePath {
1286                    leaf,
1287                    path: Vec::new(),
1288                })
1289            } else {
1290                Err(InvalidIndex(index))
1291            };
1292        }
1293        let (path, lefts) = self.path_for_index_internal(index, true)?;
1294        Ok(MerklePath {
1295            leaf,
1296            path: path
1297                .into_iter()
1298                .zip(lefts)
1299                .map(|(sibling, goes_left)| {
1300                    Ok(MerklePathEntry {
1301                        sibling: MerkleTreeDigest(sibling.ok_or(InvalidIndex(index))?),
1302                        goes_left,
1303                    })
1304                })
1305                .rev()
1306                .collect::<Result<_, _>>()?,
1307        })
1308    }
1309
1310    fn path_for_index_internal(
1311        &self,
1312        index: u64,
1313        siblings: bool,
1314    ) -> Result<(Vec<Option<Fr>>, Vec<bool>), InvalidIndex> {
1315        let mut at = self.0.deref();
1316        let mut i = index;
1317        assert!(
1318            at.height() >= 1,
1319            "height-0 trees should have been caught earlier"
1320        );
1321        let mut path = Vec::with_capacity(at.height() as usize);
1322        let mut goes_left = Vec::with_capacity(at.height() as usize);
1323        while at.height() > 1 {
1324            let cmp = 1 << (at.height() - 1);
1325            let nxt = match at {
1326                Leaf { .. } => unreachable!(),
1327                Stub { .. } => return Err(InvalidIndex(index)),
1328                Collapsed { .. } => return Err(InvalidIndex(index)),
1329                Node { left, right, .. } => {
1330                    if i < cmp {
1331                        path.push(if siblings { right.root() } else { at.root() });
1332                        goes_left.push(true);
1333                        left
1334                    } else {
1335                        path.push(if siblings { left.root() } else { at.root() });
1336                        goes_left.push(false);
1337                        i -= cmp;
1338                        right
1339                    }
1340                }
1341            };
1342            at = nxt;
1343        }
1344        goes_left.push(i == 0);
1345        let path_elem = match (siblings, i, at) {
1346            (_, _, Stub { .. }) => return Err(InvalidIndex(index)),
1347            (false, _, at) => at.root(),
1348            (true, 0, Node { right, .. }) => right.root(),
1349            (true, 1, Node { left, .. }) => left.root(),
1350            _ => unreachable!(),
1351        };
1352        path.push(path_elem);
1353        Ok((path, goes_left))
1354    }
1355}
1356
1357#[cfg(feature = "proptest")]
1358impl<A: Debug + Storable<D>, D: DB> Arbitrary for MerkleTree<A, D>
1359where
1360    Standard: Distribution<A>,
1361{
1362    type Parameters = ();
1363    type Strategy = NoStrategy<MerkleTree<A, D>>;
1364
1365    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
1366        NoStrategy(PhantomData)
1367    }
1368}
1369
1370impl<A: Storable<D>, D: DB> Distribution<MerkleTree<A, D>> for Standard
1371where
1372    Standard: Distribution<u8> + Distribution<Fr> + Distribution<A>,
1373{
1374    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> MerkleTree<A, D> {
1375        let height: u8 = rng.gen_range(1..17);
1376        let mut mt = MerkleTree::blank(height);
1377
1378        for i in 0..height {
1379            if let Ok(updated) = mt.try_update(i.into(), &rng.r#gen::<Fr>(), rng.r#gen()) {
1380                mt = updated;
1381            }
1382        }
1383
1384        mt.rehash()
1385    }
1386}
1387
1388#[cfg(test)]
1389mod tests {
1390    use sha2::Sha256;
1391
1392    use storage_core::db::InMemoryDB;
1393
1394    use super::*;
1395
1396    fn new_mt<A: Storable<InMemoryDB>>(height: u8) -> MerkleTree<A, InMemoryDB<Sha256>> {
1397        MerkleTree::<A, InMemoryDB<Sha256>>::blank(height)
1398    }
1399
1400    #[test]
1401    fn test_membership() {
1402        let tree = new_mt::<()>(32)
1403            .try_update(0, &Fr::from(42u64), ())
1404            .and_then(|mt| mt.try_update(0, &Fr::from(41u64), ()))
1405            .and_then(|mt| mt.try_update(3, &Fr::from(43u64), ()))
1406            .and_then(|mt| mt.try_update(62, &Fr::from(12u64), ()))
1407            .unwrap()
1408            .rehash();
1409        assert_eq!(
1410            tree.path_for_leaf(0, Fr::from(41u64)).unwrap().root(),
1411            tree.root().unwrap()
1412        );
1413        assert_eq!(
1414            tree.path_for_leaf(3, Fr::from(43u64)).unwrap().root(),
1415            tree.root().unwrap()
1416        );
1417        assert_eq!(
1418            tree.path_for_leaf(62, Fr::from(12u64)).unwrap().root(),
1419            tree.root().unwrap()
1420        );
1421    }
1422
1423    #[test]
1424    fn test_collapse_good() {
1425        let tree = new_mt::<()>(32)
1426            .try_update(0, &Fr::from(42u64), ())
1427            .and_then(|mt| mt.try_update(0, &Fr::from(41u64), ()))
1428            .and_then(|mt| mt.try_update(3, &Fr::from(43u64), ()))
1429            .and_then(|mt| mt.try_update(62, &Fr::from(12u64), ()))
1430            .unwrap()
1431            .collapse(0, 61)
1432            .rehash();
1433        assert_eq!(
1434            tree.path_for_leaf(62, Fr::from(12u64)).unwrap().root(),
1435            tree.root().unwrap()
1436        );
1437    }
1438
1439    #[test]
1440    fn test_collapse_bad_proof() {
1441        let tree = new_mt::<()>(32)
1442            .try_update(0, &Fr::from(42u64), ())
1443            .and_then(|mt| mt.try_update(0, &Fr::from(41u64), ()))
1444            .and_then(|mt| mt.try_update(3, &Fr::from(43u64), ()))
1445            .and_then(|mt| mt.try_update(62, &Fr::from(12u64), ()))
1446            .unwrap()
1447            .collapse(0, 61)
1448            .rehash();
1449        assert!(tree.path_for_leaf(3, Fr::from(43u64)).is_err());
1450    }
1451
1452    #[test]
1453    fn test_collapse_bad_update() {
1454        let tree = new_mt::<()>(32)
1455            .try_update(0, &Fr::from(42u64), ())
1456            .and_then(|mt| mt.try_update(0, &Fr::from(41u64), ()))
1457            .and_then(|mt| mt.try_update(3, &Fr::from(43u64), ()))
1458            .and_then(|mt| mt.try_update(62, &Fr::from(12u64), ()))
1459            .unwrap()
1460            .collapse(0, 61)
1461            .try_update(61, &Fr::from(0xdeadbeefu64), ());
1462        assert_eq!(tree, Err(InvalidUpdate::CollapsedIndex(1, 1)));
1463    }
1464
1465    #[test]
1466    fn test_incremental_collapse() {
1467        let tree = new_mt::<()>(3)
1468            .try_update(0, &Fr::from(42u64), ())
1469            .unwrap()
1470            .collapse(0, 0)
1471            .try_update(1, &Fr::from(42u64), ())
1472            .unwrap()
1473            .collapse(1, 1)
1474            .try_update(2, &Fr::from(42u64), ())
1475            .unwrap()
1476            .collapse(2, 2)
1477            .try_update(3, &Fr::from(42u64), ())
1478            .unwrap()
1479            .try_update(4, &Fr::from(42u64), ())
1480            .unwrap()
1481            .collapse(4, 4);
1482        let tree2 = new_mt::<()>(3)
1483            .try_update(0, &Fr::from(42u64), ())
1484            .and_then(|mt| mt.try_update(1, &Fr::from(42u64), ()))
1485            .and_then(|mt| mt.try_update(2, &Fr::from(42u64), ()))
1486            .and_then(|mt| mt.try_update(3, &Fr::from(42u64), ()))
1487            .and_then(|mt| mt.try_update(4, &Fr::from(42u64), ()))
1488            .unwrap()
1489            .collapse(0, 2)
1490            .collapse(4, 4);
1491        assert_eq!(tree, tree2);
1492    }
1493
1494    #[test]
1495    fn test_collapsed_update() {
1496        let t = new_mt::<()>(6)
1497            .try_update(0, &Fr::from(42u64), ())
1498            .unwrap()
1499            .try_update(1, &Fr::from(42u64), ())
1500            .unwrap();
1501        let t2 = (2..=32)
1502            .fold(t.clone(), |t, i| {
1503                t.try_update(i, &Fr::from(42u64), ()).unwrap()
1504            })
1505            .rehash();
1506        let upd1 = MerkleTreeCollapsedUpdate::new(&t2, 2, 2).unwrap();
1507        let upd2 = MerkleTreeCollapsedUpdate::new(&t2, 3, 31).unwrap();
1508        let t3 = t.try_update(32, &Fr::from(42u64), ()).unwrap();
1509        let t4 = t3
1510            .apply_collapsed_update(&upd1)
1511            .unwrap()
1512            .apply_collapsed_update(&upd2)
1513            .unwrap()
1514            .rehash();
1515        assert_eq!(t4.root(), t2.root());
1516    }
1517
1518    #[test]
1519    fn test_insertion_evidence() {
1520        let t = (0..=32)
1521            .fold(new_mt::<()>(6), |t, i| {
1522                t.try_update(i, &Fr::from(42u64), ()).unwrap()
1523            })
1524            .rehash();
1525        let t2 = t.try_update(12, &Fr::from(43u64), ()).unwrap().rehash();
1526        let evidence = t2.insertion_evidence(12).unwrap();
1527        assert_eq!(
1528            t.update_from_evidence(evidence.clone()).unwrap().rehash(),
1529            t2
1530        );
1531        assert_eq!(
1532            t.collapse(0, 32)
1533                .update_from_evidence(evidence)
1534                .unwrap()
1535                .rehash()
1536                .root(),
1537            t2.root()
1538        );
1539        // test *not* rehashing the tree first
1540        let t3 = (33..64).fold(
1541            t.try_update(12, &Fr::from(43u64), ()).unwrap().rehash(),
1542            |t, i| t.try_update(i, &Fr::from(42u64), ()).unwrap(),
1543        );
1544        let evidence = t3.insertion_evidence(12).unwrap();
1545        dbg!(&evidence);
1546        // We should still be able to insert into collapsed `t`!
1547        assert_eq!(
1548            t.collapse(0, 32)
1549                .update_from_evidence(evidence)
1550                .unwrap()
1551                .rehash()
1552                .root(),
1553            t2.root()
1554        );
1555    }
1556
1557    #[test]
1558    fn test_singleton_collapsed_update() {
1559        let t = new_mt::<()>(6)
1560            .try_update(0, &Fr::from(42u64), ())
1561            .unwrap()
1562            .rehash();
1563        let upd = MerkleTreeCollapsedUpdate::new(&t, 0, 0).unwrap();
1564        let t2 = new_mt::<()>(6)
1565            .apply_collapsed_update(&upd)
1566            .unwrap()
1567            .rehash();
1568        assert_eq!(t.root(), t2.root());
1569    }
1570
1571    #[test]
1572    fn test_tiny_trees() {
1573        let t = new_mt::<()>(1)
1574            .try_update(0, &Fr::from(42u64), ())
1575            .unwrap()
1576            .try_update(1, &Fr::from(42u64), ())
1577            .unwrap();
1578        t.path_for_leaf(0, Fr::from(42u64)).unwrap();
1579        let t = new_mt::<()>(0).try_update(0, &Fr::from(42u64), ()).unwrap();
1580        t.path_for_leaf(0, Fr::from(42u64)).unwrap();
1581    }
1582
1583    #[test]
1584    fn test_aux_data() {
1585        let t = new_mt::<u8>(32)
1586            .try_update(0, &Fr::from(42u64), 10)
1587            .unwrap();
1588        for (_index, (_hash, aux)) in t.iter_aux() {
1589            assert_eq!(aux, 10);
1590        }
1591    }
1592
1593    #[test]
1594    fn test_find_path_for_leaf_within_range() {
1595        let tree = new_mt::<()>(32)
1596            .try_update(0, &Fr::from(10u64), ())
1597            .and_then(|mt| mt.try_update(5, &Fr::from(20u64), ()))
1598            .and_then(|mt| mt.try_update(10, &Fr::from(30u64), ()))
1599            .unwrap()
1600            .rehash();
1601
1602        // Full range finds the leaf
1603        assert!(
1604            tree.find_path_for_leaf_within_range(Fr::from(20u64), ..)
1605                .is_some()
1606        );
1607
1608        // Range containing the leaf finds it
1609        assert!(
1610            tree.find_path_for_leaf_within_range(Fr::from(20u64), 3..=7)
1611                .is_some()
1612        );
1613
1614        // Range excluding the leaf does not find it
1615        assert!(
1616            tree.find_path_for_leaf_within_range(Fr::from(20u64), 0..=4)
1617                .is_none()
1618        );
1619        assert!(
1620            tree.find_path_for_leaf_within_range(Fr::from(20u64), 6..=100)
1621                .is_none()
1622        );
1623
1624        // Path produced is valid
1625        let path = tree
1626            .find_path_for_leaf_within_range(Fr::from(30u64), 8..=12)
1627            .expect("leaf at index 10 should be in range 8..=12");
1628        assert_eq!(path.root(), tree.root().unwrap());
1629    }
1630
1631    #[test]
1632    fn test_find_path_for_hashed_leaf_within_range() {
1633        let tree = new_mt::<()>(32)
1634            .try_update(0, &Fr::from(10u64), ())
1635            .and_then(|mt| mt.try_update(5, &Fr::from(20u64), ()))
1636            .unwrap()
1637            .rehash();
1638
1639        let hash = leaf_hash(&Fr::from(20u64));
1640
1641        // Finds by hash
1642        assert!(
1643            tree.find_path_for_hashed_leaf_within_range(hash, ..)
1644                .is_some()
1645        );
1646
1647        // Range restriction works
1648        assert!(
1649            tree.find_path_for_hashed_leaf_within_range(hash, 5..=5)
1650                .is_some()
1651        );
1652        assert!(
1653            tree.find_path_for_hashed_leaf_within_range(hash, 0..=4)
1654                .is_none()
1655        );
1656    }
1657
1658    #[test]
1659    fn test_find_within_range_with_collapsed() {
1660        let tree = new_mt::<()>(6)
1661            .try_update(0, &Fr::from(10u64), ())
1662            .and_then(|mt| mt.try_update(5, &Fr::from(20u64), ()))
1663            .and_then(|mt| mt.try_update(10, &Fr::from(30u64), ()))
1664            .unwrap()
1665            .collapse(0, 4)
1666            .rehash();
1667
1668        // Leaf in collapsed region is not found
1669        assert!(
1670            tree.find_path_for_leaf_within_range(Fr::from(10u64), ..)
1671                .is_none()
1672        );
1673
1674        // Leaf outside collapsed region is found
1675        assert!(
1676            tree.find_path_for_leaf_within_range(Fr::from(20u64), ..)
1677                .is_some()
1678        );
1679
1680        // Range restricted to collapsed region returns nothing
1681        assert!(
1682            tree.find_path_for_leaf_within_range(Fr::from(20u64), 0..=4)
1683                .is_none()
1684        );
1685    }
1686
1687    #[test]
1688    fn test_find_within_range_duplicate_leaves() {
1689        let val = Fr::from(42u64);
1690        let tree = new_mt::<()>(6)
1691            .try_update(2, &val, ())
1692            .and_then(|mt| mt.try_update(5, &val, ()))
1693            .and_then(|mt| mt.try_update(8, &val, ()))
1694            .unwrap()
1695            .rehash();
1696
1697        // Restricting range picks the correct duplicate
1698        let path = tree
1699            .find_path_for_leaf_within_range(val, 4..=6)
1700            .expect("should find leaf at index 5");
1701        assert_eq!(path.root(), tree.root().unwrap());
1702
1703        let path = tree
1704            .find_path_for_leaf_within_range(val, 7..=10)
1705            .expect("should find leaf at index 8");
1706        assert_eq!(path.root(), tree.root().unwrap());
1707
1708        // Empty range finds nothing
1709        assert!(tree.find_path_for_leaf_within_range(val, 3..=4).is_none());
1710    }
1711
1712    #[test]
1713    fn test_update_rejects_out_of_bounds_index() {
1714        let val = Fr::from(42u64);
1715        let tree = new_mt::<()>(1).try_update(1, &val, ()).unwrap().rehash();
1716
1717        let root_before = tree.root().unwrap();
1718
1719        let other_value = Fr::from(43u64);
1720        let result = tree.try_update(10, &other_value, ()).unwrap_err();
1721
1722        assert_eq!(result, InvalidUpdate::IndexOutOfTree(10));
1723        assert_eq!(tree.root().unwrap(), root_before);
1724    }
1725
1726    #[test]
1727    fn test_update_hash_rejects_out_of_bounds_index() {
1728        let val = Fr::from(42u64);
1729        let tree = new_mt::<()>(1);
1730        let hash = leaf_hash(&val);
1731
1732        let result = tree.try_update_hash(10, hash, ()).unwrap_err();
1733
1734        assert_eq!(result, InvalidUpdate::IndexOutOfTree(10));
1735    }
1736
1737    #[cfg(feature = "proptest")]
1738    proptest::proptest! {
1739        #[test]
1740        fn test_update_rejects_indices_at_or_above_tree_size(
1741            height in 0u8..=20,
1742            extra in 0u64..=1024,
1743            leaf in proptest::arbitrary::any::<u64>(),
1744        ) {
1745            let tree = new_mt::<()>(height);
1746            let tree_size = 1u64 << height;
1747            let index = tree_size + extra;
1748
1749            proptest::prop_assert_eq!(
1750                tree.try_update(index, &Fr::from(leaf), ()).unwrap_err(),
1751                InvalidUpdate::IndexOutOfTree(index),
1752            );
1753        }
1754    }
1755}