miden-crypto/src/merkle/store/mod.rs
src/merkle/store/mod.rsRaw
1use super::{
2 BTreeMap, BTreeSet, EmptySubtreeRoots, MerkleError, MerklePath, MerklePathSet, MerkleTree,
3 NodeIndex, RootPath, Rpo256, RpoDigest, SimpleSmt, ValuePath, Vec, Word,
4};
5use crate::utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable};
6
7#[cfg(test)]
8mod tests;
9
10#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
11pub struct Node {
12 left: RpoDigest,
13 right: RpoDigest,
14}
15
16/// An in-memory data store for Merkle-lized data.
17///
18/// This is a in memory data store for Merkle trees, this store allows all the nodes of multiple
19/// trees to live as long as necessary and without duplication, this allows the implementation of
20/// space efficient persistent data structures.
21///
22/// Example usage:
23///
24/// ```rust
25/// # use miden_crypto::{ZERO, Felt, Word};
26/// # use miden_crypto::merkle::{NodeIndex, MerkleStore, MerkleTree};
27/// # use miden_crypto::hash::rpo::Rpo256;
28/// # const fn int_to_node(value: u64) -> Word {
29/// # [Felt::new(value), ZERO, ZERO, ZERO]
30/// # }
31/// # let A = int_to_node(1);
32/// # let B = int_to_node(2);
33/// # let C = int_to_node(3);
34/// # let D = int_to_node(4);
35/// # let E = int_to_node(5);
36/// # let F = int_to_node(6);
37/// # let G = int_to_node(7);
38/// # let H0 = int_to_node(8);
39/// # let H1 = int_to_node(9);
40/// # let T0 = MerkleTree::new([A, B, C, D, E, F, G, H0].to_vec()).expect("even number of leaves provided");
41/// # let T1 = MerkleTree::new([A, B, C, D, E, F, G, H1].to_vec()).expect("even number of leaves provided");
42/// # let ROOT0 = T0.root();
43/// # let ROOT1 = T1.root();
44/// let mut store = MerkleStore::new();
45///
46/// // the store is initialized with the SMT empty nodes
47/// assert_eq!(store.num_internal_nodes(), 255);
48///
49/// // populates the store with two merkle trees, common nodes are shared
50/// store.add_merkle_tree([A, B, C, D, E, F, G, H0]);
51/// store.add_merkle_tree([A, B, C, D, E, F, G, H1]);
52///
53/// // every leaf except the last are the same
54/// for i in 0..7 {
55/// let d0 = store.get_node(ROOT0, NodeIndex::new(3, i)).unwrap();
56/// let d1 = store.get_node(ROOT1, NodeIndex::new(3, i)).unwrap();
57/// assert_eq!(d0, d1, "Both trees have the same leaf at pos {i}");
58/// }
59///
60/// // The leafs A-B-C-D are the same for both trees, so are their 2 immediate parents
61/// for i in 0..4 {
62/// let d0 = store.get_path(ROOT0, NodeIndex::new(3, i)).unwrap();
63/// let d1 = store.get_path(ROOT1, NodeIndex::new(3, i)).unwrap();
64/// assert_eq!(d0.path[0..2], d1.path[0..2], "Both sub-trees are equal up to two levels");
65/// }
66///
67/// // Common internal nodes are shared, the two added trees have a total of 30, but the store has
68/// // only 10 new entries, corresponding to the 10 unique internal nodes of these trees.
69/// assert_eq!(store.num_internal_nodes() - 255, 10);
70/// ```
71#[derive(Debug, Clone, Eq, PartialEq)]
72pub struct MerkleStore {
73 nodes: BTreeMap<RpoDigest, Node>,
74}
75
76impl Default for MerkleStore {
77 fn default() -> Self {
78 Self::new()
79 }
80}
81
82impl MerkleStore {
83 // CONSTRUCTORS
84 // --------------------------------------------------------------------------------------------
85
86 /// Creates an empty `MerkleStore` instance.
87 pub fn new() -> MerkleStore {
88 // pre-populate the store with the empty hashes
89 let subtrees = EmptySubtreeRoots::empty_hashes(255);
90 let nodes = subtrees
91 .iter()
92 .rev()
93 .copied()
94 .zip(subtrees.iter().rev().skip(1).copied())
95 .map(|(child, parent)| {
96 (
97 parent,
98 Node {
99 left: child,
100 right: child,
101 },
102 )
103 })
104 .collect();
105
106 MerkleStore { nodes }
107 }
108
109 /// Appends the provided merkle tree represented by its `leaves` to the set.
110 pub fn with_merkle_tree<I>(mut self, leaves: I) -> Result<Self, MerkleError>
111 where
112 I: IntoIterator<Item = Word>,
113 {
114 self.add_merkle_tree(leaves)?;
115 Ok(self)
116 }
117
118 /// Appends the provided Sparse Merkle tree represented by its `entries` to the set.
119 ///
120 /// For more information, check [MerkleStore::add_sparse_merkle_tree].
121 pub fn with_sparse_merkle_tree<R, I>(
122 mut self,
123 depth: u8,
124 entries: R,
125 ) -> Result<Self, MerkleError>
126 where
127 R: IntoIterator<IntoIter = I>,
128 I: Iterator<Item = (u64, Word)> + ExactSizeIterator,
129 {
130 self.add_sparse_merkle_tree(depth, entries)?;
131 Ok(self)
132 }
133
134 /// Appends the provided merkle path set.
135 pub fn with_merkle_path(
136 mut self,
137 index_value: u64,
138 node: Word,
139 path: MerklePath,
140 ) -> Result<Self, MerkleError> {
141 self.add_merkle_path(index_value, node, path)?;
142 Ok(self)
143 }
144
145 /// Appends the provided merkle path set.
146 pub fn with_merkle_paths<I>(mut self, paths: I) -> Result<Self, MerkleError>
147 where
148 I: IntoIterator<Item = (u64, Word, MerklePath)>,
149 {
150 self.add_merkle_paths(paths)?;
151 Ok(self)
152 }
153
154 // PUBLIC ACCESSORS
155 // --------------------------------------------------------------------------------------------
156
157 /// Return a count of the non-leaf nodes in the store.
158 pub fn num_internal_nodes(&self) -> usize {
159 self.nodes.len()
160 }
161
162 /// Returns the node at `index` rooted on the tree `root`.
163 ///
164 /// # Errors
165 ///
166 /// This method can return the following errors:
167 /// - `RootNotInStore` if the `root` is not present in the store.
168 /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
169 pub fn get_node(&self, root: Word, index: NodeIndex) -> Result<Word, MerkleError> {
170 let mut hash: RpoDigest = root.into();
171
172 // corner case: check the root is in the store when called with index `NodeIndex::root()`
173 self.nodes
174 .get(&hash)
175 .ok_or(MerkleError::RootNotInStore(hash.into()))?;
176
177 for bit in index.bit_iterator().rev() {
178 let node = self
179 .nodes
180 .get(&hash)
181 .ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
182 hash = if bit { node.right } else { node.left }
183 }
184
185 Ok(hash.into())
186 }
187
188 /// Returns the node at the specified `index` and its opening to the `root`.
189 ///
190 /// The path starts at the sibling of the target leaf.
191 ///
192 /// # Errors
193 ///
194 /// This method can return the following errors:
195 /// - `RootNotInStore` if the `root` is not present in the store.
196 /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
197 pub fn get_path(&self, root: Word, index: NodeIndex) -> Result<ValuePath, MerkleError> {
198 let mut hash: RpoDigest = root.into();
199 let mut path = Vec::with_capacity(index.depth().into());
200
201 // corner case: check the root is in the store when called with index `NodeIndex::root()`
202 self.nodes
203 .get(&hash)
204 .ok_or(MerkleError::RootNotInStore(hash.into()))?;
205
206 for bit in index.bit_iterator().rev() {
207 let node = self
208 .nodes
209 .get(&hash)
210 .ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
211
212 hash = if bit {
213 path.push(node.left.into());
214 node.right
215 } else {
216 path.push(node.right.into());
217 node.left
218 }
219 }
220
221 // the path is computed from root to leaf, so it must be reversed
222 path.reverse();
223
224 Ok(ValuePath {
225 value: hash.into(),
226 path: MerklePath::new(path),
227 })
228 }
229
230 // STATE MUTATORS
231 // --------------------------------------------------------------------------------------------
232
233 /// Adds all the nodes of a Merkle tree represented by `leaves`.
234 ///
235 /// This will instantiate a Merkle tree using `leaves` and include all the nodes into the
236 /// store.
237 ///
238 /// # Errors
239 ///
240 /// This method may return the following errors:
241 /// - `DepthTooSmall` if leaves is empty or contains only 1 element
242 /// - `NumLeavesNotPowerOfTwo` if the number of leaves is not a power-of-two
243 pub fn add_merkle_tree<I>(&mut self, leaves: I) -> Result<Word, MerkleError>
244 where
245 I: IntoIterator<Item = Word>,
246 {
247 let leaves: Vec<_> = leaves.into_iter().collect();
248 if leaves.len() < 2 {
249 return Err(MerkleError::DepthTooSmall(leaves.len() as u8));
250 }
251
252 let tree = MerkleTree::new(leaves)?;
253 for node in tree.inner_nodes() {
254 self.nodes.insert(
255 node.value.into(),
256 Node {
257 left: node.left.into(),
258 right: node.right.into(),
259 },
260 );
261 }
262
263 Ok(tree.root())
264 }
265
266 /// Adds a Sparse Merkle tree defined by the specified `entries` to the store, and returns the
267 /// root of the added tree.
268 ///
269 /// The entries are expected to contain tuples of `(index, node)` describing nodes in the tree
270 /// at `depth`.
271 ///
272 /// # Errors
273 /// Returns an error if the provided `depth` is greater than [SimpleSmt::MAX_DEPTH].
274 pub fn add_sparse_merkle_tree<R, I>(
275 &mut self,
276 depth: u8,
277 entries: R,
278 ) -> Result<Word, MerkleError>
279 where
280 R: IntoIterator<IntoIter = I>,
281 I: Iterator<Item = (u64, Word)> + ExactSizeIterator,
282 {
283 let smt = SimpleSmt::new(depth)?.with_leaves(entries)?;
284 for node in smt.inner_nodes() {
285 self.nodes.insert(
286 node.value.into(),
287 Node {
288 left: node.left.into(),
289 right: node.right.into(),
290 },
291 );
292 }
293
294 Ok(smt.root())
295 }
296
297 /// Adds all the nodes of a Merkle path represented by `path`, opening to `node`. Returns the
298 /// new root.
299 ///
300 /// This will compute the sibling elements determined by the Merkle `path` and `node`, and
301 /// include all the nodes into the store.
302 pub fn add_merkle_path(
303 &mut self,
304 index_value: u64,
305 mut node: Word,
306 path: MerklePath,
307 ) -> Result<Word, MerkleError> {
308 let mut index = NodeIndex::new(self.nodes.len() as u8, index_value);
309
310 for sibling in path {
311 let (left, right) = match index.is_value_odd() {
312 true => (sibling, node),
313 false => (node, sibling),
314 };
315 let parent = Rpo256::merge(&[left.into(), right.into()]);
316 self.nodes.insert(
317 parent,
318 Node {
319 left: left.into(),
320 right: right.into(),
321 },
322 );
323
324 index.move_up();
325 node = parent.into();
326 }
327
328 Ok(node)
329 }
330
331 /// Adds all the nodes of multiple Merkle paths into the store.
332 ///
333 /// This will compute the sibling elements for each Merkle `path` and include all the nodes
334 /// into the store.
335 ///
336 /// For further reference, check [MerkleStore::add_merkle_path].
337 ///
338 /// # Errors
339 ///
340 /// Every path must resolve to the same root, otherwise this will return an `ConflictingRoots`
341 /// error.
342 pub fn add_merkle_paths<I>(&mut self, paths: I) -> Result<Word, MerkleError>
343 where
344 I: IntoIterator<Item = (u64, Word, MerklePath)>,
345 {
346 let paths: Vec<(u64, Word, MerklePath)> = paths.into_iter().collect();
347
348 let roots: BTreeSet<RpoDigest> = paths
349 .iter()
350 .map(|(index, node, path)| path.compute_root(*index, *node).into())
351 .collect();
352
353 if roots.len() != 1 {
354 return Err(MerkleError::ConflictingRoots(
355 roots.iter().map(|v| Word::from(*v)).collect(),
356 ));
357 }
358
359 for (index_value, node, path) in paths {
360 self.add_merkle_path(index_value, node, path)?;
361 }
362
363 Ok(roots.iter().next().unwrap().into())
364 }
365
366 /// Appends the provided [MerklePathSet] into the store.
367 ///
368 /// For further reference, check [MerkleStore::add_merkle_path].
369 pub fn add_merkle_path_set(&mut self, path_set: &MerklePathSet) -> Result<Word, MerkleError> {
370 let root = path_set.root();
371 for (index, path) in path_set.to_paths() {
372 self.add_merkle_path(index, path.value, path.path)?;
373 }
374 Ok(root)
375 }
376
377 /// Sets a node to `value`.
378 ///
379 /// # Errors
380 ///
381 /// This method can return the following errors:
382 /// - `RootNotInStore` if the `root` is not present in the store.
383 /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
384 pub fn set_node(
385 &mut self,
386 mut root: Word,
387 index: NodeIndex,
388 value: Word,
389 ) -> Result<RootPath, MerkleError> {
390 let node = value;
391 let ValuePath { value, path } = self.get_path(root, index)?;
392
393 // performs the update only if the node value differs from the opening
394 if node != value {
395 root = self.add_merkle_path(index.value(), node, path.clone())?;
396 }
397
398 Ok(RootPath { root, path })
399 }
400
401 pub fn merge_roots(&mut self, root1: Word, root2: Word) -> Result<Word, MerkleError> {
402 let root1: RpoDigest = root1.into();
403 let root2: RpoDigest = root2.into();
404
405 if !self.nodes.contains_key(&root1) {
406 Err(MerkleError::NodeNotInStore(
407 root1.into(),
408 NodeIndex::new(0, 0),
409 ))
410 } else if !self.nodes.contains_key(&root1) {
411 Err(MerkleError::NodeNotInStore(
412 root2.into(),
413 NodeIndex::new(0, 0),
414 ))
415 } else {
416 let parent: Word = Rpo256::merge(&[root1, root2]).into();
417 self.nodes.insert(
418 parent.into(),
419 Node {
420 left: root1,
421 right: root2,
422 },
423 );
424
425 Ok(parent)
426 }
427 }
428}
429
430// SERIALIZATION
431// ================================================================================================
432
433impl Serializable for Node {
434 fn write_into<W: ByteWriter>(&self, target: &mut W) {
435 self.left.write_into(target);
436 self.right.write_into(target);
437 }
438}
439
440impl Deserializable for Node {
441 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
442 let left = RpoDigest::read_from(source)?;
443 let right = RpoDigest::read_from(source)?;
444 Ok(Node { left, right })
445 }
446}
447
448impl Serializable for MerkleStore {
449 fn write_into<W: ByteWriter>(&self, target: &mut W) {
450 target.write_u64(self.nodes.len() as u64);
451
452 for (k, v) in self.nodes.iter() {
453 k.write_into(target);
454 v.write_into(target);
455 }
456 }
457}
458
459impl Deserializable for MerkleStore {
460 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
461 let len = source.read_u64()?;
462 let mut nodes: BTreeMap<RpoDigest, Node> = BTreeMap::new();
463
464 for _ in 0..len {
465 let key = RpoDigest::read_from(source)?;
466 let value = Node::read_from(source)?;
467 nodes.insert(key, value);
468 }
469
470 Ok(MerkleStore { nodes })
471 }
472}