miden-crypto/src/merkle/store/mod.rs
src/merkle/store/mod.rsRaw
1//! An in-memory data store for Merkle-lized data
2//!
3//! This is a in memory data store for Merkle trees, this store allows all the nodes of a tree
4//! (leaves or internal) to live as long as necessary and without duplication, this allows the
5//! implementation of efficient persistent data structures
6use super::{
7 BTreeMap, BTreeSet, EmptySubtreeRoots, MerkleError, MerklePath, MerklePathSet, MerkleTree,
8 NodeIndex, Rpo256, RpoDigest, SimpleSmt, Vec, Word,
9};
10
11#[cfg(test)]
12mod tests;
13
14#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
15pub struct Node {
16 left: RpoDigest,
17 right: RpoDigest,
18}
19
20#[derive(Debug, Clone, Eq, PartialEq)]
21pub struct MerkleStore {
22 nodes: BTreeMap<RpoDigest, Node>,
23}
24
25impl Default for MerkleStore {
26 fn default() -> Self {
27 Self::new()
28 }
29}
30
31impl MerkleStore {
32 // CONSTRUCTORS
33 // --------------------------------------------------------------------------------------------
34
35 /// Creates an empty `MerkleStore` instance.
36 pub fn new() -> MerkleStore {
37 // pre-populate the store with the empty hashes
38 let subtrees = EmptySubtreeRoots::empty_hashes(64);
39 let nodes = subtrees
40 .iter()
41 .copied()
42 .zip(subtrees.iter().skip(1).copied())
43 .map(|(child, parent)| {
44 (
45 parent,
46 Node {
47 left: child,
48 right: child,
49 },
50 )
51 })
52 .collect();
53
54 MerkleStore { nodes }
55 }
56
57 /// Appends the provided merkle tree represented by its `leaves` to the set.
58 pub fn with_merkle_tree<I>(mut self, leaves: I) -> Result<Self, MerkleError>
59 where
60 I: IntoIterator<Item = Word>,
61 {
62 self.add_merkle_tree(leaves)?;
63 Ok(self)
64 }
65
66 /// Appends the provided sparse merkle tree represented by its `entries` to the set.
67 pub fn with_sparse_merkle_tree<R, I>(mut self, entries: R) -> Result<Self, MerkleError>
68 where
69 R: IntoIterator<IntoIter = I>,
70 I: Iterator<Item = (u64, Word)> + ExactSizeIterator,
71 {
72 self.add_sparse_merkle_tree(entries)?;
73 Ok(self)
74 }
75
76 /// Appends the provided merkle path set.
77 pub fn with_merkle_path(
78 mut self,
79 index_value: u64,
80 node: Word,
81 path: MerklePath,
82 ) -> Result<Self, MerkleError> {
83 self.add_merkle_path(index_value, node, path)?;
84 Ok(self)
85 }
86
87 // PUBLIC ACCESSORS
88 // --------------------------------------------------------------------------------------------
89
90 /// Returns the node at `index` rooted on the tree `root`.
91 ///
92 /// # Errors
93 ///
94 /// This method can return the following errors:
95 /// - `RootNotInStore` if the `root` is not present in the storage.
96 /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
97 pub fn get_node(&self, root: Word, index: NodeIndex) -> Result<Word, MerkleError> {
98 let mut hash: RpoDigest = root.into();
99
100 // corner case: check the root is in the storage when called with index `NodeIndex::root()`
101 self.nodes
102 .get(&hash)
103 .ok_or(MerkleError::RootNotInStore(hash.into()))?;
104
105 for bit in index.bit_iterator().rev() {
106 let node = self
107 .nodes
108 .get(&hash)
109 .ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
110 hash = if bit { node.right } else { node.left }
111 }
112
113 Ok(hash.into())
114 }
115
116 /// Returns the node at the specified `index` and its opening to the `root`.
117 ///
118 /// The path starts at the sibling of the target leaf.
119 ///
120 /// # Errors
121 ///
122 /// This method can return the following errors:
123 /// - `RootNotInStore` if the `root` is not present in the storage.
124 /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
125 pub fn get_path(
126 &self,
127 root: Word,
128 index: NodeIndex,
129 ) -> Result<(Word, MerklePath), MerkleError> {
130 let mut hash: RpoDigest = root.into();
131 let mut path = Vec::with_capacity(index.depth().into());
132
133 // corner case: check the root is in the storage when called with index `NodeIndex::root()`
134 self.nodes
135 .get(&hash)
136 .ok_or(MerkleError::RootNotInStore(hash.into()))?;
137
138 for bit in index.bit_iterator().rev() {
139 let node = self
140 .nodes
141 .get(&hash)
142 .ok_or(MerkleError::NodeNotInStore(hash.into(), index))?;
143
144 hash = if bit {
145 path.push(node.left.into());
146 node.right
147 } else {
148 path.push(node.right.into());
149 node.left
150 }
151 }
152
153 path.reverse();
154 Ok((hash.into(), MerklePath::new(path)))
155 }
156
157 // STATE MUTATORS
158 // --------------------------------------------------------------------------------------------
159
160 /// Adds all the nodes of a Merkle tree represented by `leaves`.
161 ///
162 /// This will instantiate a Merkle tree using `leaves` and include all the nodes into the
163 /// storage.
164 ///
165 /// # Errors
166 ///
167 /// This method may return the following errors:
168 /// - `DepthTooSmall` if leaves is empty or contains only 1 element
169 /// - `NumLeavesNotPowerOfTwo` if the number of leaves is not a power-of-two
170 pub fn add_merkle_tree<I>(&mut self, leaves: I) -> Result<Word, MerkleError>
171 where
172 I: IntoIterator<Item = Word>,
173 {
174 let leaves: Vec<_> = leaves.into_iter().collect();
175 if leaves.len() < 2 {
176 return Err(MerkleError::DepthTooSmall(leaves.len() as u8));
177 }
178
179 let layers = leaves.len().ilog2();
180 let tree = MerkleTree::new(leaves)?;
181
182 let mut depth = 0;
183 let mut parent_offset = 1;
184 let mut child_offset = 2;
185 while depth < layers {
186 let layer_size = 1usize << depth;
187 for _ in 0..layer_size {
188 // merkle tree is using level form representation, so left and right siblings are
189 // next to each other
190 let left = tree.nodes[child_offset];
191 let right = tree.nodes[child_offset + 1];
192 self.nodes.insert(
193 tree.nodes[parent_offset].into(),
194 Node {
195 left: left.into(),
196 right: right.into(),
197 },
198 );
199 parent_offset += 1;
200 child_offset += 2;
201 }
202 depth += 1;
203 }
204
205 Ok(tree.nodes[1])
206 }
207
208 /// Adds all the nodes of a Sparse Merkle tree represented by `entries`.
209 ///
210 /// This will instantiate a Sparse Merkle tree using `entries` and include all the nodes into
211 /// the storage.
212 ///
213 /// # Errors
214 ///
215 /// This will return `InvalidEntriesCount` if the length of `entries` is not `63`.
216 pub fn add_sparse_merkle_tree<R, I>(&mut self, entries: R) -> Result<Word, MerkleError>
217 where
218 R: IntoIterator<IntoIter = I>,
219 I: Iterator<Item = (u64, Word)> + ExactSizeIterator,
220 {
221 let smt = SimpleSmt::new(SimpleSmt::MAX_DEPTH)?.with_leaves(entries)?;
222 for branch in smt.store.branches.values() {
223 let parent = Rpo256::merge(&[branch.left, branch.right]);
224 self.nodes.insert(
225 parent,
226 Node {
227 left: branch.left,
228 right: branch.right,
229 },
230 );
231 }
232
233 Ok(smt.root())
234 }
235
236 /// Adds all the nodes of a Merkle path represented by `path`.
237 ///
238 /// This will compute the sibling elements determined by the Merkle `path` and `node`, and
239 /// include all the nodes into the storage.
240 pub fn add_merkle_path(
241 &mut self,
242 index_value: u64,
243 node: Word,
244 path: MerklePath,
245 ) -> Result<Word, MerkleError> {
246 let mut node = node;
247 let mut index = NodeIndex::new(self.nodes.len() as u8, index_value);
248
249 for sibling in path {
250 let (left, right) = match index.is_value_odd() {
251 true => (sibling, node),
252 false => (node, sibling),
253 };
254 let parent = Rpo256::merge(&[left.into(), right.into()]);
255 self.nodes.insert(
256 parent,
257 Node {
258 left: left.into(),
259 right: right.into(),
260 },
261 );
262
263 index.move_up();
264 node = parent.into();
265 }
266
267 Ok(node)
268 }
269
270 /// Adds all the nodes of multiple Merkle paths into the store.
271 ///
272 /// This will compute the sibling elements for each Merkle `path` and include all the nodes
273 /// into the storage.
274 ///
275 /// # Errors
276 ///
277 /// Every path must resolve to the same root, otherwise this will return an `ConflictingRoots`
278 /// error.
279 pub fn add_merkle_paths<I>(&mut self, paths: I) -> Result<Word, MerkleError>
280 where
281 I: IntoIterator<Item = (u64, Word, MerklePath)>,
282 {
283 let paths: Vec<(u64, Word, MerklePath)> = paths.into_iter().collect();
284
285 let roots: BTreeSet<RpoDigest> = paths
286 .iter()
287 .map(|(index, node, path)| path.compute_root(*index, *node).into())
288 .collect();
289
290 if roots.len() != 1 {
291 return Err(MerkleError::ConflictingRoots(
292 roots.iter().map(|v| Word::from(*v)).collect(),
293 ));
294 }
295
296 for (index_value, node, path) in paths {
297 self.add_merkle_path(index_value, node, path)?;
298 }
299
300 Ok(roots.iter().next().unwrap().into())
301 }
302
303 /// Appends the provided [MerklePathSet] into the store.
304 pub fn add_merkle_path_set(&mut self, path_set: &MerklePathSet) -> Result<Word, MerkleError> {
305 let root = path_set.root();
306 path_set.indexes().try_fold(root, |_, index| {
307 let node = path_set.get_node(index)?;
308 let path = path_set.get_path(index)?;
309 self.add_merkle_path(index.value(), node, path)
310 })
311 }
312
313 /// Sets a node to `value`.
314 ///
315 /// # Errors
316 ///
317 /// This method can return the following errors:
318 /// - `RootNotInStore` if the `root` is not present in the storage.
319 /// - `NodeNotInStore` if a node needed to traverse from `root` to `index` is not present in the store.
320 pub fn set_node(
321 &mut self,
322 root: Word,
323 index: NodeIndex,
324 value: Word,
325 ) -> Result<Word, MerkleError> {
326 let result = self.get_path(root, index)?;
327 if result.0 != value {
328 self.add_merkle_path(index.value(), value, result.1)
329 } else {
330 Ok(root)
331 }
332 }
333
334 pub fn merge_roots(&mut self, root1: Word, root2: Word) -> Result<Word, MerkleError> {
335 let root1: RpoDigest = root1.into();
336 let root2: RpoDigest = root2.into();
337
338 if !self.nodes.contains_key(&root1) {
339 Err(MerkleError::NodeNotInStore(
340 root1.into(),
341 NodeIndex::new(0, 0),
342 ))
343 } else if !self.nodes.contains_key(&root1) {
344 Err(MerkleError::NodeNotInStore(
345 root2.into(),
346 NodeIndex::new(0, 0),
347 ))
348 } else {
349 let parent: Word = Rpo256::merge(&[root1, root2]).into();
350 self.nodes.insert(
351 parent.into(),
352 Node {
353 left: root1,
354 right: root2,
355 },
356 );
357
358 Ok(parent)
359 }
360 }
361}