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