arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/merkle/path_set.rs
src/merkle/path_set.rsRaw
  1use super::{BTreeMap, MerkleError, MerklePath, NodeIndex, Rpo256, ValuePath, Vec, Word, ZERO};
  2
  3// MERKLE PATH SET
  4// ================================================================================================
  5
  6/// A set of Merkle paths.
  7#[derive(Debug, Clone, PartialEq, Eq)]
  8pub struct MerklePathSet {
  9    root: Word,
 10    total_depth: u8,
 11    paths: BTreeMap<u64, MerklePath>,
 12}
 13
 14impl MerklePathSet {
 15    // CONSTRUCTOR
 16    // --------------------------------------------------------------------------------------------
 17
 18    /// Returns an empty MerklePathSet.
 19    pub fn new(depth: u8) -> Self {
 20        let root = [ZERO; 4];
 21        let paths = BTreeMap::new();
 22
 23        Self {
 24            root,
 25            total_depth: depth,
 26            paths,
 27        }
 28    }
 29
 30    /// Appends the provided paths iterator into the set.
 31    ///
 32    /// Analogous to `[Self::add_path]`.
 33    pub fn with_paths<I>(self, paths: I) -> Result<Self, MerkleError>
 34    where
 35        I: IntoIterator<Item = (u64, Word, MerklePath)>,
 36    {
 37        paths
 38            .into_iter()
 39            .try_fold(self, |mut set, (index, value, path)| {
 40                set.add_path(index, value, path)?;
 41                Ok(set)
 42            })
 43    }
 44
 45    // PUBLIC ACCESSORS
 46    // --------------------------------------------------------------------------------------------
 47
 48    /// Returns the root to which all paths in this set resolve.
 49    pub const fn root(&self) -> Word {
 50        self.root
 51    }
 52
 53    /// Returns the depth of the Merkle tree implied by the paths stored in this set.
 54    ///
 55    /// Merkle tree of depth 1 has two leaves, depth 2 has four leaves etc.
 56    pub const fn depth(&self) -> u8 {
 57        self.total_depth
 58    }
 59
 60    /// Returns a node at the specified index.
 61    ///
 62    /// # Errors
 63    /// Returns an error if:
 64    /// * The specified index is not valid for the depth of structure.
 65    /// * Requested node does not exist in the set.
 66    pub fn get_node(&self, index: NodeIndex) -> Result<Word, MerkleError> {
 67        if index.depth() != self.total_depth {
 68            return Err(MerkleError::InvalidDepth {
 69                expected: self.total_depth,
 70                provided: index.depth(),
 71            });
 72        }
 73
 74        let parity = index.value() & 1;
 75        let path_key = index.value() - parity;
 76        self.paths
 77            .get(&path_key)
 78            .ok_or(MerkleError::NodeNotInSet(path_key))
 79            .map(|path| path[parity as usize])
 80    }
 81
 82    /// Returns a leaf at the specified index.
 83    ///
 84    /// # Errors
 85    /// * The specified index is not valid for the depth of the structure.
 86    /// * Leaf with the requested path does not exist in the set.
 87    pub fn get_leaf(&self, index: u64) -> Result<Word, MerkleError> {
 88        let index = NodeIndex::new(self.depth(), index)?;
 89        self.get_node(index)
 90    }
 91
 92    /// Returns a Merkle path to the node at the specified index. The node itself is
 93    /// not included in the path.
 94    ///
 95    /// # Errors
 96    /// Returns an error if:
 97    /// * The specified index is not valid for the depth of structure.
 98    /// * Node of the requested path does not exist in the set.
 99    pub fn get_path(&self, index: NodeIndex) -> Result<MerklePath, MerkleError> {
100        if index.depth() != self.total_depth {
101            return Err(MerkleError::InvalidDepth {
102                expected: self.total_depth,
103                provided: index.depth(),
104            });
105        }
106
107        let parity = index.value() & 1;
108        let path_key = index.value() - parity;
109        let mut path = self
110            .paths
111            .get(&path_key)
112            .cloned()
113            .ok_or(MerkleError::NodeNotInSet(index.value()))?;
114        path.remove(parity as usize);
115        Ok(path)
116    }
117
118    /// Returns all paths in this path set together with their indexes.
119    pub fn to_paths(&self) -> Vec<(u64, ValuePath)> {
120        let mut result = Vec::with_capacity(self.paths.len() * 2);
121
122        for (&index, path) in self.paths.iter() {
123            // push path for the even index into the result
124            let path1 = ValuePath {
125                value: path[0],
126                path: MerklePath::new(path[1..].to_vec()),
127            };
128            result.push((index, path1));
129
130            // push path for the odd index into the result
131            let mut path2 = path.clone();
132            let leaf2 = path2.remove(1);
133            let path2 = ValuePath {
134                value: leaf2,
135                path: path2,
136            };
137            result.push((index + 1, path2));
138        }
139
140        result
141    }
142
143    // STATE MUTATORS
144    // --------------------------------------------------------------------------------------------
145
146    /// Adds the specified Merkle path to this [MerklePathSet]. The `index` and `value` parameters
147    /// specify the leaf node at which the path starts.
148    ///
149    /// # Errors
150    /// Returns an error if:
151    /// - The specified index is is not valid in the context of this Merkle path set (i.e., the
152    ///   index implies a greater depth than is specified for this set).
153    /// - The specified path is not consistent with other paths in the set (i.e., resolves to a
154    ///   different root).
155    pub fn add_path(
156        &mut self,
157        index_value: u64,
158        value: Word,
159        mut path: MerklePath,
160    ) -> Result<(), MerkleError> {
161        let mut index = NodeIndex::new(path.len() as u8, index_value)?;
162        if index.depth() != self.total_depth {
163            return Err(MerkleError::InvalidDepth {
164                expected: self.total_depth,
165                provided: index.depth(),
166            });
167        }
168
169        // update the current path
170        let parity = index_value & 1;
171        path.insert(parity as usize, value);
172
173        // traverse to the root, updating the nodes
174        let root: Word = Rpo256::merge(&[path[0].into(), path[1].into()]).into();
175        let root = path.iter().skip(2).copied().fold(root, |root, hash| {
176            index.move_up();
177            Rpo256::merge(&index.build_node(root.into(), hash.into())).into()
178        });
179
180        // if the path set is empty (the root is all ZEROs), set the root to the root of the added
181        // path; otherwise, the root of the added path must be identical to the current root
182        if self.root == [ZERO; 4] {
183            self.root = root;
184        } else if self.root != root {
185            return Err(MerkleError::ConflictingRoots([self.root, root].to_vec()));
186        }
187
188        // finish updating the path
189        let path_key = index_value - parity;
190        self.paths.insert(path_key, path);
191        Ok(())
192    }
193
194    /// Replaces the leaf at the specified index with the provided value.
195    ///
196    /// # Errors
197    /// Returns an error if:
198    /// * Requested node does not exist in the set.
199    pub fn update_leaf(&mut self, base_index_value: u64, value: Word) -> Result<(), MerkleError> {
200        let mut index = NodeIndex::new(self.depth(), base_index_value)?;
201        let parity = index.value() & 1;
202        let path_key = index.value() - parity;
203        let path = match self.paths.get_mut(&path_key) {
204            Some(path) => path,
205            None => return Err(MerkleError::NodeNotInSet(base_index_value)),
206        };
207
208        // Fill old_hashes vector -----------------------------------------------------------------
209        let mut current_index = index;
210        let mut old_hashes = Vec::with_capacity(path.len().saturating_sub(2));
211        let mut root: Word = Rpo256::merge(&[path[0].into(), path[1].into()]).into();
212        for hash in path.iter().skip(2).copied() {
213            old_hashes.push(root);
214            current_index.move_up();
215            let input = current_index.build_node(hash.into(), root.into());
216            root = Rpo256::merge(&input).into();
217        }
218
219        // Fill new_hashes vector -----------------------------------------------------------------
220        path[index.is_value_odd() as usize] = value;
221
222        let mut new_hashes = Vec::with_capacity(path.len().saturating_sub(2));
223        let mut new_root: Word = Rpo256::merge(&[path[0].into(), path[1].into()]).into();
224        for path_hash in path.iter().skip(2).copied() {
225            new_hashes.push(new_root);
226            index.move_up();
227            let input = current_index.build_node(path_hash.into(), new_root.into());
228            new_root = Rpo256::merge(&input).into();
229        }
230
231        self.root = new_root;
232
233        // update paths ---------------------------------------------------------------------------
234        for path in self.paths.values_mut() {
235            for i in (0..old_hashes.len()).rev() {
236                if path[i + 2] == old_hashes[i] {
237                    path[i + 2] = new_hashes[i];
238                    break;
239                }
240            }
241        }
242
243        Ok(())
244    }
245}
246
247// TESTS
248// ================================================================================================
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use crate::merkle::int_to_node;
254
255    #[test]
256    fn get_root() {
257        let leaf0 = int_to_node(0);
258        let leaf1 = int_to_node(1);
259        let leaf2 = int_to_node(2);
260        let leaf3 = int_to_node(3);
261
262        let parent0 = calculate_parent_hash(leaf0, 0, leaf1);
263        let parent1 = calculate_parent_hash(leaf2, 2, leaf3);
264
265        let root_exp = calculate_parent_hash(parent0, 0, parent1);
266
267        let set = super::MerklePathSet::new(2)
268            .with_paths([(0, leaf0, vec![leaf1, parent1].into())])
269            .unwrap();
270
271        assert_eq!(set.root(), root_exp);
272    }
273
274    #[test]
275    fn add_and_get_path() {
276        let path_6 = vec![int_to_node(7), int_to_node(45), int_to_node(123)];
277        let hash_6 = int_to_node(6);
278        let index = 6_u64;
279        let depth = 3_u8;
280        let set = super::MerklePathSet::new(depth)
281            .with_paths([(index, hash_6, path_6.clone().into())])
282            .unwrap();
283        let stored_path_6 = set.get_path(NodeIndex::make(depth, index)).unwrap();
284
285        assert_eq!(path_6, *stored_path_6);
286    }
287
288    #[test]
289    fn get_node() {
290        let path_6 = vec![int_to_node(7), int_to_node(45), int_to_node(123)];
291        let hash_6 = int_to_node(6);
292        let index = 6_u64;
293        let depth = 3_u8;
294        let set = MerklePathSet::new(depth)
295            .with_paths([(index, hash_6, path_6.into())])
296            .unwrap();
297
298        assert_eq!(
299            int_to_node(6u64),
300            set.get_node(NodeIndex::make(depth, index)).unwrap()
301        );
302    }
303
304    #[test]
305    fn update_leaf() {
306        let hash_4 = int_to_node(4);
307        let hash_5 = int_to_node(5);
308        let hash_6 = int_to_node(6);
309        let hash_7 = int_to_node(7);
310        let hash_45 = calculate_parent_hash(hash_4, 12u64, hash_5);
311        let hash_67 = calculate_parent_hash(hash_6, 14u64, hash_7);
312
313        let hash_0123 = int_to_node(123);
314
315        let path_6 = vec![hash_7, hash_45, hash_0123];
316        let path_5 = vec![hash_4, hash_67, hash_0123];
317        let path_4 = vec![hash_5, hash_67, hash_0123];
318
319        let index_6 = 6_u64;
320        let index_5 = 5_u64;
321        let index_4 = 4_u64;
322        let depth = 3_u8;
323        let mut set = MerklePathSet::new(depth)
324            .with_paths([
325                (index_6, hash_6, path_6.into()),
326                (index_5, hash_5, path_5.into()),
327                (index_4, hash_4, path_4.into()),
328            ])
329            .unwrap();
330
331        let new_hash_6 = int_to_node(100);
332        let new_hash_5 = int_to_node(55);
333
334        set.update_leaf(index_6, new_hash_6).unwrap();
335        let new_path_4 = set.get_path(NodeIndex::make(depth, index_4)).unwrap();
336        let new_hash_67 = calculate_parent_hash(new_hash_6, 14_u64, hash_7);
337        assert_eq!(new_hash_67, new_path_4[1]);
338
339        set.update_leaf(index_5, new_hash_5).unwrap();
340        let new_path_4 = set.get_path(NodeIndex::make(depth, index_4)).unwrap();
341        let new_path_6 = set.get_path(NodeIndex::make(depth, index_6)).unwrap();
342        let new_hash_45 = calculate_parent_hash(new_hash_5, 13_u64, hash_4);
343        assert_eq!(new_hash_45, new_path_6[1]);
344        assert_eq!(new_hash_5, new_path_4[0]);
345    }
346
347    #[test]
348    fn depth_3_is_correct() {
349        let a = int_to_node(1);
350        let b = int_to_node(2);
351        let c = int_to_node(3);
352        let d = int_to_node(4);
353        let e = int_to_node(5);
354        let f = int_to_node(6);
355        let g = int_to_node(7);
356        let h = int_to_node(8);
357
358        let i = Rpo256::merge(&[a.into(), b.into()]);
359        let j = Rpo256::merge(&[c.into(), d.into()]);
360        let k = Rpo256::merge(&[e.into(), f.into()]);
361        let l = Rpo256::merge(&[g.into(), h.into()]);
362
363        let m = Rpo256::merge(&[i.into(), j.into()]);
364        let n = Rpo256::merge(&[k.into(), l.into()]);
365
366        let root = Rpo256::merge(&[m.into(), n.into()]);
367
368        let mut set = MerklePathSet::new(3);
369
370        let value = b;
371        let index = 1;
372        let path = MerklePath::new([a.into(), j.into(), n.into()].to_vec());
373        set.add_path(index, value, path.clone()).unwrap();
374        assert_eq!(value, set.get_leaf(index).unwrap());
375        assert_eq!(Word::from(root), set.root());
376
377        let value = e;
378        let index = 4;
379        let path = MerklePath::new([f.into(), l.into(), m.into()].to_vec());
380        set.add_path(index, value, path.clone()).unwrap();
381        assert_eq!(value, set.get_leaf(index).unwrap());
382        assert_eq!(Word::from(root), set.root());
383
384        let value = a;
385        let index = 0;
386        let path = MerklePath::new([b.into(), j.into(), n.into()].to_vec());
387        set.add_path(index, value, path.clone()).unwrap();
388        assert_eq!(value, set.get_leaf(index).unwrap());
389        assert_eq!(Word::from(root), set.root());
390
391        let value = h;
392        let index = 7;
393        let path = MerklePath::new([g.into(), k.into(), m.into()].to_vec());
394        set.add_path(index, value, path.clone()).unwrap();
395        assert_eq!(value, set.get_leaf(index).unwrap());
396        assert_eq!(Word::from(root), set.root());
397    }
398
399    // HELPER FUNCTIONS
400    // --------------------------------------------------------------------------------------------
401
402    const fn is_even(pos: u64) -> bool {
403        pos & 1 == 0
404    }
405
406    /// Calculates the hash of the parent node by two sibling ones
407    /// - node — current node
408    /// - node_pos — position of the current node
409    /// - sibling — neighboring vertex in the tree
410    fn calculate_parent_hash(node: Word, node_pos: u64, sibling: Word) -> Word {
411        if is_even(node_pos) {
412            Rpo256::merge(&[node.into(), sibling.into()]).into()
413        } else {
414            Rpo256::merge(&[sibling.into(), node.into()]).into()
415        }
416    }
417}