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