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//! reestablished.
13use super::{
14 super::{InnerNodeInfo, MerklePath, Vec},
15 bit::TrueBitPositionIterator,
16 leaf_to_corresponding_tree, nodes_in_forest, MmrDelta, MmrError, MmrPeaks, MmrProof, Rpo256,
17 RpoDigest,
18};
19
20// MMR
21// ===============================================================================================
22
23/// A fully materialized Merkle Mountain Range, with every tree in the forest and all their
24/// elements.
25///
26/// Since this is a full representation of the MMR, elements are never removed and the MMR will
27/// grow roughly `O(2n)` in number of leaf elements.
28#[derive(Debug, Clone)]
29#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
30pub struct Mmr {
31 /// Refer to the `forest` method documentation for details of the semantics of this value.
32 pub(super) forest: usize,
33
34 /// Contains every element of the forest.
35 ///
36 /// The trees are in postorder sequential representation. This representation allows for all
37 /// the elements of every tree in the forest to be stored in the same sequential buffer. It
38 /// also means new elements can be added to the forest, and merging of trees is very cheap with
39 /// no need to copy elements.
40 pub(super) nodes: Vec<RpoDigest>,
41}
42
43impl Default for Mmr {
44 fn default() -> Self {
45 Self::new()
46 }
47}
48
49impl Mmr {
50 // CONSTRUCTORS
51 // ============================================================================================
52
53 /// Constructor for an empty `Mmr`.
54 pub fn new() -> Mmr {
55 Mmr { forest: 0, nodes: Vec::new() }
56 }
57
58 // ACCESSORS
59 // ============================================================================================
60
61 /// Returns the MMR forest representation.
62 ///
63 /// The forest value has the following interpretations:
64 /// - its value is the number of elements in the forest
65 /// - bit count corresponds to the number of trees in the forest
66 /// - each true bit position determines the depth of a tree in the forest
67 pub const fn forest(&self) -> usize {
68 self.forest
69 }
70
71 // FUNCTIONALITY
72 // ============================================================================================
73
74 /// Given a leaf position, returns the Merkle path to its corresponding peak. If the position
75 /// is greater-or-equal than the tree size an error is returned.
76 ///
77 /// Note: The leaf position is the 0-indexed number corresponding to the order the leaves were
78 /// added, this corresponds to the MMR size _prior_ to adding the element. So the 1st element
79 /// has position 0, the second position 1, and so on.
80 pub fn open(&self, pos: usize) -> Result<MmrProof, MmrError> {
81 // find the target tree responsible for the MMR position
82 let tree_bit =
83 leaf_to_corresponding_tree(pos, self.forest).ok_or(MmrError::InvalidPosition(pos))?;
84
85 // isolate the trees before the target
86 let forest_before = self.forest & high_bitmask(tree_bit + 1);
87 let index_offset = nodes_in_forest(forest_before);
88
89 // update the value position from global to the target tree
90 let relative_pos = pos - forest_before;
91
92 // collect the path and the final index of the target value
93 let (_, path) = self.collect_merkle_path_and_value(tree_bit, relative_pos, index_offset);
94
95 Ok(MmrProof {
96 forest: self.forest,
97 position: pos,
98 merkle_path: MerklePath::new(path),
99 })
100 }
101
102 /// Returns the leaf value at position `pos`.
103 ///
104 /// Note: The leaf position is the 0-indexed number corresponding to the order the leaves were
105 /// added, this corresponds to the MMR size _prior_ to adding the element. So the 1st element
106 /// has position 0, the second position 1, and so on.
107 pub fn get(&self, pos: usize) -> Result<RpoDigest, MmrError> {
108 // find the target tree responsible for the MMR position
109 let tree_bit =
110 leaf_to_corresponding_tree(pos, self.forest).ok_or(MmrError::InvalidPosition(pos))?;
111
112 // isolate the trees before the target
113 let forest_before = self.forest & high_bitmask(tree_bit + 1);
114 let index_offset = nodes_in_forest(forest_before);
115
116 // update the value position from global to the target tree
117 let relative_pos = pos - forest_before;
118
119 // collect the path and the final index of the target value
120 let (value, _) = self.collect_merkle_path_and_value(tree_bit, relative_pos, index_offset);
121
122 Ok(value)
123 }
124
125 /// Adds a new element to the MMR.
126 pub fn add(&mut self, el: RpoDigest) {
127 // Note: every node is also a tree of size 1, adding an element to the forest creates a new
128 // rooted-tree of size 1. This may temporarily break the invariant that every tree in the
129 // forest has different sizes, the loop below will eagerly merge trees of same size and
130 // restore the invariant.
131 self.nodes.push(el);
132
133 let mut left_offset = self.nodes.len().saturating_sub(2);
134 let mut right = el;
135 let mut left_tree = 1;
136 while self.forest & left_tree != 0 {
137 right = Rpo256::merge(&[self.nodes[left_offset], right]);
138 self.nodes.push(right);
139
140 left_offset = left_offset.saturating_sub(nodes_in_forest(left_tree));
141 left_tree <<= 1;
142 }
143
144 self.forest += 1;
145 }
146
147 /// Returns an accumulator representing the current state of the MMR.
148 pub fn accumulator(&self) -> MmrPeaks {
149 let peaks: Vec<RpoDigest> = TrueBitPositionIterator::new(self.forest)
150 .rev()
151 .map(|bit| nodes_in_forest(1 << bit))
152 .scan(0, |offset, el| {
153 *offset += el;
154 Some(*offset)
155 })
156 .map(|offset| self.nodes[offset - 1])
157 .collect();
158
159 // Safety: the invariant is maintained by the [Mmr]
160 MmrPeaks::new(self.forest, peaks).unwrap()
161 }
162
163 /// Compute the required update to `original_forest`.
164 ///
165 /// The result is a packed sequence of the authentication elements required to update the trees
166 /// that have been merged together, followed by the new peaks of the [Mmr].
167 pub fn get_delta(&self, from_forest: usize, to_forest: usize) -> Result<MmrDelta, MmrError> {
168 if to_forest > self.forest || from_forest > to_forest {
169 return Err(MmrError::InvalidPeaks);
170 }
171
172 if from_forest == to_forest {
173 return Ok(MmrDelta { forest: to_forest, data: Vec::new() });
174 }
175
176 let mut result = Vec::new();
177
178 // Find the largest tree in this [Mmr] which is new to `from_forest`.
179 let candidate_trees = to_forest ^ from_forest;
180 let mut new_high = 1 << candidate_trees.ilog2();
181
182 // Collect authentication nodes used for tree merges
183 // ----------------------------------------------------------------------------------------
184
185 // Find the trees from `from_forest` that have been merged into `new_high`.
186 let mut merges = from_forest & (new_high - 1);
187
188 // Find the peaks that are common to `from_forest` and this [Mmr]
189 let common_trees = from_forest ^ merges;
190
191 if merges != 0 {
192 // Skip the smallest trees unknown to `from_forest`.
193 let mut target = 1 << merges.trailing_zeros();
194
195 // Collect siblings required to computed the merged tree's peak
196 while target < new_high {
197 // Computes the offset to the smallest know peak
198 // - common_trees: peaks unchanged in the current update, target comes after these.
199 // - merges: peaks that have not been merged so far, target comes after these.
200 // - target: tree from which to load the sibling. On the first iteration this is a
201 // value known by the partial mmr, on subsequent iterations this value is to be
202 // computed from the known peaks and provided authentication nodes.
203 let known = nodes_in_forest(common_trees | merges | target);
204 let sibling = nodes_in_forest(target);
205 result.push(self.nodes[known + sibling - 1]);
206
207 // Update the target and account for tree merges
208 target <<= 1;
209 while merges & target != 0 {
210 target <<= 1;
211 }
212 // Remove the merges done so far
213 merges ^= merges & (target - 1);
214 }
215 } else {
216 // The new high tree may not be the result of any merges, if it is smaller than all the
217 // trees of `from_forest`.
218 new_high = 0;
219 }
220
221 // Collect the new [Mmr] peaks
222 // ----------------------------------------------------------------------------------------
223
224 let mut new_peaks = to_forest ^ common_trees ^ new_high;
225 let old_peaks = to_forest ^ new_peaks;
226 let mut offset = nodes_in_forest(old_peaks);
227 while new_peaks != 0 {
228 let target = 1 << new_peaks.ilog2();
229 offset += nodes_in_forest(target);
230 result.push(self.nodes[offset - 1]);
231 new_peaks ^= target;
232 }
233
234 Ok(MmrDelta { forest: to_forest, data: result })
235 }
236
237 /// An iterator over inner nodes in the MMR. The order of iteration is unspecified.
238 pub fn inner_nodes(&self) -> MmrNodes {
239 MmrNodes {
240 mmr: self,
241 forest: 0,
242 last_right: 0,
243 index: 0,
244 }
245 }
246
247 // UTILITIES
248 // ============================================================================================
249
250 /// Internal function used to collect the Merkle path of a value.
251 ///
252 /// The arguments are relative to the target tree. To compute the opening of the second leaf
253 /// for a tree with depth 2 in the forest `0b110`:
254 ///
255 /// - `tree_bit`: Depth of the target tree, e.g. 2 for the smallest tree.
256 /// - `relative_pos`: 0-indexed leaf position in the target tree, e.g. 1 for the second leaf.
257 /// - `index_offset`: Node count prior to the target tree, e.g. 7 for the tree of depth 3.
258 fn collect_merkle_path_and_value(
259 &self,
260 tree_bit: u32,
261 relative_pos: usize,
262 index_offset: usize,
263 ) -> (RpoDigest, Vec<RpoDigest>) {
264 // see documentation of `leaf_to_corresponding_tree` for details
265 let tree_depth = (tree_bit + 1) as usize;
266 let mut path = Vec::with_capacity(tree_depth);
267
268 // The tree walk below goes from the root to the leaf, compute the root index to start
269 let mut forest_target = 1usize << tree_bit;
270 let mut index = nodes_in_forest(forest_target) - 1;
271
272 // Loop until the leaf is reached
273 while forest_target > 1 {
274 // Update the depth of the tree to correspond to a subtree
275 forest_target >>= 1;
276
277 // compute the indeces of the right and left subtrees based on the post-order
278 let right_offset = index - 1;
279 let left_offset = right_offset - nodes_in_forest(forest_target);
280
281 let left_or_right = relative_pos & forest_target;
282 let sibling = if left_or_right != 0 {
283 // going down the right subtree, the right child becomes the new root
284 index = right_offset;
285 // and the left child is the authentication
286 self.nodes[index_offset + left_offset]
287 } else {
288 index = left_offset;
289 self.nodes[index_offset + right_offset]
290 };
291
292 path.push(sibling);
293 }
294
295 debug_assert!(path.len() == tree_depth - 1);
296
297 // the rest of the codebase has the elements going from leaf to root, adjust it here for
298 // easy of use/consistency sake
299 path.reverse();
300
301 let value = self.nodes[index_offset + index];
302 (value, path)
303 }
304}
305
306// CONVERSIONS
307// ================================================================================================
308
309impl<T> From<T> for Mmr
310where
311 T: IntoIterator<Item = RpoDigest>,
312{
313 fn from(values: T) -> Self {
314 let mut mmr = Mmr::new();
315 for v in values {
316 mmr.add(v)
317 }
318 mmr
319 }
320}
321
322// ITERATOR
323// ===============================================================================================
324
325/// Yields inner nodes of the [Mmr].
326pub struct MmrNodes<'a> {
327 /// [Mmr] being yielded, when its `forest` value is matched, the iterations is finished.
328 mmr: &'a Mmr,
329 /// Keeps track of the left nodes yielded so far waiting for a right pair, this matches the
330 /// semantics of the [Mmr]'s forest attribute, since that too works as a buffer of left nodes
331 /// waiting for a pair to be hashed together.
332 forest: usize,
333 /// Keeps track of the last right node yielded, after this value is set, the next iteration
334 /// will be its parent with its corresponding left node that has been yield already.
335 last_right: usize,
336 /// The current index in the `nodes` vector.
337 index: usize,
338}
339
340impl<'a> Iterator for MmrNodes<'a> {
341 type Item = InnerNodeInfo;
342
343 fn next(&mut self) -> Option<Self::Item> {
344 debug_assert!(self.last_right.count_ones() <= 1, "last_right tracks zero or one element");
345
346 // only parent nodes are emitted, remove the single node tree from the forest
347 let target = self.mmr.forest & (usize::MAX << 1);
348
349 if self.forest < target {
350 if self.last_right == 0 {
351 // yield the left leaf
352 debug_assert!(self.last_right == 0, "left must be before right");
353 self.forest |= 1;
354 self.index += 1;
355
356 // yield the right leaf
357 debug_assert!((self.forest & 1) == 1, "right must be after left");
358 self.last_right |= 1;
359 self.index += 1;
360 };
361
362 debug_assert!(
363 self.forest & self.last_right != 0,
364 "parent requires both a left and right",
365 );
366
367 // compute the number of nodes in the right tree, this is the offset to the
368 // previous left parent
369 let right_nodes = nodes_in_forest(self.last_right);
370 // the next parent position is one above the position of the pair
371 let parent = self.last_right << 1;
372
373 // the left node has been paired and the current parent yielded, removed it from the forest
374 self.forest ^= self.last_right;
375 if self.forest & parent == 0 {
376 // this iteration yielded the left parent node
377 debug_assert!(self.forest & 1 == 0, "next iteration yields a left leaf");
378 self.last_right = 0;
379 self.forest ^= parent;
380 } else {
381 // the left node of the parent level has been yielded already, this iteration
382 // was the right parent. Next iteration yields their parent.
383 self.last_right = parent;
384 }
385
386 // yields a parent
387 let value = self.mmr.nodes[self.index];
388 let right = self.mmr.nodes[self.index - 1];
389 let left = self.mmr.nodes[self.index - 1 - right_nodes];
390 self.index += 1;
391 let node = InnerNodeInfo { value, left, right };
392
393 Some(node)
394 } else {
395 None
396 }
397 }
398}
399
400// UTILITIES
401// ===============================================================================================
402
403/// Return a bitmask for the bits including and above the given position.
404pub(crate) const fn high_bitmask(bit: u32) -> usize {
405 if bit > usize::BITS - 1 {
406 0
407 } else {
408 usize::MAX << bit
409 }
410}