Skip to main content

miden_crypto/merkle/partial_mt/
mod.rs

1use alloc::{
2    collections::{BTreeMap, BTreeSet},
3    string::String,
4    vec::Vec,
5};
6use core::fmt;
7
8use super::{
9    EMPTY_WORD, Eidos, InnerNodeInfo, MerkleError, MerklePath, MerkleProof, NodeIndex, Word,
10};
11use crate::utils::{
12    ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable, word_to_hex,
13};
14
15#[cfg(test)]
16mod tests;
17
18// ARBITRARY (proptest)
19// ================================================================================================
20
21#[cfg(any(test, feature = "arbitrary"))]
22mod arbitrary {
23    extern crate alloc;
24
25    use alloc::vec::Vec;
26
27    use proptest::prelude::*;
28
29    use super::PartialMerkleTree;
30    use crate::{
31        Word,
32        merkle::{MerklePath, MerkleTree, NodeIndex},
33    };
34
35    impl Arbitrary for PartialMerkleTree {
36        type Parameters = ();
37        type Strategy = BoxedStrategy<Self>;
38
39        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
40            // Sound by construction. Branch A opens a subset of leaves of a real MerkleTree:
41            // all paths share one depth, so no entry can be an ancestor of another (the
42            // ambiguity `with_leaves` rejects), and an all-false mask yields the empty tree.
43            // Branch B contributes a single synthetic deep path (no other path, so still no
44            // ambiguity), exercising large NodeIndex depth/position wire encodings cheaply -
45            // path provenance is irrelevant to the leaves-only wire format. No generation-time
46            // panics: every input is valid for any shrunken prefix.
47            prop_oneof![paths_from_real_tree().boxed(), single_deep_path().boxed()].boxed()
48        }
49    }
50
51    fn paths_from_real_tree() -> impl Strategy<Value = PartialMerkleTree> {
52        (1u8..=6)
53            .prop_flat_map(|depth| {
54                let count = 1usize << depth;
55                (
56                    Just(depth),
57                    proptest::collection::vec(any::<Word>(), count),
58                    proptest::collection::vec(any::<bool>(), count),
59                )
60            })
61            .prop_map(|(depth, leaves, track_mask)| {
62                let tree = MerkleTree::new(&leaves).expect("leaf count is a power of two >= 2");
63                let paths: Vec<(u64, Word, MerklePath)> = track_mask
64                    .iter()
65                    .enumerate()
66                    .filter(|(_, tracked)| **tracked)
67                    .map(|(pos, _)| {
68                        let node_index =
69                            NodeIndex::new(depth, pos as u64).expect("position fits the depth");
70                        let path = tree.get_path(node_index).expect("position within the tree");
71                        (pos as u64, leaves[pos], path)
72                    })
73                    .collect();
74                PartialMerkleTree::with_paths(paths)
75                    .expect("paths from one tree share a depth and no ancestor relation")
76            })
77    }
78
79    fn single_deep_path() -> impl Strategy<Value = PartialMerkleTree> {
80        (7u8..=64, any::<u64>(), any::<Word>())
81            .prop_flat_map(|(depth, index, value)| {
82                let mask = if depth == 64 { u64::MAX } else { (1u64 << depth) - 1 };
83                (
84                    Just(depth),
85                    Just(value),
86                    Just(index & mask),
87                    proptest::collection::vec(any::<Word>(), depth as usize),
88                )
89            })
90            .prop_map(|(_depth, value, index, path_nodes)| {
91                let path = MerklePath::new(path_nodes);
92                PartialMerkleTree::with_paths([(index, value, path)])
93                    .expect("a single path is always a valid partial tree")
94            })
95    }
96}
97
98// CONSTANTS
99// ================================================================================================
100
101/// Index of the root node.
102const ROOT_INDEX: NodeIndex = NodeIndex::root();
103
104/// An Word consisting of 4 ZERO elements.
105const EMPTY_DIGEST: Word = EMPTY_WORD;
106
107// PARTIAL MERKLE TREE
108// ================================================================================================
109
110/// A partial Merkle tree with NodeIndex keys and 4-element [Word] leaf values. Partial Merkle
111/// Tree allows to create Merkle Tree by providing Merkle paths of different lengths.
112///
113/// The root of the tree is recomputed on each new leaf update.
114#[derive(Debug, Clone, PartialEq, Eq)]
115#[cfg_attr(
116    all(feature = "arbitrary", test),
117    miden_test_serialization_macros::serialization_test
118)]
119pub struct PartialMerkleTree {
120    max_depth: u8,
121    nodes: BTreeMap<NodeIndex, Word>,
122    leaves: BTreeSet<NodeIndex>,
123}
124
125impl Default for PartialMerkleTree {
126    fn default() -> Self {
127        Self::new()
128    }
129}
130
131impl PartialMerkleTree {
132    // CONSTANTS
133    // --------------------------------------------------------------------------------------------
134
135    /// Minimum supported depth.
136    pub const MIN_DEPTH: u8 = 1;
137
138    /// Maximum supported depth.
139    pub const MAX_DEPTH: u8 = 64;
140
141    // CONSTRUCTORS
142    // --------------------------------------------------------------------------------------------
143
144    /// Returns a new empty [PartialMerkleTree].
145    pub fn new() -> Self {
146        PartialMerkleTree {
147            max_depth: 0,
148            nodes: BTreeMap::new(),
149            leaves: BTreeSet::new(),
150        }
151    }
152
153    /// Appends the provided paths iterator into the set.
154    ///
155    /// Analogous to [Self::add_path].
156    pub fn with_paths<I>(paths: I) -> Result<Self, MerkleError>
157    where
158        I: IntoIterator<Item = (u64, Word, MerklePath)>,
159    {
160        // create an empty tree
161        let tree = PartialMerkleTree::new();
162
163        paths.into_iter().try_fold(tree, |mut tree, (index, value, path)| {
164            tree.add_path(index, value, path)?;
165            Ok(tree)
166        })
167    }
168
169    /// Returns a new [PartialMerkleTree] instantiated with leaves map as specified by the provided
170    /// entries.
171    ///
172    /// # Errors
173    /// Returns an error if:
174    /// - Any entry has depth 0 or is greater than 64.
175    /// - The number of entries exceeds the maximum tree capacity, that is 2^{depth}.
176    /// - The provided entries contain an insufficient set of nodes.
177    /// - Any entry is an ancestor of another entry (creates hash ambiguity).
178    ///
179    /// An empty input returns an empty tree.
180    pub fn with_leaves<R, I>(entries: R) -> Result<Self, MerkleError>
181    where
182        R: IntoIterator<IntoIter = I>,
183        I: Iterator<Item = (NodeIndex, Word)> + ExactSizeIterator,
184    {
185        let entries = entries.into_iter();
186        if entries.len() == 0 {
187            return Ok(PartialMerkleTree::new());
188        }
189
190        let mut layers: BTreeMap<u8, Vec<u64>> = BTreeMap::new();
191        let mut leaves = BTreeSet::new();
192        let mut nodes = BTreeMap::new();
193
194        // add data to the leaves and nodes maps and also fill layers map, where the key is the
195        // depth of the node and value is its index.
196        for (node_index, hash) in entries {
197            Self::check_depth(node_index.depth())?;
198            leaves.insert(node_index);
199            nodes.insert(node_index, hash);
200            layers
201                .entry(node_index.depth())
202                .and_modify(|layer_vec| layer_vec.push(node_index.position()))
203                .or_insert(vec![node_index.position()]);
204        }
205
206        // Get maximum depth
207        let max_depth = *layers.keys().next_back().unwrap_or(&0);
208
209        // fill layers without nodes with empty vector
210        for depth in 0..max_depth {
211            layers.entry(depth).or_default();
212        }
213
214        let mut layer_iter = layers.into_values().rev();
215        let mut parent_layer = layer_iter.next().unwrap();
216        let mut current_layer;
217
218        for depth in (1..max_depth + 1).rev() {
219            // set current_layer = parent_layer and parent_layer = layer_iter.next()
220            current_layer = layer_iter.next().unwrap();
221            core::mem::swap(&mut current_layer, &mut parent_layer);
222
223            // Siblings have the same parent position. Sort them together and retain one child per
224            // parent so each parent is computed once.
225            current_layer.sort_unstable();
226            current_layer.dedup_by_key(|position| *position / 2);
227
228            for index_value in current_layer {
229                // get the parent node index
230                let parent_node = NodeIndex::new(depth - 1, index_value / 2)?;
231
232                // A user-provided parent cannot also have a descendant in the input set.
233                if leaves.contains(&parent_node) {
234                    return Err(MerkleError::EntryIsNotLeaf { node: parent_node });
235                }
236
237                // create current node index
238                let index = NodeIndex::new(depth, index_value)?;
239
240                // get hash of the current node
241                let node = nodes.get(&index).ok_or(MerkleError::NodeIndexNotFoundInTree(index))?;
242                // get hash of the sibling node
243                let sibling = nodes
244                    .get(&index.sibling())
245                    .ok_or(MerkleError::NodeIndexNotFoundInTree(index.sibling()))?;
246                // get parent hash
247                let parent = Eidos::merge(&index.build_node(*node, *sibling));
248
249                // add index value of the calculated node to the parents layer
250                parent_layer.push(parent_node.position());
251                // add index and hash to the nodes map
252                nodes.insert(parent_node, parent);
253            }
254        }
255
256        Ok(PartialMerkleTree { max_depth, nodes, leaves })
257    }
258
259    // PUBLIC ACCESSORS
260    // --------------------------------------------------------------------------------------------
261
262    /// Returns the root of this Merkle tree.
263    pub fn root(&self) -> Word {
264        self.nodes.get(&ROOT_INDEX).cloned().unwrap_or(EMPTY_DIGEST)
265    }
266
267    /// Returns the depth of this Merkle tree.
268    pub fn max_depth(&self) -> u8 {
269        self.max_depth
270    }
271
272    /// Returns a node at the specified NodeIndex.
273    ///
274    /// # Errors
275    /// Returns an error if the specified NodeIndex is not contained in the nodes map.
276    pub fn get_node(&self, index: NodeIndex) -> Result<Word, MerkleError> {
277        self.nodes
278            .get(&index)
279            .ok_or(MerkleError::NodeIndexNotFoundInTree(index))
280            .copied()
281    }
282
283    /// Returns true if provided index contains in the leaves set, false otherwise.
284    pub fn is_leaf(&self, index: NodeIndex) -> bool {
285        self.leaves.contains(&index)
286    }
287
288    /// Returns a vector of paths from every leaf to the root.
289    pub fn to_paths(&self) -> Vec<(NodeIndex, MerkleProof)> {
290        let mut paths = Vec::new();
291        self.leaves.iter().for_each(|&leaf| {
292            paths.push((
293                leaf,
294                MerkleProof {
295                    value: self.get_node(leaf).expect("Failed to get leaf node"),
296                    path: self.get_path(leaf).expect("Failed to get path"),
297                },
298            ));
299        });
300        paths
301    }
302
303    /// Returns a Merkle path from the node at the specified index to the root.
304    ///
305    /// The node itself is not included in the path.
306    ///
307    /// # Errors
308    /// Returns an error if:
309    /// - the specified index has depth set to 0 or the depth is greater than the depth of this
310    ///   Merkle tree.
311    /// - the specified index is not contained in the nodes map.
312    pub fn get_path(&self, mut index: NodeIndex) -> Result<MerklePath, MerkleError> {
313        if index.is_root() {
314            return Err(MerkleError::DepthTooSmall(index.depth()));
315        } else if index.depth() > self.max_depth() {
316            return Err(MerkleError::DepthTooBig(index.depth() as u64));
317        }
318
319        if !self.nodes.contains_key(&index) {
320            return Err(MerkleError::NodeIndexNotFoundInTree(index));
321        }
322
323        let mut path = Vec::new();
324        for _ in 0..index.depth() {
325            let sibling_index = index.sibling();
326            index.move_up();
327            let sibling =
328                self.nodes.get(&sibling_index).cloned().expect("Sibling node not in the map");
329            path.push(sibling);
330        }
331        Ok(MerklePath::new(path))
332    }
333
334    // ITERATORS
335    // --------------------------------------------------------------------------------------------
336
337    /// Returns an iterator over the leaves of this [PartialMerkleTree].
338    pub fn leaves(&self) -> impl Iterator<Item = (NodeIndex, Word)> + '_ {
339        self.leaves.iter().map(|&leaf| {
340            (
341                leaf,
342                self.get_node(leaf)
343                    .unwrap_or_else(|_| panic!("Leaf with {leaf} is not in the nodes map")),
344            )
345        })
346    }
347
348    /// Returns an iterator over the inner nodes of this Merkle tree.
349    pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
350        let inner_nodes = self.nodes.iter().filter(|(index, _)| !self.leaves.contains(index));
351        inner_nodes.map(|(index, digest)| {
352            let left_hash =
353                self.nodes.get(&index.left_child()).expect("Failed to get left child hash");
354            let right_hash =
355                self.nodes.get(&index.right_child()).expect("Failed to get right child hash");
356            InnerNodeInfo {
357                value: *digest,
358                left: *left_hash,
359                right: *right_hash,
360            }
361        })
362    }
363
364    // STATE MUTATORS
365    // --------------------------------------------------------------------------------------------
366
367    /// Adds the nodes of the specified Merkle path to this [PartialMerkleTree]. The `index_value`
368    /// and `value` parameters specify the leaf node at which the path starts.
369    ///
370    /// # Errors
371    /// Returns an error if:
372    /// - The depth of the specified node_index is greater than 64 or smaller than 1.
373    /// - The specified path is not consistent with other paths in the set (i.e., resolves to a
374    ///   different root).
375    ///
376    /// If an error is returned, the tree is unchanged.
377    pub fn add_path(
378        &mut self,
379        index_value: u64,
380        value: Word,
381        path: MerklePath,
382    ) -> Result<(), MerkleError> {
383        let index_value = NodeIndex::new(path.len() as u8, index_value)?;
384
385        Self::check_depth(index_value.depth())?;
386
387        // Compute the candidate root and the parent hashes without changing the tree.
388        let mut parent_hashes = [EMPTY_DIGEST; PartialMerkleTree::MAX_DEPTH as usize];
389        let (root, parent_count) =
390            Self::compute_path_nodes(index_value, value, &path, &mut parent_hashes);
391
392        // if the path set is empty (the root is all ZEROs), set the root to the root of the added
393        // path; otherwise, the root of the added path must be identical to the current root
394        let expected_root = self.root();
395        if expected_root != EMPTY_DIGEST && expected_root != root {
396            return Err(MerkleError::ConflictingRoots { expected_root, actual_root: root });
397        }
398
399        self.update_depth(index_value.depth());
400
401        // add provided node and its sibling to the leaves set
402        self.leaves.insert(index_value);
403        let sibling_node_index = index_value.sibling();
404        self.leaves.insert(sibling_node_index);
405
406        // add provided node and its sibling to the nodes map
407        self.nodes.insert(index_value, value);
408        self.nodes.insert(sibling_node_index, path[0]);
409
410        // traverse to the root, updating the nodes from the staged parent hashes
411        let mut index_value = index_value;
412        for (&parent_hash, &sibling_hash) in
413            parent_hashes[..parent_count].iter().zip(path.iter().skip(1))
414        {
415            index_value.move_up();
416            // insert calculated node to the nodes map
417            self.nodes.insert(index_value, parent_hash);
418
419            // if the calculated node was a leaf, remove it from leaves set.
420            self.leaves.remove(&index_value);
421
422            let sibling_node = index_value.sibling();
423
424            // Insert node from Merkle path to the nodes map. This sibling node becomes a leaf only
425            // if it is a new node (it wasn't in nodes map).
426            // Node can be in 3 states: internal node, leaf of the tree and not a tree node at all.
427            // - Internal node can only stay in this state -- addition of a new path can't make it
428            // a leaf or remove it from the tree.
429            // - Leaf node can stay in the same state (remain a leaf) or can become an internal
430            // node. In the first case we don't need to do anything, and the second case is handled
431            // by the call of `self.leaves.remove(&index_value);`
432            // - New node can be a calculated node or a "sibling" node from a Merkle Path:
433            // --- Calculated node, obviously, never can be a leaf.
434            // --- Sibling node can be only a leaf, because otherwise it is not a new node.
435            if self.nodes.insert(sibling_node, sibling_hash).is_none() {
436                self.leaves.insert(sibling_node);
437            }
438        }
439
440        if expected_root == EMPTY_DIGEST {
441            self.nodes.insert(ROOT_INDEX, root);
442        }
443
444        Ok(())
445    }
446
447    /// Updates value of the leaf at the specified index returning the old leaf value.
448    ///
449    /// By default the specified index is assumed to belong to the deepest layer. If the considered
450    /// node does not belong to the tree, the first node on the way to the root will be changed.
451    ///
452    /// This also recomputes all hashes between the leaf and the root, updating the root itself.
453    ///
454    /// # Errors
455    /// Returns an error if:
456    /// - No entry exists at the specified index.
457    /// - The specified index is greater than the maximum number of nodes on the deepest layer.
458    pub fn update_leaf(&mut self, index: u64, value: Word) -> Result<Word, MerkleError> {
459        let mut node_index = NodeIndex::new(self.max_depth(), index)?;
460
461        // proceed to the leaf
462        for _ in 0..node_index.depth() {
463            if !self.leaves.contains(&node_index) {
464                node_index.move_up();
465            }
466        }
467
468        // add node value to the nodes Map
469        let old_value = self
470            .nodes
471            .insert(node_index, value)
472            .ok_or(MerkleError::NodeIndexNotFoundInTree(node_index))?;
473
474        // if the old value and new value are the same, there is nothing to update
475        if value == old_value {
476            return Ok(old_value);
477        }
478
479        let mut value = value;
480        for _ in 0..node_index.depth() {
481            let sibling = self.nodes.get(&node_index.sibling()).expect("sibling should exist");
482            value = Eidos::merge(&node_index.build_node(value, *sibling));
483            node_index.move_up();
484            self.nodes.insert(node_index, value);
485        }
486
487        Ok(old_value)
488    }
489
490    // UTILITY FUNCTIONS
491    // --------------------------------------------------------------------------------------------
492
493    /// Utility to visualize a [PartialMerkleTree] in text.
494    pub fn print(&self) -> Result<String, fmt::Error> {
495        let indent = "  ";
496        let mut s = String::new();
497        s.push_str("root: ");
498        s.push_str(&word_to_hex(&self.root())?);
499        s.push('\n');
500        for d in 1..=self.max_depth() {
501            let entries = 2u64.pow(d.into());
502            for i in 0..entries {
503                let index = NodeIndex::new(d, i).expect("The index must always be valid");
504                let node = self.get_node(index);
505                let node = match node {
506                    Err(_) => continue,
507                    Ok(node) => node,
508                };
509
510                for _ in 0..d {
511                    s.push_str(indent);
512                }
513                s.push_str(&format!("({}, {}): ", index.depth(), index.position()));
514                s.push_str(&word_to_hex(&node)?);
515                s.push('\n');
516            }
517        }
518
519        Ok(s)
520    }
521
522    // HELPER METHODS
523    // --------------------------------------------------------------------------------------------
524
525    /// Updates depth value with the maximum of current and provided depth.
526    fn update_depth(&mut self, new_depth: u8) {
527        self.max_depth = new_depth.max(self.max_depth);
528    }
529
530    /// Returns an error if the depth is 0 or is greater than 64.
531    fn check_depth(depth: u8) -> Result<(), MerkleError> {
532        // validate the range of the depth.
533        if depth < Self::MIN_DEPTH {
534            return Err(MerkleError::DepthTooSmall(depth));
535        } else if Self::MAX_DEPTH < depth {
536            return Err(MerkleError::DepthTooBig(depth as u64));
537        }
538        Ok(())
539    }
540
541    /// Computes the candidate root and staged parent hashes without changing the tree.
542    ///
543    /// The buffer receives one parent hash for each path node above the leaf. The returned count
544    /// is the number of hashes written to the buffer.
545    fn compute_path_nodes(
546        index_value: NodeIndex,
547        value: Word,
548        path: &MerklePath,
549        parent_hashes: &mut [Word],
550    ) -> (Word, usize) {
551        let mut index_value = index_value;
552        let mut node = Eidos::merge(&index_value.build_node(value, path[0]));
553        let mut parent_count = 0;
554
555        for &sibling_hash in path.iter().skip(1) {
556            index_value.move_up();
557            parent_hashes[parent_count] = node;
558            parent_count += 1;
559            node = Eidos::merge(&index_value.build_node(node, sibling_hash));
560        }
561
562        (node, parent_count)
563    }
564}
565
566// SERIALIZATION
567// ================================================================================================
568
569impl Serializable for PartialMerkleTree {
570    fn write_into<W: ByteWriter>(&self, target: &mut W) {
571        // write leaf nodes
572        target.write_u64(self.leaves.len() as u64);
573        for leaf_index in self.leaves.iter() {
574            leaf_index.write_into(target);
575            self.get_node(*leaf_index).expect("Leaf hash not found").write_into(target);
576        }
577    }
578}
579
580impl Deserializable for PartialMerkleTree {
581    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
582        let leaves_len_u64 = source.read_u64()?;
583        let leaves_len = usize::try_from(leaves_len_u64).map_err(|_| {
584            DeserializationError::InvalidValue("PartialMerkleTree leaf count too large".into())
585        })?;
586
587        // Use read_many_iter to avoid eager allocation and respect BudgetedReader limits
588        let leaf_nodes: Vec<(NodeIndex, Word)> =
589            source.read_many_iter(leaves_len)?.collect::<Result<_, _>>()?;
590
591        let pmt = PartialMerkleTree::with_leaves(leaf_nodes).map_err(|_| {
592            DeserializationError::InvalidValue("Invalid data for PartialMerkleTree creation".into())
593        })?;
594
595        Ok(pmt)
596    }
597
598    /// Minimum serialized size: u64 length prefix (0 entries).
599    fn min_serialized_size() -> usize {
600        8
601    }
602}