arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/mmr/full.rs
src/merkle/mmr/full.rsRaw
  1//! A fully materialized Merkle mountain range (MMR).
  2//!
  3//! A MMR is a forest structure, i.e. it is an ordered set of disjoint rooted trees. The trees are
  4//! ordered by size, from the most to least number of leaves. Every tree is a perfect binary tree,
  5//! meaning a tree has all its leaves at the same depth, and every inner node has a branch-factor
  6//! of 2 with both children set.
  7//!
  8//! Additionally the structure only supports adding leaves to the right-most tree, the one with the
  9//! least number of leaves. The structure preserves the invariant that each tree has different
 10//! depths, i.e. as part of adding adding a new element to the forest the trees with same depth are
 11//! merged, creating a new tree with depth d+1, this process is continued until the property is
 12//! restabilished.
 13use super::{
 14    super::{InnerNodeInfo, MerklePath, RpoDigest, Vec},
 15    bit::TrueBitPositionIterator,
 16    MmrPeaks, MmrProof, Rpo256,
 17};
 18use core::fmt::{Display, Formatter};
 19
 20#[cfg(feature = "std")]
 21use std::error::Error;
 22
 23// MMR
 24// ===============================================================================================
 25
 26/// A fully materialized Merkle Mountain Range, with every tree in the forest and all their
 27/// elements.
 28///
 29/// Since this is a full representation of the MMR, elements are never removed and the MMR will
 30/// grow roughly `O(2n)` in number of leaf elements.
 31#[derive(Debug, Clone)]
 32pub struct Mmr {
 33    /// Refer to the `forest` method documentation for details of the semantics of this value.
 34    pub(super) forest: usize,
 35
 36    /// Contains every element of the forest.
 37    ///
 38    /// The trees are in postorder sequential representation. This representation allows for all
 39    /// the elements of every tree in the forest to be stored in the same sequential buffer. It
 40    /// also means new elements can be added to the forest, and merging of trees is very cheap with
 41    /// no need to copy elements.
 42    pub(super) nodes: Vec<RpoDigest>,
 43}
 44
 45#[derive(Debug, PartialEq, Eq, Copy, Clone)]
 46pub enum MmrError {
 47    InvalidPosition(usize),
 48}
 49
 50impl Display for MmrError {
 51    fn fmt(&self, fmt: &mut Formatter<'_>) -> Result<(), core::fmt::Error> {
 52        match self {
 53            MmrError::InvalidPosition(pos) => write!(fmt, "Mmr does not contain position {pos}"),
 54        }
 55    }
 56}
 57
 58#[cfg(feature = "std")]
 59impl Error for MmrError {}
 60
 61impl Default for Mmr {
 62    fn default() -> Self {
 63        Self::new()
 64    }
 65}
 66
 67impl Mmr {
 68    // CONSTRUCTORS
 69    // ============================================================================================
 70
 71    /// Constructor for an empty `Mmr`.
 72    pub fn new() -> Mmr {
 73        Mmr {
 74            forest: 0,
 75            nodes: Vec::new(),
 76        }
 77    }
 78
 79    // ACCESSORS
 80    // ============================================================================================
 81
 82    /// Returns the MMR forest representation.
 83    ///
 84    /// The forest value has the following interpretations:
 85    /// - its value is the number of elements in the forest
 86    /// - bit count corresponds to the number of trees in the forest
 87    /// - each true bit position determines the depth of a tree in the forest
 88    pub const fn forest(&self) -> usize {
 89        self.forest
 90    }
 91
 92    // FUNCTIONALITY
 93    // ============================================================================================
 94
 95    /// Given a leaf position, returns the Merkle path to its corresponding peak. If the position
 96    /// is greater-or-equal than the tree size an error is returned.
 97    ///
 98    /// Note: The leaf position is the 0-indexed number corresponding to the order the leaves were
 99    /// added, this corresponds to the MMR size _prior_ to adding the element. So the 1st element
100    /// has position 0, the second position 1, and so on.
101    pub fn open(&self, pos: usize) -> Result<MmrProof, MmrError> {
102        // find the target tree responsible for the MMR position
103        let tree_bit =
104            leaf_to_corresponding_tree(pos, self.forest).ok_or(MmrError::InvalidPosition(pos))?;
105        let forest_target = 1usize << tree_bit;
106
107        // isolate the trees before the target
108        let forest_before = self.forest & high_bitmask(tree_bit + 1);
109        let index_offset = nodes_in_forest(forest_before);
110
111        // find the root
112        let index = nodes_in_forest(forest_target) - 1;
113
114        // update the value position from global to the target tree
115        let relative_pos = pos - forest_before;
116
117        // collect the path and the final index of the target value
118        let (_, path) =
119            self.collect_merkle_path_and_value(tree_bit, relative_pos, index_offset, index);
120
121        Ok(MmrProof {
122            forest: self.forest,
123            position: pos,
124            merkle_path: MerklePath::new(path),
125        })
126    }
127
128    /// Returns the leaf value at position `pos`.
129    ///
130    /// Note: The leaf position is the 0-indexed number corresponding to the order the leaves were
131    /// added, this corresponds to the MMR size _prior_ to adding the element. So the 1st element
132    /// has position 0, the second position 1, and so on.
133    pub fn get(&self, pos: usize) -> Result<RpoDigest, MmrError> {
134        // find the target tree responsible for the MMR position
135        let tree_bit =
136            leaf_to_corresponding_tree(pos, self.forest).ok_or(MmrError::InvalidPosition(pos))?;
137        let forest_target = 1usize << tree_bit;
138
139        // isolate the trees before the target
140        let forest_before = self.forest & high_bitmask(tree_bit + 1);
141        let index_offset = nodes_in_forest(forest_before);
142
143        // find the root
144        let index = nodes_in_forest(forest_target) - 1;
145
146        // update the value position from global to the target tree
147        let relative_pos = pos - forest_before;
148
149        // collect the path and the final index of the target value
150        let (value, _) =
151            self.collect_merkle_path_and_value(tree_bit, relative_pos, index_offset, index);
152
153        Ok(value)
154    }
155
156    /// Adds a new element to the MMR.
157    pub fn add(&mut self, el: RpoDigest) {
158        // Note: every node is also a tree of size 1, adding an element to the forest creates a new
159        // rooted-tree of size 1. This may temporarily break the invariant that every tree in the
160        // forest has different sizes, the loop below will eagerly merge trees of same size and
161        // restore the invariant.
162        self.nodes.push(el);
163
164        let mut left_offset = self.nodes.len().saturating_sub(2);
165        let mut right = el;
166        let mut left_tree = 1;
167        while self.forest & left_tree != 0 {
168            right = Rpo256::merge(&[self.nodes[left_offset], right]);
169            self.nodes.push(right);
170
171            left_offset = left_offset.saturating_sub(nodes_in_forest(left_tree));
172            left_tree <<= 1;
173        }
174
175        self.forest += 1;
176    }
177
178    /// Returns an accumulator representing the current state of the MMR.
179    pub fn accumulator(&self) -> MmrPeaks {
180        let peaks: Vec<RpoDigest> = TrueBitPositionIterator::new(self.forest)
181            .rev()
182            .map(|bit| nodes_in_forest(1 << bit))
183            .scan(0, |offset, el| {
184                *offset += el;
185                Some(*offset)
186            })
187            .map(|offset| self.nodes[offset - 1])
188            .collect();
189
190        MmrPeaks {
191            num_leaves: self.forest,
192            peaks,
193        }
194    }
195
196    /// An iterator over inner nodes in the MMR. The order of iteration is unspecified.
197    pub fn inner_nodes(&self) -> MmrNodes {
198        MmrNodes {
199            mmr: self,
200            forest: 0,
201            last_right: 0,
202            index: 0,
203        }
204    }
205
206    // UTILITIES
207    // ============================================================================================
208
209    /// Internal function used to collect the Merkle path of a value.
210    fn collect_merkle_path_and_value(
211        &self,
212        tree_bit: u32,
213        relative_pos: usize,
214        index_offset: usize,
215        mut index: usize,
216    ) -> (RpoDigest, Vec<RpoDigest>) {
217        // collect the Merkle path
218        let mut tree_depth = tree_bit as usize;
219        let mut path = Vec::with_capacity(tree_depth + 1);
220        while tree_depth > 0 {
221            let bit = relative_pos & tree_depth;
222            let right_offset = index - 1;
223            let left_offset = right_offset - nodes_in_forest(tree_depth);
224
225            // Elements to the right have a higher position because they were
226            // added later. Therefore when the bit is true the node's path is
227            // to the right, and its sibling to the left.
228            let sibling = if bit != 0 {
229                index = right_offset;
230                self.nodes[index_offset + left_offset]
231            } else {
232                index = left_offset;
233                self.nodes[index_offset + right_offset]
234            };
235
236            tree_depth >>= 1;
237            path.push(sibling);
238        }
239
240        // the rest of the codebase has the elements going from leaf to root, adjust it here for
241        // easy of use/consistency sake
242        path.reverse();
243
244        let value = self.nodes[index_offset + index];
245        (value, path)
246    }
247}
248
249impl<T> From<T> for Mmr
250where
251    T: IntoIterator<Item = RpoDigest>,
252{
253    fn from(values: T) -> Self {
254        let mut mmr = Mmr::new();
255        for v in values {
256            mmr.add(v)
257        }
258        mmr
259    }
260}
261
262// ITERATOR
263// ===============================================================================================
264
265/// Yields inner nodes of the [Mmr].
266pub struct MmrNodes<'a> {
267    /// [Mmr] being yielded, when its `forest` value is matched, the iterations is finished.
268    mmr: &'a Mmr,
269    /// Keeps track of the left nodes yielded so far waiting for a right pair, this matches the
270    /// semantics of the [Mmr]'s forest attribute, since that too works as a buffer of left nodes
271    /// waiting for a pair to be hashed together.
272    forest: usize,
273    /// Keeps track of the last right node yielded, after this value is set, the next iteration
274    /// will be its parent with its corresponding left node that has been yield already.
275    last_right: usize,
276    /// The current index in the `nodes` vector.
277    index: usize,
278}
279
280impl<'a> Iterator for MmrNodes<'a> {
281    type Item = InnerNodeInfo;
282
283    fn next(&mut self) -> Option<Self::Item> {
284        debug_assert!(self.last_right.count_ones() <= 1, "last_right tracks zero or one element");
285
286        // only parent nodes are emitted, remove the single node tree from the forest
287        let target = self.mmr.forest & (usize::MAX << 1);
288
289        if self.forest < target {
290            if self.last_right == 0 {
291                // yield the left leaf
292                debug_assert!(self.last_right == 0, "left must be before right");
293                self.forest |= 1;
294                self.index += 1;
295
296                // yield the right leaf
297                debug_assert!((self.forest & 1) == 1, "right must be after left");
298                self.last_right |= 1;
299                self.index += 1;
300            };
301
302            debug_assert!(
303                self.forest & self.last_right != 0,
304                "parent requires both a left and right",
305            );
306
307            // compute the number of nodes in the right tree, this is the offset to the
308            // previous left parent
309            let right_nodes = nodes_in_forest(self.last_right);
310            // the next parent position is one above the position of the pair
311            let parent = self.last_right << 1;
312
313            // the left node has been paired and the current parent yielded, removed it from the forest
314            self.forest ^= self.last_right;
315            if self.forest & parent == 0 {
316                // this iteration yielded the left parent node
317                debug_assert!(self.forest & 1 == 0, "next iteration yields a left leaf");
318                self.last_right = 0;
319                self.forest ^= parent;
320            } else {
321                // the left node of the parent level has been yielded already, this iteration
322                // was the right parent. Next iteration yields their parent.
323                self.last_right = parent;
324            }
325
326            // yields a parent
327            let value = self.mmr.nodes[self.index];
328            let right = self.mmr.nodes[self.index - 1];
329            let left = self.mmr.nodes[self.index - 1 - right_nodes];
330            self.index += 1;
331            let node = InnerNodeInfo { value, left, right };
332
333            Some(node)
334        } else {
335            None
336        }
337    }
338}
339
340// UTILITIES
341// ===============================================================================================
342
343/// Given a 0-indexed leaf position and the current forest, return the tree number responsible for
344/// the position.
345///
346/// Note:
347/// The result is a tree position `p`, it has the following interpretations. $p+1$ is the depth of
348/// the tree, which corresponds to the size of a Merkle proof for that tree. $2^p$ is equal to the
349/// number of leaves in this particular tree. and $2^(p+1)-1$ corresponds to size of the tree.
350pub(crate) const fn leaf_to_corresponding_tree(pos: usize, forest: usize) -> Option<u32> {
351    if pos >= forest {
352        None
353    } else {
354        // - each bit in the forest is a unique tree and the bit position its power-of-two size
355        // - each tree owns a consecutive range of positions equal to its size from left-to-right
356        // - this means the first tree owns from `0` up to the `2^k_0` first positions, where `k_0`
357        // is the highest true bit position, the second tree from `2^k_0 + 1` up to `2^k_1` where
358        // `k_1` is the second higest bit, so on.
359        // - this means the highest bits work as a category marker, and the position is owned by
360        // the first tree which doesn't share a high bit with the position
361        let before = forest & pos;
362        let after = forest ^ before;
363        let tree = after.ilog2();
364
365        Some(tree)
366    }
367}
368
369/// Return a bitmask for the bits including and above the given position.
370pub(crate) const fn high_bitmask(bit: u32) -> usize {
371    if bit > usize::BITS - 1 {
372        0
373    } else {
374        usize::MAX << bit
375    }
376}
377
378/// Return the total number of nodes of a given forest
379///
380/// Panics:
381///
382/// This will panic if the forest has size greater than `usize::MAX / 2`
383pub(crate) const fn nodes_in_forest(forest: usize) -> usize {
384    // - the size of a perfect binary tree is $2^{k+1}-1$ or $2*2^k-1$
385    // - the forest represents the sum of $2^k$ so a single multiplication is necessary
386    // - the number of `-1` is the same as the number of trees, which is the same as the number
387    // bits set
388    let tree_count = forest.count_ones() as usize;
389    forest * 2 - tree_count
390}