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