miden-crypto/src/merkle/simple_smt/mod.rs
src/merkle/simple_smt/mod.rsRaw
1use super::{
2 BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNodeInfo, MerkleError, MerklePath, MerkleTreeDelta,
3 NodeIndex, Rpo256, RpoDigest, StoreNode, TryApplyDiff, Vec, Word,
4};
5
6#[cfg(test)]
7mod tests;
8
9// SPARSE MERKLE TREE
10// ================================================================================================
11
12/// A sparse Merkle tree with 64-bit keys and 4-element leaf values, without compaction.
13///
14/// The root of the tree is recomputed on each new leaf update.
15#[derive(Debug, Clone, PartialEq, Eq)]
16#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
17pub struct SimpleSmt {
18 depth: u8,
19 root: RpoDigest,
20 leaves: BTreeMap<u64, Word>,
21 branches: BTreeMap<NodeIndex, BranchNode>,
22}
23
24impl SimpleSmt {
25 // CONSTANTS
26 // --------------------------------------------------------------------------------------------
27
28 /// Minimum supported depth.
29 pub const MIN_DEPTH: u8 = 1;
30
31 /// Maximum supported depth.
32 pub const MAX_DEPTH: u8 = 64;
33
34 /// Value of an empty leaf.
35 pub const EMPTY_VALUE: Word = super::EMPTY_WORD;
36
37 // CONSTRUCTORS
38 // --------------------------------------------------------------------------------------------
39
40 /// Returns a new [SimpleSmt] instantiated with the specified depth.
41 ///
42 /// All leaves in the returned tree are set to [ZERO; 4].
43 ///
44 /// # Errors
45 /// Returns an error if the depth is 0 or is greater than 64.
46 pub fn new(depth: u8) -> Result<Self, MerkleError> {
47 // validate the range of the depth.
48 if depth < Self::MIN_DEPTH {
49 return Err(MerkleError::DepthTooSmall(depth));
50 } else if Self::MAX_DEPTH < depth {
51 return Err(MerkleError::DepthTooBig(depth as u64));
52 }
53
54 let root = *EmptySubtreeRoots::entry(depth, 0);
55
56 Ok(Self {
57 root,
58 depth,
59 leaves: BTreeMap::new(),
60 branches: BTreeMap::new(),
61 })
62 }
63
64 /// Returns a new [SimpleSmt] instantiated with the specified depth and with leaves
65 /// set as specified by the provided entries.
66 ///
67 /// All leaves omitted from the entries list are set to [ZERO; 4].
68 ///
69 /// # Errors
70 /// Returns an error if:
71 /// - If the depth is 0 or is greater than 64.
72 /// - The number of entries exceeds the maximum tree capacity, that is 2^{depth}.
73 /// - The provided entries contain multiple values for the same key.
74 pub fn with_leaves<R, I>(depth: u8, entries: R) -> Result<Self, MerkleError>
75 where
76 R: IntoIterator<IntoIter = I>,
77 I: Iterator<Item = (u64, Word)> + ExactSizeIterator,
78 {
79 // create an empty tree
80 let mut tree = Self::new(depth)?;
81
82 // check if the number of leaves can be accommodated by the tree's depth; we use a min
83 // depth of 63 because we consider passing in a vector of size 2^64 infeasible.
84 let entries = entries.into_iter();
85 let max = 1 << tree.depth.min(63);
86 if entries.len() > max {
87 return Err(MerkleError::InvalidNumEntries(max, entries.len()));
88 }
89
90 // This being a sparse data structure, the EMPTY_WORD is not assigned to the `BTreeMap`, so
91 // entries with the empty value need additional tracking.
92 let mut key_set_to_zero = BTreeSet::new();
93
94 for (key, value) in entries {
95 let old_value = tree.update_leaf(key, value)?;
96
97 if old_value != Self::EMPTY_VALUE || key_set_to_zero.contains(&key) {
98 return Err(MerkleError::DuplicateValuesForIndex(key));
99 }
100
101 if value == Self::EMPTY_VALUE {
102 key_set_to_zero.insert(key);
103 };
104 }
105 Ok(tree)
106 }
107
108 /// Wrapper around [`SimpleSmt::with_leaves`] which inserts leaves at contiguous indices
109 /// starting at index 0.
110 pub fn with_contiguous_leaves<R, I>(depth: u8, entries: R) -> Result<Self, MerkleError>
111 where
112 R: IntoIterator<IntoIter = I>,
113 I: Iterator<Item = Word> + ExactSizeIterator,
114 {
115 Self::with_leaves(
116 depth,
117 entries
118 .into_iter()
119 .enumerate()
120 .map(|(idx, word)| (idx.try_into().expect("tree max depth is 2^8"), word)),
121 )
122 }
123
124 // PUBLIC ACCESSORS
125 // --------------------------------------------------------------------------------------------
126
127 /// Returns the root of this Merkle tree.
128 pub const fn root(&self) -> RpoDigest {
129 self.root
130 }
131
132 /// Returns the depth of this Merkle tree.
133 pub const fn depth(&self) -> u8 {
134 self.depth
135 }
136
137 /// Returns a node at the specified index.
138 ///
139 /// # Errors
140 /// Returns an error if the specified index has depth set to 0 or the depth is greater than
141 /// the depth of this Merkle tree.
142 pub fn get_node(&self, index: NodeIndex) -> Result<RpoDigest, MerkleError> {
143 if index.is_root() {
144 Err(MerkleError::DepthTooSmall(index.depth()))
145 } else if index.depth() > self.depth() {
146 Err(MerkleError::DepthTooBig(index.depth() as u64))
147 } else if index.depth() == self.depth() {
148 // the lookup in empty_hashes could fail only if empty_hashes were not built correctly
149 // by the constructor as we check the depth of the lookup above.
150 let leaf_pos = index.value();
151 let leaf = match self.get_leaf_node(leaf_pos) {
152 Some(word) => word.into(),
153 None => *EmptySubtreeRoots::entry(self.depth, index.depth()),
154 };
155 Ok(leaf)
156 } else {
157 Ok(self.get_branch_node(&index).parent())
158 }
159 }
160
161 /// Returns a value of the leaf at the specified index.
162 ///
163 /// # Errors
164 /// Returns an error if the index is greater than the maximum tree capacity, that is 2^{depth}.
165 pub fn get_leaf(&self, index: u64) -> Result<Word, MerkleError> {
166 let index = NodeIndex::new(self.depth, index)?;
167 Ok(self.get_node(index)?.into())
168 }
169
170 /// Returns a Merkle path from the node at the specified index to the root.
171 ///
172 /// The node itself is not included in the path.
173 ///
174 /// # Errors
175 /// Returns an error if the specified index has depth set to 0 or the depth is greater than
176 /// the depth of this Merkle tree.
177 pub fn get_path(&self, mut index: NodeIndex) -> Result<MerklePath, MerkleError> {
178 if index.is_root() {
179 return Err(MerkleError::DepthTooSmall(index.depth()));
180 } else if index.depth() > self.depth() {
181 return Err(MerkleError::DepthTooBig(index.depth() as u64));
182 }
183
184 let mut path = Vec::with_capacity(index.depth() as usize);
185 for _ in 0..index.depth() {
186 let is_right = index.is_value_odd();
187 index.move_up();
188 let BranchNode { left, right } = self.get_branch_node(&index);
189 let value = if is_right { left } else { right };
190 path.push(value);
191 }
192 Ok(MerklePath::new(path))
193 }
194
195 /// Return a Merkle path from the leaf at the specified index to the root.
196 ///
197 /// The leaf itself is not included in the path.
198 ///
199 /// # Errors
200 /// Returns an error if the index is greater than the maximum tree capacity, that is 2^{depth}.
201 pub fn get_leaf_path(&self, index: u64) -> Result<MerklePath, MerkleError> {
202 let index = NodeIndex::new(self.depth(), index)?;
203 self.get_path(index)
204 }
205
206 // ITERATORS
207 // --------------------------------------------------------------------------------------------
208
209 /// Returns an iterator over the leaves of this [SimpleSmt].
210 pub fn leaves(&self) -> impl Iterator<Item = (u64, &Word)> {
211 self.leaves.iter().map(|(i, w)| (*i, w))
212 }
213
214 /// Returns an iterator over the inner nodes of this Merkle tree.
215 pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
216 self.branches.values().map(|e| InnerNodeInfo {
217 value: e.parent(),
218 left: e.left,
219 right: e.right,
220 })
221 }
222
223 // STATE MUTATORS
224 // --------------------------------------------------------------------------------------------
225
226 /// Updates value of the leaf at the specified index returning the old leaf value.
227 ///
228 /// This also recomputes all hashes between the leaf and the root, updating the root itself.
229 ///
230 /// # Errors
231 /// Returns an error if the index is greater than the maximum tree capacity, that is 2^{depth}.
232 pub fn update_leaf(&mut self, index: u64, value: Word) -> Result<Word, MerkleError> {
233 // validate the index before modifying the structure
234 let mut idx = NodeIndex::new(self.depth(), index)?;
235
236 let old_value = self.insert_leaf_node(index, value).unwrap_or(Self::EMPTY_VALUE);
237
238 // if the old value and new value are the same, there is nothing to update
239 if value == old_value {
240 return Ok(value);
241 }
242
243 let mut value = RpoDigest::from(value);
244 for _ in 0..idx.depth() {
245 let is_right = idx.is_value_odd();
246 idx.move_up();
247 let BranchNode { left, right } = self.get_branch_node(&idx);
248 let (left, right) = if is_right { (left, value) } else { (value, right) };
249 self.insert_branch_node(idx, left, right);
250 value = Rpo256::merge(&[left, right]);
251 }
252 self.root = value;
253 Ok(old_value)
254 }
255
256 // HELPER METHODS
257 // --------------------------------------------------------------------------------------------
258
259 fn get_leaf_node(&self, key: u64) -> Option<Word> {
260 self.leaves.get(&key).copied()
261 }
262
263 fn insert_leaf_node(&mut self, key: u64, node: Word) -> Option<Word> {
264 self.leaves.insert(key, node)
265 }
266
267 fn get_branch_node(&self, index: &NodeIndex) -> BranchNode {
268 self.branches.get(index).cloned().unwrap_or_else(|| {
269 let node = EmptySubtreeRoots::entry(self.depth, index.depth() + 1);
270 BranchNode { left: *node, right: *node }
271 })
272 }
273
274 fn insert_branch_node(&mut self, index: NodeIndex, left: RpoDigest, right: RpoDigest) {
275 let branch = BranchNode { left, right };
276 self.branches.insert(index, branch);
277 }
278}
279
280// BRANCH NODE
281// ================================================================================================
282
283#[derive(Debug, Default, Clone, PartialEq, Eq)]
284#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
285struct BranchNode {
286 left: RpoDigest,
287 right: RpoDigest,
288}
289
290impl BranchNode {
291 fn parent(&self) -> RpoDigest {
292 Rpo256::merge(&[self.left, self.right])
293 }
294}
295
296// TRY APPLY DIFF
297// ================================================================================================
298impl TryApplyDiff<RpoDigest, StoreNode> for SimpleSmt {
299 type Error = MerkleError;
300 type DiffType = MerkleTreeDelta;
301
302 fn try_apply(&mut self, diff: MerkleTreeDelta) -> Result<(), MerkleError> {
303 if diff.depth() != self.depth() {
304 return Err(MerkleError::InvalidDepth {
305 expected: self.depth(),
306 provided: diff.depth(),
307 });
308 }
309
310 for slot in diff.cleared_slots() {
311 self.update_leaf(*slot, Self::EMPTY_VALUE)?;
312 }
313
314 for (slot, value) in diff.updated_slots() {
315 self.update_leaf(*slot, *value)?;
316 }
317
318 Ok(())
319 }
320}