arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/mmr/partial.rs
src/merkle/mmr/partial.rsRaw
  1use alloc::{
  2    collections::{BTreeMap, BTreeSet},
  3    vec::Vec,
  4};
  5
  6use winter_utils::{Deserializable, Serializable};
  7
  8use super::{MmrDelta, MmrProof, Rpo256, RpoDigest};
  9use crate::merkle::{
 10    mmr::{leaf_to_corresponding_tree, nodes_in_forest},
 11    InOrderIndex, InnerNodeInfo, MerklePath, MmrError, MmrPeaks,
 12};
 13
 14// TYPE ALIASES
 15// ================================================================================================
 16
 17type NodeMap = BTreeMap<InOrderIndex, RpoDigest>;
 18
 19// PARTIAL MERKLE MOUNTAIN RANGE
 20// ================================================================================================
 21/// Partially materialized Merkle Mountain Range (MMR), used to efficiently store and update the
 22/// authentication paths for a subset of the elements in a full MMR.
 23///
 24/// This structure store only the authentication path for a value, the value itself is stored
 25/// separately.
 26#[derive(Debug, Clone, PartialEq, Eq)]
 27pub struct PartialMmr {
 28    /// The version of the MMR.
 29    ///
 30    /// This value serves the following purposes:
 31    ///
 32    /// - The forest is a counter for the total number of elements in the MMR.
 33    /// - Since the MMR is an append-only structure, every change to it causes a change to the
 34    ///   `forest`, so this value has a dual purpose as a version tag.
 35    /// - The bits in the forest also corresponds to the count and size of every perfect binary
 36    ///   tree that composes the MMR structure, which server to compute indexes and perform
 37    ///   validation.
 38    pub(crate) forest: usize,
 39
 40    /// The MMR peaks.
 41    ///
 42    /// The peaks are used for two reasons:
 43    ///
 44    /// 1. It authenticates the addition of an element to the [PartialMmr], ensuring only valid
 45    ///    elements are tracked.
 46    /// 2. During a MMR update peaks can be merged by hashing the left and right hand sides. The
 47    ///    peaks are used as the left hand.
 48    ///
 49    /// All the peaks of every tree in the MMR forest. The peaks are always ordered by number of
 50    /// leaves, starting from the peak with most children, to the one with least.
 51    pub(crate) peaks: Vec<RpoDigest>,
 52
 53    /// Authentication nodes used to construct merkle paths for a subset of the MMR's leaves.
 54    ///
 55    /// This does not include the MMR's peaks nor the tracked nodes, only the elements required to
 56    /// construct their authentication paths. This property is used to detect when elements can be
 57    /// safely removed, because they are no longer required to authenticate any element in the
 58    /// [PartialMmr].
 59    ///
 60    /// The elements in the MMR are referenced using a in-order tree index. This indexing scheme
 61    /// permits for easy computation of the relative nodes (left/right children, sibling, parent),
 62    /// which is useful for traversal. The indexing is also stable, meaning that merges to the
 63    /// trees in the MMR can be represented without rewrites of the indexes.
 64    pub(crate) nodes: NodeMap,
 65
 66    /// Flag indicating if the odd element should be tracked.
 67    ///
 68    /// This flag is necessary because the sibling of the odd doesn't exist yet, so it can not be
 69    /// added into `nodes` to signal the value is being tracked.
 70    pub(crate) track_latest: bool,
 71}
 72
 73impl PartialMmr {
 74    // CONSTRUCTORS
 75    // --------------------------------------------------------------------------------------------
 76
 77    /// Returns a new [PartialMmr] instantiated from the specified peaks.
 78    pub fn from_peaks(peaks: MmrPeaks) -> Self {
 79        let forest = peaks.num_leaves();
 80        let peaks = peaks.into();
 81        let nodes = BTreeMap::new();
 82        let track_latest = false;
 83
 84        Self { forest, peaks, nodes, track_latest }
 85    }
 86
 87    /// Returns a new [PartialMmr] instantiated from the specified components.
 88    ///
 89    /// This constructor does not check the consistency between peaks and nodes. If the specified
 90    /// peaks are nodes are inconsistent, the returned partial MMR may exhibit undefined behavior.
 91    pub fn from_parts(peaks: MmrPeaks, nodes: NodeMap, track_latest: bool) -> Self {
 92        let forest = peaks.num_leaves();
 93        let peaks = peaks.into();
 94
 95        Self { forest, peaks, nodes, track_latest }
 96    }
 97
 98    // PUBLIC ACCESSORS
 99    // --------------------------------------------------------------------------------------------
100
101    /// Returns the current `forest` of this [PartialMmr].
102    ///
103    /// This value corresponds to the version of the [PartialMmr] and the number of leaves in the
104    /// underlying MMR.
105    pub fn forest(&self) -> usize {
106        self.forest
107    }
108
109    /// Returns the number of leaves in the underlying MMR for this [PartialMmr].
110    pub fn num_leaves(&self) -> usize {
111        self.forest
112    }
113
114    /// Returns the peaks of the MMR for this [PartialMmr].
115    pub fn peaks(&self) -> MmrPeaks {
116        // expect() is OK here because the constructor ensures that MMR peaks can be constructed
117        // correctly
118        MmrPeaks::new(self.forest, self.peaks.clone()).expect("invalid MMR peaks")
119    }
120
121    /// Returns true if this partial MMR tracks an authentication path for the leaf at the
122    /// specified position.
123    pub fn is_tracked(&self, pos: usize) -> bool {
124        if pos >= self.forest {
125            return false;
126        } else if pos == self.forest - 1 && self.forest & 1 != 0 {
127            // if the number of leaves in the MMR is odd and the position is for the last leaf
128            // whether the leaf is tracked is defined by the `track_latest` flag
129            return self.track_latest;
130        }
131
132        let leaf_index = InOrderIndex::from_leaf_pos(pos);
133        self.is_tracked_node(&leaf_index)
134    }
135
136    /// Given a leaf position, returns the Merkle path to its corresponding peak, or None if this
137    /// partial MMR does not track an authentication paths for the specified leaf.
138    ///
139    /// Note: The leaf position is the 0-indexed number corresponding to the order the leaves were
140    /// added, this corresponds to the MMR size _prior_ to adding the element. So the 1st element
141    /// has position 0, the second position 1, and so on.
142    ///
143    /// # Errors
144    /// Returns an error if the specified position is greater-or-equal than the number of leaves
145    /// in the underlying MMR.
146    pub fn open(&self, pos: usize) -> Result<Option<MmrProof>, MmrError> {
147        let tree_bit =
148            leaf_to_corresponding_tree(pos, self.forest).ok_or(MmrError::PositionNotFound(pos))?;
149        let depth = tree_bit as usize;
150
151        let mut nodes = Vec::with_capacity(depth);
152        let mut idx = InOrderIndex::from_leaf_pos(pos);
153
154        while let Some(node) = self.nodes.get(&idx.sibling()) {
155            nodes.push(*node);
156            idx = idx.parent();
157        }
158
159        // If there are nodes then the path must be complete, otherwise it is a bug
160        debug_assert!(nodes.is_empty() || nodes.len() == depth);
161
162        if nodes.len() != depth {
163            // The requested `pos` is not being tracked.
164            Ok(None)
165        } else {
166            Ok(Some(MmrProof {
167                forest: self.forest,
168                position: pos,
169                merkle_path: MerklePath::new(nodes),
170            }))
171        }
172    }
173
174    // ITERATORS
175    // --------------------------------------------------------------------------------------------
176
177    /// Returns an iterator nodes of all authentication paths of this [PartialMmr].
178    pub fn nodes(&self) -> impl Iterator<Item = (&InOrderIndex, &RpoDigest)> {
179        self.nodes.iter()
180    }
181
182    /// Returns an iterator over inner nodes of this [PartialMmr] for the specified leaves.
183    ///
184    /// The order of iteration is not defined. If a leaf is not presented in this partial MMR it
185    /// is silently ignored.
186    pub fn inner_nodes<'a, I: Iterator<Item = (usize, RpoDigest)> + 'a>(
187        &'a self,
188        mut leaves: I,
189    ) -> impl Iterator<Item = InnerNodeInfo> + 'a {
190        let stack = if let Some((pos, leaf)) = leaves.next() {
191            let idx = InOrderIndex::from_leaf_pos(pos);
192            vec![(idx, leaf)]
193        } else {
194            Vec::new()
195        };
196
197        InnerNodeIterator {
198            nodes: &self.nodes,
199            leaves,
200            stack,
201            seen_nodes: BTreeSet::new(),
202        }
203    }
204
205    // STATE MUTATORS
206    // --------------------------------------------------------------------------------------------
207
208    /// Adds a new peak and optionally track it. Returns a vector of the authentication nodes
209    /// inserted into this [PartialMmr] as a result of this operation.
210    ///
211    /// When `track` is `true` the new leaf is tracked.
212    pub fn add(&mut self, leaf: RpoDigest, track: bool) -> Vec<(InOrderIndex, RpoDigest)> {
213        self.forest += 1;
214        let merges = self.forest.trailing_zeros() as usize;
215        let mut new_nodes = Vec::with_capacity(merges);
216
217        let peak = if merges == 0 {
218            self.track_latest = track;
219            leaf
220        } else {
221            let mut track_right = track;
222            let mut track_left = self.track_latest;
223
224            let mut right = leaf;
225            let mut right_idx = forest_to_rightmost_index(self.forest);
226
227            for _ in 0..merges {
228                let left = self.peaks.pop().expect("Missing peak");
229                let left_idx = right_idx.sibling();
230
231                if track_right {
232                    let old = self.nodes.insert(left_idx, left);
233                    new_nodes.push((left_idx, left));
234
235                    debug_assert!(
236                        old.is_none(),
237                        "Idx {:?} already contained an element {:?}",
238                        left_idx,
239                        old
240                    );
241                };
242                if track_left {
243                    let old = self.nodes.insert(right_idx, right);
244                    new_nodes.push((right_idx, right));
245
246                    debug_assert!(
247                        old.is_none(),
248                        "Idx {:?} already contained an element {:?}",
249                        right_idx,
250                        old
251                    );
252                };
253
254                // Update state for the next iteration.
255                // --------------------------------------------------------------------------------
256
257                // This layer is merged, go up one layer.
258                right_idx = right_idx.parent();
259
260                // Merge the current layer. The result is either the right element of the next
261                // merge, or a new peak.
262                right = Rpo256::merge(&[left, right]);
263
264                // This iteration merged the left and right nodes, the new value is always used as
265                // the next iteration's right node. Therefore the tracking flags of this iteration
266                // have to be merged into the right side only.
267                track_right = track_right || track_left;
268
269                // On the next iteration, a peak will be merged. If any of its children are tracked,
270                // then we have to track the left side
271                track_left = self.is_tracked_node(&right_idx.sibling());
272            }
273            right
274        };
275
276        self.peaks.push(peak);
277
278        new_nodes
279    }
280
281    /// Adds the authentication path represented by [MerklePath] if it is valid.
282    ///
283    /// The `leaf_pos` refers to the global position of the leaf in the MMR, these are 0-indexed
284    /// values assigned in a strictly monotonic fashion as elements are inserted into the MMR,
285    /// this value corresponds to the values used in the MMR structure.
286    ///
287    /// The `leaf` corresponds to the value at `leaf_pos`, and `path` is the authentication path for
288    /// that element up to its corresponding Mmr peak. The `leaf` is only used to compute the root
289    /// from the authentication path to valid the data, only the authentication data is saved in
290    /// the structure. If the value is required it should be stored out-of-band.
291    pub fn track(
292        &mut self,
293        leaf_pos: usize,
294        leaf: RpoDigest,
295        path: &MerklePath,
296    ) -> Result<(), MmrError> {
297        // Checks there is a tree with same depth as the authentication path, if not the path is
298        // invalid.
299        let tree = 1 << path.depth();
300        if tree & self.forest == 0 {
301            return Err(MmrError::UnknownPeak(path.depth()));
302        };
303
304        if leaf_pos + 1 == self.forest
305            && path.depth() == 0
306            && self.peaks.last().is_some_and(|v| *v == leaf)
307        {
308            self.track_latest = true;
309            return Ok(());
310        }
311
312        // ignore the trees smaller than the target (these elements are position after the current
313        // target and don't affect the target leaf_pos)
314        let target_forest = self.forest ^ (self.forest & (tree - 1));
315        let peak_pos = (target_forest.count_ones() - 1) as usize;
316
317        // translate from mmr leaf_pos to merkle path
318        let path_idx = leaf_pos - (target_forest ^ tree);
319
320        // Compute the root of the authentication path, and check it matches the current version of
321        // the PartialMmr.
322        let computed = path
323            .compute_root(path_idx as u64, leaf)
324            .map_err(MmrError::MerkleRootComputationFailed)?;
325        if self.peaks[peak_pos] != computed {
326            return Err(MmrError::PeakPathMismatch);
327        }
328
329        let mut idx = InOrderIndex::from_leaf_pos(leaf_pos);
330        for leaf in path.nodes() {
331            self.nodes.insert(idx.sibling(), *leaf);
332            idx = idx.parent();
333        }
334
335        Ok(())
336    }
337
338    /// Removes a leaf of the [PartialMmr] and the unused nodes from the authentication path.
339    ///
340    /// Note: `leaf_pos` corresponds to the position in the MMR and not on an individual tree.
341    pub fn untrack(&mut self, leaf_pos: usize) {
342        let mut idx = InOrderIndex::from_leaf_pos(leaf_pos);
343
344        self.nodes.remove(&idx.sibling());
345
346        // `idx` represent the element that can be computed by the authentication path, because
347        // these elements can be computed they are not saved for the authentication of the current
348        // target. In other words, if the idx is present it was added for the authentication of
349        // another element, and no more elements should be removed otherwise it would remove that
350        // element's authentication data.
351        while !self.nodes.contains_key(&idx) {
352            idx = idx.parent();
353            self.nodes.remove(&idx.sibling());
354        }
355    }
356
357    /// Applies updates to this [PartialMmr] and returns a vector of new authentication nodes
358    /// inserted into the partial MMR.
359    pub fn apply(&mut self, delta: MmrDelta) -> Result<Vec<(InOrderIndex, RpoDigest)>, MmrError> {
360        if delta.forest < self.forest {
361            return Err(MmrError::InvalidPeaks(format!(
362                "forest of mmr delta {} is less than current forest {}",
363                delta.forest, self.forest
364            )));
365        }
366
367        let mut inserted_nodes = Vec::new();
368
369        if delta.forest == self.forest {
370            if !delta.data.is_empty() {
371                return Err(MmrError::InvalidUpdate);
372            }
373
374            return Ok(inserted_nodes);
375        }
376
377        // find the tree merges
378        let changes = self.forest ^ delta.forest;
379        let largest = 1 << changes.ilog2();
380        let merges = self.forest & (largest - 1);
381
382        debug_assert!(
383            !self.track_latest || (merges & 1) == 1,
384            "if there is an odd element, a merge is required"
385        );
386
387        // count the number elements needed to produce largest from the current state
388        let (merge_count, new_peaks) = if merges != 0 {
389            let depth = largest.trailing_zeros();
390            let skipped = merges.trailing_zeros();
391            let computed = merges.count_ones() - 1;
392            let merge_count = depth - skipped - computed;
393
394            let new_peaks = delta.forest & (largest - 1);
395
396            (merge_count, new_peaks)
397        } else {
398            (0, changes)
399        };
400
401        // verify the delta size
402        if (delta.data.len() as u32) != merge_count + new_peaks.count_ones() {
403            return Err(MmrError::InvalidUpdate);
404        }
405
406        // keeps track of how many data elements from the update have been consumed
407        let mut update_count = 0;
408
409        if merges != 0 {
410            // starts at the smallest peak and follows the merged peaks
411            let mut peak_idx = forest_to_root_index(self.forest);
412
413            // match order of the update data while applying it
414            self.peaks.reverse();
415
416            // set to true when the data is needed for authentication paths updates
417            let mut track = self.track_latest;
418            self.track_latest = false;
419
420            let mut peak_count = 0;
421            let mut target = 1 << merges.trailing_zeros();
422            let mut new = delta.data[0];
423            update_count += 1;
424
425            while target < largest {
426                // check if either the left or right subtrees have saved for authentication paths.
427                // If so, turn tracking on to update those paths.
428                if target != 1 && !track {
429                    track = self.is_tracked_node(&peak_idx);
430                }
431
432                // update data only contains the nodes from the right subtrees, left nodes are
433                // either previously known peaks or computed values
434                let (left, right) = if target & merges != 0 {
435                    let peak = self.peaks[peak_count];
436                    let sibling_idx = peak_idx.sibling();
437
438                    // if the sibling peak is tracked, add this peaks to the set of
439                    // authentication nodes
440                    if self.is_tracked_node(&sibling_idx) {
441                        self.nodes.insert(peak_idx, new);
442                        inserted_nodes.push((peak_idx, new));
443                    }
444                    peak_count += 1;
445                    (peak, new)
446                } else {
447                    let update = delta.data[update_count];
448                    update_count += 1;
449                    (new, update)
450                };
451
452                if track {
453                    let sibling_idx = peak_idx.sibling();
454                    if peak_idx.is_left_child() {
455                        self.nodes.insert(sibling_idx, right);
456                        inserted_nodes.push((sibling_idx, right));
457                    } else {
458                        self.nodes.insert(sibling_idx, left);
459                        inserted_nodes.push((sibling_idx, left));
460                    }
461                }
462
463                peak_idx = peak_idx.parent();
464                new = Rpo256::merge(&[left, right]);
465                target <<= 1;
466            }
467
468            debug_assert!(peak_count == (merges.count_ones() as usize));
469
470            // restore the peaks order
471            self.peaks.reverse();
472            // remove the merged peaks
473            self.peaks.truncate(self.peaks.len() - peak_count);
474            // add the newly computed peak, the result of the merges
475            self.peaks.push(new);
476        }
477
478        // The rest of the update data is composed of peaks. None of these elements can contain
479        // tracked elements because the peaks were unknown, and it is not possible to add elements
480        // for tacking without authenticating it to a peak.
481        self.peaks.extend_from_slice(&delta.data[update_count..]);
482        self.forest = delta.forest;
483
484        debug_assert!(self.peaks.len() == (self.forest.count_ones() as usize));
485
486        Ok(inserted_nodes)
487    }
488
489    // HELPER METHODS
490    // --------------------------------------------------------------------------------------------
491
492    /// Returns true if this [PartialMmr] tracks authentication path for the node at the specified
493    /// index.
494    fn is_tracked_node(&self, node_index: &InOrderIndex) -> bool {
495        if node_index.is_leaf() {
496            self.nodes.contains_key(&node_index.sibling())
497        } else {
498            let left_child = node_index.left_child();
499            let right_child = node_index.right_child();
500            self.nodes.contains_key(&left_child) | self.nodes.contains_key(&right_child)
501        }
502    }
503}
504
505// CONVERSIONS
506// ================================================================================================
507
508impl From<MmrPeaks> for PartialMmr {
509    fn from(peaks: MmrPeaks) -> Self {
510        Self::from_peaks(peaks)
511    }
512}
513
514impl From<PartialMmr> for MmrPeaks {
515    fn from(partial_mmr: PartialMmr) -> Self {
516        // Safety: the [PartialMmr] maintains the constraints the number of true bits in the forest
517        // matches the number of peaks, as required by the [MmrPeaks]
518        MmrPeaks::new(partial_mmr.forest, partial_mmr.peaks).unwrap()
519    }
520}
521
522impl From<&MmrPeaks> for PartialMmr {
523    fn from(peaks: &MmrPeaks) -> Self {
524        Self::from_peaks(peaks.clone())
525    }
526}
527
528impl From<&PartialMmr> for MmrPeaks {
529    fn from(partial_mmr: &PartialMmr) -> Self {
530        // Safety: the [PartialMmr] maintains the constraints the number of true bits in the forest
531        // matches the number of peaks, as required by the [MmrPeaks]
532        MmrPeaks::new(partial_mmr.forest, partial_mmr.peaks.clone()).unwrap()
533    }
534}
535
536// ITERATORS
537// ================================================================================================
538
539/// An iterator over every inner node of the [PartialMmr].
540pub struct InnerNodeIterator<'a, I: Iterator<Item = (usize, RpoDigest)>> {
541    nodes: &'a NodeMap,
542    leaves: I,
543    stack: Vec<(InOrderIndex, RpoDigest)>,
544    seen_nodes: BTreeSet<InOrderIndex>,
545}
546
547impl<I: Iterator<Item = (usize, RpoDigest)>> Iterator for InnerNodeIterator<'_, I> {
548    type Item = InnerNodeInfo;
549
550    fn next(&mut self) -> Option<Self::Item> {
551        while let Some((idx, node)) = self.stack.pop() {
552            let parent_idx = idx.parent();
553            let new_node = self.seen_nodes.insert(parent_idx);
554
555            // if we haven't seen this node's parent before, and the node has a sibling, return
556            // the inner node defined by the parent of this node, and move up the branch
557            if new_node {
558                if let Some(sibling) = self.nodes.get(&idx.sibling()) {
559                    let (left, right) = if parent_idx.left_child() == idx {
560                        (node, *sibling)
561                    } else {
562                        (*sibling, node)
563                    };
564                    let parent = Rpo256::merge(&[left, right]);
565                    let inner_node = InnerNodeInfo { value: parent, left, right };
566
567                    self.stack.push((parent_idx, parent));
568                    return Some(inner_node);
569                }
570            }
571
572            // the previous leaf has been processed, try to process the next leaf
573            if let Some((pos, leaf)) = self.leaves.next() {
574                let idx = InOrderIndex::from_leaf_pos(pos);
575                self.stack.push((idx, leaf));
576            }
577        }
578
579        None
580    }
581}
582
583impl Serializable for PartialMmr {
584    fn write_into<W: winter_utils::ByteWriter>(&self, target: &mut W) {
585        self.forest.write_into(target);
586        self.peaks.write_into(target);
587        self.nodes.write_into(target);
588        target.write_bool(self.track_latest);
589    }
590}
591
592impl Deserializable for PartialMmr {
593    fn read_from<R: winter_utils::ByteReader>(
594        source: &mut R,
595    ) -> Result<Self, winter_utils::DeserializationError> {
596        let forest = usize::read_from(source)?;
597        let peaks = Vec::<RpoDigest>::read_from(source)?;
598        let nodes = NodeMap::read_from(source)?;
599        let track_latest = source.read_bool()?;
600
601        Ok(Self { forest, peaks, nodes, track_latest })
602    }
603}
604
605// UTILS
606// ================================================================================================
607
608/// Given the description of a `forest`, returns the index of the root element of the smallest tree
609/// in it.
610fn forest_to_root_index(forest: usize) -> InOrderIndex {
611    // Count total size of all trees in the forest.
612    let nodes = nodes_in_forest(forest);
613
614    // Add the count for the parent nodes that separate each tree. These are allocated but
615    // currently empty, and correspond to the nodes that will be used once the trees are merged.
616    let open_trees = (forest.count_ones() - 1) as usize;
617
618    // Remove the count of the right subtree of the target tree, target tree root index comes
619    // before the subtree for the in-order tree walk.
620    let right_subtree_count = ((1u32 << forest.trailing_zeros()) - 1) as usize;
621
622    let idx = nodes + open_trees - right_subtree_count;
623
624    InOrderIndex::new(idx.try_into().unwrap())
625}
626
627/// Given the description of a `forest`, returns the index of the right most element.
628fn forest_to_rightmost_index(forest: usize) -> InOrderIndex {
629    // Count total size of all trees in the forest.
630    let nodes = nodes_in_forest(forest);
631
632    // Add the count for the parent nodes that separate each tree. These are allocated but
633    // currently empty, and correspond to the nodes that will be used once the trees are merged.
634    let open_trees = (forest.count_ones() - 1) as usize;
635
636    let idx = nodes + open_trees;
637
638    InOrderIndex::new(idx.try_into().unwrap())
639}
640
641// TESTS
642// ================================================================================================
643
644#[cfg(test)]
645mod tests {
646    use alloc::{collections::BTreeSet, vec::Vec};
647
648    use winter_utils::{Deserializable, Serializable};
649
650    use super::{
651        forest_to_rightmost_index, forest_to_root_index, InOrderIndex, MmrPeaks, PartialMmr,
652        RpoDigest,
653    };
654    use crate::merkle::{int_to_node, MerkleStore, Mmr, NodeIndex};
655
656    const LEAVES: [RpoDigest; 7] = [
657        int_to_node(0),
658        int_to_node(1),
659        int_to_node(2),
660        int_to_node(3),
661        int_to_node(4),
662        int_to_node(5),
663        int_to_node(6),
664    ];
665
666    #[test]
667    fn test_forest_to_root_index() {
668        fn idx(pos: usize) -> InOrderIndex {
669            InOrderIndex::new(pos.try_into().unwrap())
670        }
671
672        // When there is a single tree in the forest, the index is equivalent to the number of
673        // leaves in that tree, which is `2^n`.
674        assert_eq!(forest_to_root_index(0b0001), idx(1));
675        assert_eq!(forest_to_root_index(0b0010), idx(2));
676        assert_eq!(forest_to_root_index(0b0100), idx(4));
677        assert_eq!(forest_to_root_index(0b1000), idx(8));
678
679        assert_eq!(forest_to_root_index(0b0011), idx(5));
680        assert_eq!(forest_to_root_index(0b0101), idx(9));
681        assert_eq!(forest_to_root_index(0b1001), idx(17));
682        assert_eq!(forest_to_root_index(0b0111), idx(13));
683        assert_eq!(forest_to_root_index(0b1011), idx(21));
684        assert_eq!(forest_to_root_index(0b1111), idx(29));
685
686        assert_eq!(forest_to_root_index(0b0110), idx(10));
687        assert_eq!(forest_to_root_index(0b1010), idx(18));
688        assert_eq!(forest_to_root_index(0b1100), idx(20));
689        assert_eq!(forest_to_root_index(0b1110), idx(26));
690    }
691
692    #[test]
693    fn test_forest_to_rightmost_index() {
694        fn idx(pos: usize) -> InOrderIndex {
695            InOrderIndex::new(pos.try_into().unwrap())
696        }
697
698        for forest in 1..256 {
699            assert!(forest_to_rightmost_index(forest).inner() % 2 == 1, "Leaves are always odd");
700        }
701
702        assert_eq!(forest_to_rightmost_index(0b0001), idx(1));
703        assert_eq!(forest_to_rightmost_index(0b0010), idx(3));
704        assert_eq!(forest_to_rightmost_index(0b0011), idx(5));
705        assert_eq!(forest_to_rightmost_index(0b0100), idx(7));
706        assert_eq!(forest_to_rightmost_index(0b0101), idx(9));
707        assert_eq!(forest_to_rightmost_index(0b0110), idx(11));
708        assert_eq!(forest_to_rightmost_index(0b0111), idx(13));
709        assert_eq!(forest_to_rightmost_index(0b1000), idx(15));
710        assert_eq!(forest_to_rightmost_index(0b1001), idx(17));
711        assert_eq!(forest_to_rightmost_index(0b1010), idx(19));
712        assert_eq!(forest_to_rightmost_index(0b1011), idx(21));
713        assert_eq!(forest_to_rightmost_index(0b1100), idx(23));
714        assert_eq!(forest_to_rightmost_index(0b1101), idx(25));
715        assert_eq!(forest_to_rightmost_index(0b1110), idx(27));
716        assert_eq!(forest_to_rightmost_index(0b1111), idx(29));
717    }
718
719    #[test]
720    fn test_partial_mmr_apply_delta() {
721        // build an MMR with 10 nodes (2 peaks) and a partial MMR based on it
722        let mut mmr = Mmr::default();
723        (0..10).for_each(|i| mmr.add(int_to_node(i)));
724        let mut partial_mmr: PartialMmr = mmr.peaks().into();
725
726        // add authentication path for position 1 and 8
727        {
728            let node = mmr.get(1).unwrap();
729            let proof = mmr.open(1).unwrap();
730            partial_mmr.track(1, node, &proof.merkle_path).unwrap();
731        }
732
733        {
734            let node = mmr.get(8).unwrap();
735            let proof = mmr.open(8).unwrap();
736            partial_mmr.track(8, node, &proof.merkle_path).unwrap();
737        }
738
739        // add 2 more nodes into the MMR and validate apply_delta()
740        (10..12).for_each(|i| mmr.add(int_to_node(i)));
741        validate_apply_delta(&mmr, &mut partial_mmr);
742
743        // add 1 more node to the MMR, validate apply_delta() and start tracking the node
744        mmr.add(int_to_node(12));
745        validate_apply_delta(&mmr, &mut partial_mmr);
746        {
747            let node = mmr.get(12).unwrap();
748            let proof = mmr.open(12).unwrap();
749            partial_mmr.track(12, node, &proof.merkle_path).unwrap();
750            assert!(partial_mmr.track_latest);
751        }
752
753        // by this point we are tracking authentication paths for positions: 1, 8, and 12
754
755        // add 3 more nodes to the MMR (collapses to 1 peak) and validate apply_delta()
756        (13..16).for_each(|i| mmr.add(int_to_node(i)));
757        validate_apply_delta(&mmr, &mut partial_mmr);
758    }
759
760    fn validate_apply_delta(mmr: &Mmr, partial: &mut PartialMmr) {
761        let tracked_leaves = partial
762            .nodes
763            .iter()
764            .filter_map(|(index, _)| if index.is_leaf() { Some(index.sibling()) } else { None })
765            .collect::<Vec<_>>();
766        let nodes_before = partial.nodes.clone();
767
768        // compute and apply delta
769        let delta = mmr.get_delta(partial.forest(), mmr.forest()).unwrap();
770        let nodes_delta = partial.apply(delta).unwrap();
771
772        // new peaks were computed correctly
773        assert_eq!(mmr.peaks(), partial.peaks());
774
775        let mut expected_nodes = nodes_before;
776        for (key, value) in nodes_delta {
777            // nodes should not be duplicated
778            assert!(expected_nodes.insert(key, value).is_none());
779        }
780
781        // new nodes should be a combination of original nodes and delta
782        assert_eq!(expected_nodes, partial.nodes);
783
784        // make sure tracked leaves open to the same proofs as in the underlying MMR
785        for index in tracked_leaves {
786            let index_value: u64 = index.into();
787            let pos = index_value / 2;
788            let proof1 = partial.open(pos as usize).unwrap().unwrap();
789            let proof2 = mmr.open(pos as usize).unwrap();
790            assert_eq!(proof1, proof2);
791        }
792    }
793
794    #[test]
795    fn test_partial_mmr_inner_nodes_iterator() {
796        // build the MMR
797        let mmr: Mmr = LEAVES.into();
798        let first_peak = mmr.peaks().peaks()[0];
799
800        // -- test single tree ----------------------------
801
802        // get path and node for position 1
803        let node1 = mmr.get(1).unwrap();
804        let proof1 = mmr.open(1).unwrap();
805
806        // create partial MMR and add authentication path to node at position 1
807        let mut partial_mmr: PartialMmr = mmr.peaks().into();
808        partial_mmr.track(1, node1, &proof1.merkle_path).unwrap();
809
810        // empty iterator should have no nodes
811        assert_eq!(partial_mmr.inner_nodes([].iter().cloned()).next(), None);
812
813        // build Merkle store from authentication paths in partial MMR
814        let mut store: MerkleStore = MerkleStore::new();
815        store.extend(partial_mmr.inner_nodes([(1, node1)].iter().cloned()));
816
817        let index1 = NodeIndex::new(2, 1).unwrap();
818        let path1 = store.get_path(first_peak, index1).unwrap().path;
819
820        assert_eq!(path1, proof1.merkle_path);
821
822        // -- test no duplicates --------------------------
823
824        // build the partial MMR
825        let mut partial_mmr: PartialMmr = mmr.peaks().into();
826
827        let node0 = mmr.get(0).unwrap();
828        let proof0 = mmr.open(0).unwrap();
829
830        let node2 = mmr.get(2).unwrap();
831        let proof2 = mmr.open(2).unwrap();
832
833        partial_mmr.track(0, node0, &proof0.merkle_path).unwrap();
834        partial_mmr.track(1, node1, &proof1.merkle_path).unwrap();
835        partial_mmr.track(2, node2, &proof2.merkle_path).unwrap();
836
837        // make sure there are no duplicates
838        let leaves = [(0, node0), (1, node1), (2, node2)];
839        let mut nodes = BTreeSet::new();
840        for node in partial_mmr.inner_nodes(leaves.iter().cloned()) {
841            assert!(nodes.insert(node.value));
842        }
843
844        // and also that the store is still be built correctly
845        store.extend(partial_mmr.inner_nodes(leaves.iter().cloned()));
846
847        let index0 = NodeIndex::new(2, 0).unwrap();
848        let index1 = NodeIndex::new(2, 1).unwrap();
849        let index2 = NodeIndex::new(2, 2).unwrap();
850
851        let path0 = store.get_path(first_peak, index0).unwrap().path;
852        let path1 = store.get_path(first_peak, index1).unwrap().path;
853        let path2 = store.get_path(first_peak, index2).unwrap().path;
854
855        assert_eq!(path0, proof0.merkle_path);
856        assert_eq!(path1, proof1.merkle_path);
857        assert_eq!(path2, proof2.merkle_path);
858
859        // -- test multiple trees -------------------------
860
861        // build the partial MMR
862        let mut partial_mmr: PartialMmr = mmr.peaks().into();
863
864        let node5 = mmr.get(5).unwrap();
865        let proof5 = mmr.open(5).unwrap();
866
867        partial_mmr.track(1, node1, &proof1.merkle_path).unwrap();
868        partial_mmr.track(5, node5, &proof5.merkle_path).unwrap();
869
870        // build Merkle store from authentication paths in partial MMR
871        let mut store: MerkleStore = MerkleStore::new();
872        store.extend(partial_mmr.inner_nodes([(1, node1), (5, node5)].iter().cloned()));
873
874        let index1 = NodeIndex::new(2, 1).unwrap();
875        let index5 = NodeIndex::new(1, 1).unwrap();
876
877        let second_peak = mmr.peaks().peaks()[1];
878
879        let path1 = store.get_path(first_peak, index1).unwrap().path;
880        let path5 = store.get_path(second_peak, index5).unwrap().path;
881
882        assert_eq!(path1, proof1.merkle_path);
883        assert_eq!(path5, proof5.merkle_path);
884    }
885
886    #[test]
887    fn test_partial_mmr_add_without_track() {
888        let mut mmr = Mmr::default();
889        let empty_peaks = MmrPeaks::new(0, vec![]).unwrap();
890        let mut partial_mmr = PartialMmr::from_peaks(empty_peaks);
891
892        for el in (0..256).map(int_to_node) {
893            mmr.add(el);
894            partial_mmr.add(el, false);
895
896            assert_eq!(mmr.peaks(), partial_mmr.peaks());
897            assert_eq!(mmr.forest(), partial_mmr.forest());
898        }
899    }
900
901    #[test]
902    fn test_partial_mmr_add_with_track() {
903        let mut mmr = Mmr::default();
904        let empty_peaks = MmrPeaks::new(0, vec![]).unwrap();
905        let mut partial_mmr = PartialMmr::from_peaks(empty_peaks);
906
907        for i in 0..256 {
908            let el = int_to_node(i);
909            mmr.add(el);
910            partial_mmr.add(el, true);
911
912            assert_eq!(mmr.peaks(), partial_mmr.peaks());
913            assert_eq!(mmr.forest(), partial_mmr.forest());
914
915            for pos in 0..i {
916                let mmr_proof = mmr.open(pos as usize).unwrap();
917                let partialmmr_proof = partial_mmr.open(pos as usize).unwrap().unwrap();
918                assert_eq!(mmr_proof, partialmmr_proof);
919            }
920        }
921    }
922
923    #[test]
924    fn test_partial_mmr_add_existing_track() {
925        let mut mmr = Mmr::from((0..7).map(int_to_node));
926
927        // derive a partial Mmr from it which tracks authentication path to leaf 5
928        let mut partial_mmr = PartialMmr::from_peaks(mmr.peaks());
929        let path_to_5 = mmr.open(5).unwrap().merkle_path;
930        let leaf_at_5 = mmr.get(5).unwrap();
931        partial_mmr.track(5, leaf_at_5, &path_to_5).unwrap();
932
933        // add a new leaf to both Mmr and partial Mmr
934        let leaf_at_7 = int_to_node(7);
935        mmr.add(leaf_at_7);
936        partial_mmr.add(leaf_at_7, false);
937
938        // the openings should be the same
939        assert_eq!(mmr.open(5).unwrap(), partial_mmr.open(5).unwrap().unwrap());
940    }
941
942    #[test]
943    fn test_partial_mmr_serialization() {
944        let mmr = Mmr::from((0..7).map(int_to_node));
945        let partial_mmr = PartialMmr::from_peaks(mmr.peaks());
946
947        let bytes = partial_mmr.to_bytes();
948        let decoded = PartialMmr::read_from_bytes(&bytes).unwrap();
949
950        assert_eq!(partial_mmr, decoded);
951    }
952}