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