miden-crypto/src/merkle/tiered_smt/mod.rs
src/merkle/tiered_smt/mod.rsRaw
1use super::{
2 BTreeMap, BTreeSet, EmptySubtreeRoots, InnerNodeInfo, MerkleError, MerklePath, NodeIndex,
3 Rpo256, RpoDigest, StarkField, Vec, Word,
4};
5use core::{cmp, ops::Deref};
6
7mod nodes;
8use nodes::NodeStore;
9
10mod values;
11use values::ValueStore;
12
13#[cfg(test)]
14mod tests;
15
16// TIERED SPARSE MERKLE TREE
17// ================================================================================================
18
19/// Tiered (compacted) Sparse Merkle tree mapping 256-bit keys to 256-bit values. Both keys and
20/// values are represented by 4 field elements.
21///
22/// Leaves in the tree can exist only on specific depths called "tiers". These depths are: 16, 32,
23/// 48, and 64. Initially, when a tree is empty, it is equivalent to an empty Sparse Merkle tree
24/// of depth 64 (i.e., leaves at depth 64 are set to [ZERO; 4]). As non-empty values are inserted
25/// into the tree they are added to the first available tier.
26///
27/// For example, when the first key-value pair is inserted, it will be stored in a node at depth
28/// 16 such that the 16 most significant bits of the key determine the position of the node at
29/// depth 16. If another value with a key sharing the same 16-bit prefix is inserted, both values
30/// move into the next tier (depth 32). This process is repeated until values end up at the bottom
31/// tier (depth 64). If multiple values have keys with a common 64-bit prefix, such key-value pairs
32/// are stored in a sorted list at the bottom tier.
33///
34/// To differentiate between internal and leaf nodes, node values are computed as follows:
35/// - Internal nodes: hash(left_child, right_child).
36/// - Leaf node at depths 16, 32, or 64: hash(key, value, domain=depth).
37/// - Leaf node at depth 64: hash([key_0, value_0, ..., key_n, value_n, domain=64]).
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct TieredSmt {
40 root: RpoDigest,
41 nodes: NodeStore,
42 values: ValueStore,
43}
44
45impl TieredSmt {
46 // CONSTANTS
47 // --------------------------------------------------------------------------------------------
48
49 /// The number of levels between tiers.
50 const TIER_SIZE: u8 = 16;
51
52 /// Depths at which leaves can exist in a tiered SMT.
53 const TIER_DEPTHS: [u8; 4] = [16, 32, 48, 64];
54
55 /// Maximum node depth. This is also the bottom tier of the tree.
56 const MAX_DEPTH: u8 = 64;
57
58 /// Value of an empty leaf.
59 pub const EMPTY_VALUE: Word = super::empty_roots::EMPTY_WORD;
60
61 // CONSTRUCTORS
62 // --------------------------------------------------------------------------------------------
63
64 /// Returns a new [TieredSmt] instantiated with the specified key-value pairs.
65 ///
66 /// # Errors
67 /// Returns an error if the provided entries contain multiple values for the same key.
68 pub fn with_leaves<R, I>(entries: R) -> Result<Self, MerkleError>
69 where
70 R: IntoIterator<IntoIter = I>,
71 I: Iterator<Item = (RpoDigest, Word)> + ExactSizeIterator,
72 {
73 // create an empty tree
74 let mut tree = Self::default();
75
76 // append leaves to the tree returning an error if a duplicate entry for the same key
77 // is found
78 let mut empty_entries = BTreeSet::new();
79 for (key, value) in entries {
80 let old_value = tree.insert(key, value);
81 if old_value != Self::EMPTY_VALUE || empty_entries.contains(&key) {
82 return Err(MerkleError::DuplicateValuesForKey(key));
83 }
84 // if we've processed an empty entry, add the key to the set of empty entry keys, and
85 // if this key was already in the set, return an error
86 if value == Self::EMPTY_VALUE && !empty_entries.insert(key) {
87 return Err(MerkleError::DuplicateValuesForKey(key));
88 }
89 }
90 Ok(tree)
91 }
92
93 // PUBLIC ACCESSORS
94 // --------------------------------------------------------------------------------------------
95
96 /// Returns the root of this Merkle tree.
97 pub const fn root(&self) -> RpoDigest {
98 self.root
99 }
100
101 /// Returns a node at the specified index.
102 ///
103 /// # Errors
104 /// Returns an error if:
105 /// - The specified index depth is 0 or greater than 64.
106 /// - The node with the specified index does not exists in the Merkle tree. This is possible
107 /// when a leaf node with the same index prefix exists at a tier higher than the requested
108 /// node.
109 pub fn get_node(&self, index: NodeIndex) -> Result<RpoDigest, MerkleError> {
110 self.nodes.get_node(index)
111 }
112
113 /// Returns a Merkle path from the node at the specified index to the root.
114 ///
115 /// The node itself is not included in the path.
116 ///
117 /// # Errors
118 /// Returns an error if:
119 /// - The specified index depth is 0 or greater than 64.
120 /// - The node with the specified index does not exists in the Merkle tree. This is possible
121 /// when a leaf node with the same index prefix exists at a tier higher than the node to
122 /// which the path is requested.
123 pub fn get_path(&self, index: NodeIndex) -> Result<MerklePath, MerkleError> {
124 self.nodes.get_path(index)
125 }
126
127 /// Returns the value associated with the specified key.
128 ///
129 /// If nothing was inserted into this tree for the specified key, [ZERO; 4] is returned.
130 pub fn get_value(&self, key: RpoDigest) -> Word {
131 match self.values.get(&key) {
132 Some(value) => *value,
133 None => Self::EMPTY_VALUE,
134 }
135 }
136
137 // STATE MUTATORS
138 // --------------------------------------------------------------------------------------------
139
140 /// Inserts the provided value into the tree under the specified key and returns the value
141 /// previously stored under this key.
142 ///
143 /// If the value for the specified key was not previously set, [ZERO; 4] is returned.
144 pub fn insert(&mut self, key: RpoDigest, value: Word) -> Word {
145 // if an empty value is being inserted, remove the leaf node to make it look as if the
146 // value was never inserted
147 if value == Self::EMPTY_VALUE {
148 return self.remove_leaf_node(key);
149 }
150
151 // insert the value into the value store, and if the key was already in the store, update
152 // it with the new value
153 if let Some(old_value) = self.values.insert(key, value) {
154 if old_value != value {
155 // if the new value is different from the old value, determine the location of
156 // the leaf node for this key, build the node, and update the root
157 let (index, leaf_exists) = self.nodes.get_leaf_index(&key);
158 debug_assert!(leaf_exists);
159 let node = self.build_leaf_node(index, key, value);
160 self.root = self.nodes.update_leaf_node(index, node);
161 }
162 return old_value;
163 };
164
165 // determine the location for the leaf node; this index could have 3 different meanings:
166 // - it points to a root of an empty subtree or an empty node at depth 64; in this case,
167 // we can replace the node with the value node immediately.
168 // - it points to an existing leaf at the bottom tier (i.e., depth = 64); in this case,
169 // we need to process update the bottom leaf.
170 // - it points to an existing leaf node for a different key with the same prefix (same
171 // key case was handled above); in this case, we need to move the leaf to a lower tier
172 let (index, leaf_exists) = self.nodes.get_leaf_index(&key);
173
174 self.root = if leaf_exists && index.depth() == Self::MAX_DEPTH {
175 // returned index points to a leaf at the bottom tier
176 let node = self.build_leaf_node(index, key, value);
177 self.nodes.update_leaf_node(index, node)
178 } else if leaf_exists {
179 // returned index pointes to a leaf for a different key with the same prefix
180
181 // get the key-value pair for the key with the same prefix; since the key-value
182 // pair has already been inserted into the value store, we need to filter it out
183 // when looking for the other key-value pair
184 let (other_key, other_value) = self
185 .values
186 .get_first_filtered(index_to_prefix(&index), &key)
187 .expect("other key-value pair not found");
188
189 // determine how far down the tree should we move the leaves
190 let common_prefix_len = get_common_prefix_tier_depth(&key, other_key);
191 let depth = cmp::min(common_prefix_len + Self::TIER_SIZE, Self::MAX_DEPTH);
192
193 // compute node locations for new and existing key-value paris
194 let new_index = LeafNodeIndex::from_key(&key, depth);
195 let other_index = LeafNodeIndex::from_key(other_key, depth);
196
197 // compute node values for the new and existing key-value pairs
198 let new_node = self.build_leaf_node(new_index, key, value);
199 let other_node = self.build_leaf_node(other_index, *other_key, *other_value);
200
201 // replace the leaf located at index with a subtree containing nodes for new and
202 // existing key-value paris
203 self.nodes.replace_leaf_with_subtree(
204 index,
205 [(new_index, new_node), (other_index, other_node)],
206 )
207 } else {
208 // returned index points to an empty subtree or an empty leaf at the bottom tier
209 let node = self.build_leaf_node(index, key, value);
210 self.nodes.insert_leaf_node(index, node)
211 };
212
213 Self::EMPTY_VALUE
214 }
215
216 // ITERATORS
217 // --------------------------------------------------------------------------------------------
218
219 /// Returns an iterator over all key-value pairs in this [TieredSmt].
220 pub fn iter(&self) -> impl Iterator<Item = &(RpoDigest, Word)> {
221 self.values.iter()
222 }
223
224 /// Returns an iterator over all inner nodes of this [TieredSmt] (i.e., nodes not at depths 16
225 /// 32, 48, or 64).
226 ///
227 /// The iterator order is unspecified.
228 pub fn inner_nodes(&self) -> impl Iterator<Item = InnerNodeInfo> + '_ {
229 self.nodes.inner_nodes()
230 }
231
232 /// Returns an iterator over upper leaves (i.e., depth = 16, 32, or 48) for this [TieredSmt]
233 /// where each yielded item is a (node, key, value) tuple.
234 ///
235 /// The iterator order is unspecified.
236 pub fn upper_leaves(&self) -> impl Iterator<Item = (RpoDigest, RpoDigest, Word)> + '_ {
237 self.nodes.upper_leaves().map(|(index, node)| {
238 let key_prefix = index_to_prefix(index);
239 let (key, value) = self.values.get_first(key_prefix).expect("upper leaf not found");
240 debug_assert_eq!(*index, LeafNodeIndex::from_key(key, index.depth()).into());
241 (*node, *key, *value)
242 })
243 }
244
245 /// Returns an iterator over bottom leaves (i.e., depth = 64) of this [TieredSmt].
246 ///
247 /// Each yielded item consists of the hash of the leaf and its contents, where contents is
248 /// a vector containing key-value pairs of entries storied in this leaf.
249 ///
250 /// The iterator order is unspecified.
251 pub fn bottom_leaves(&self) -> impl Iterator<Item = (RpoDigest, Vec<(RpoDigest, Word)>)> + '_ {
252 self.nodes.bottom_leaves().map(|(&prefix, node)| {
253 let values = self.values.get_all(prefix).expect("bottom leaf not found");
254 (*node, values)
255 })
256 }
257
258 // HELPER METHODS
259 // --------------------------------------------------------------------------------------------
260
261 /// Removes the node holding the key-value pair for the specified key from this tree, and
262 /// returns the value associated with the specified key.
263 ///
264 /// If no value was associated with the specified key, [ZERO; 4] is returned.
265 fn remove_leaf_node(&mut self, key: RpoDigest) -> Word {
266 // remove the key-value pair from the value store; if no value was associated with the
267 // specified key, return.
268 let old_value = match self.values.remove(&key) {
269 Some(old_value) => old_value,
270 None => return Self::EMPTY_VALUE,
271 };
272
273 // determine the location of the leaf holding the key-value pair to be removed
274 let (index, leaf_exists) = self.nodes.get_leaf_index(&key);
275 debug_assert!(leaf_exists);
276
277 // if the leaf is at the bottom tier and after removing the key-value pair from it, the
278 // leaf is still not empty, just recompute its hash and update the leaf node.
279 if index.depth() == Self::MAX_DEPTH {
280 if let Some(values) = self.values.get_all(index.value()) {
281 let node = hash_bottom_leaf(&values);
282 self.root = self.nodes.update_leaf_node(index, node);
283 return old_value;
284 };
285 }
286
287 // if the removed key-value pair has a lone sibling at the current tier with a root at
288 // higher tier, we need to move the sibling to a higher tier
289 if let Some((sib_key, sib_val, new_sib_index)) = self.values.get_lone_sibling(index) {
290 // determine the current index of the sibling node
291 let sib_index = LeafNodeIndex::from_key(sib_key, index.depth());
292 debug_assert!(sib_index.depth() > new_sib_index.depth());
293
294 // compute node value for the new location of the sibling leaf and replace the subtree
295 // with this leaf node
296 let node = self.build_leaf_node(new_sib_index, *sib_key, *sib_val);
297 let new_sib_depth = new_sib_index.depth();
298 self.root = self.nodes.replace_subtree_with_leaf(index, sib_index, new_sib_depth, node);
299 } else {
300 // if the removed key-value pair did not have a sibling at the current tier with a
301 // root at higher tiers, just clear the leaf node
302 self.root = self.nodes.clear_leaf_node(index);
303 }
304
305 old_value
306 }
307
308 /// Builds and returns a leaf node value for the node located as the specified index.
309 ///
310 /// This method assumes that the key-value pair for the node has already been inserted into
311 /// the value store, however, for depths 16, 32, and 48, the node is computed directly from
312 /// the passed-in values (for depth 64, the value store is queried to get all the key-value
313 /// pairs located at the specified index).
314 fn build_leaf_node(&self, index: LeafNodeIndex, key: RpoDigest, value: Word) -> RpoDigest {
315 let depth = index.depth();
316
317 // insert the key into index-key map and compute the new value of the node
318 if index.depth() == Self::MAX_DEPTH {
319 // for the bottom tier, we add the key-value pair to the existing leaf, or create a
320 // new leaf with this key-value pair
321 let values = self.values.get_all(index.value()).unwrap();
322 hash_bottom_leaf(&values)
323 } else {
324 debug_assert_eq!(self.values.get_first(index_to_prefix(&index)), Some(&(key, value)));
325 hash_upper_leaf(key, value, depth)
326 }
327 }
328}
329
330impl Default for TieredSmt {
331 fn default() -> Self {
332 let root = EmptySubtreeRoots::empty_hashes(Self::MAX_DEPTH)[0];
333 Self {
334 root,
335 nodes: NodeStore::new(root),
336 values: ValueStore::default(),
337 }
338 }
339}
340
341// LEAF NODE INDEX
342// ================================================================================================
343/// A wrapper around [NodeIndex] to provide type-safe references to nodes at depths 16, 32, 48, and
344/// 64.
345#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
346pub struct LeafNodeIndex(NodeIndex);
347
348impl LeafNodeIndex {
349 /// Returns a new [LeafNodeIndex] instantiated from the provided [NodeIndex].
350 ///
351 /// In debug mode, panics if index depth is not 16, 32, 48, or 64.
352 pub fn new(index: NodeIndex) -> Self {
353 // check if the depth is 16, 32, 48, or 64; this works because for a valid depth,
354 // depth - 16, can be 0, 16, 32, or 48 - i.e., the value is either 0 or any of the 4th
355 // or 5th bits are set. We can test for this by computing a bitwise AND with a value
356 // which has all but the 4th and 5th bits set (which is !48).
357 debug_assert_eq!(((index.depth() - 16) & !48), 0, "invalid tier depth {}", index.depth());
358 Self(index)
359 }
360
361 /// Returns a new [LeafNodeIndex] instantiated from the specified key inserted at the specified
362 /// depth.
363 ///
364 /// The value for the key is computed by taking n most significant bits from the most significant
365 /// element of the key, where n is the specified depth.
366 pub fn from_key(key: &RpoDigest, depth: u8) -> Self {
367 let mse = get_key_prefix(key);
368 Self::new(NodeIndex::new_unchecked(depth, mse >> (TieredSmt::MAX_DEPTH - depth)))
369 }
370
371 /// Returns a new [LeafNodeIndex] instantiated for testing purposes.
372 #[cfg(test)]
373 pub fn make(depth: u8, value: u64) -> Self {
374 Self::new(NodeIndex::make(depth, value))
375 }
376
377 /// Traverses towards the root until the specified depth is reached.
378 ///
379 /// The new depth must be a valid tier depth - i.e., 16, 32, 48, or 64.
380 pub fn move_up_to(&mut self, depth: u8) {
381 debug_assert_eq!(((depth - 16) & !48), 0, "invalid tier depth: {depth}");
382 self.0.move_up_to(depth);
383 }
384}
385
386impl Deref for LeafNodeIndex {
387 type Target = NodeIndex;
388
389 fn deref(&self) -> &Self::Target {
390 &self.0
391 }
392}
393
394impl From<NodeIndex> for LeafNodeIndex {
395 fn from(value: NodeIndex) -> Self {
396 Self::new(value)
397 }
398}
399
400impl From<LeafNodeIndex> for NodeIndex {
401 fn from(value: LeafNodeIndex) -> Self {
402 value.0
403 }
404}
405
406// HELPER FUNCTIONS
407// ================================================================================================
408
409/// Returns the value representing the 64 most significant bits of the specified key.
410fn get_key_prefix(key: &RpoDigest) -> u64 {
411 Word::from(key)[3].as_int()
412}
413
414/// Returns the index value shifted to be in the most significant bit positions of the returned
415/// u64 value.
416fn index_to_prefix(index: &NodeIndex) -> u64 {
417 index.value() << (TieredSmt::MAX_DEPTH - index.depth())
418}
419
420/// Returns tiered common prefix length between the most significant elements of the provided keys.
421///
422/// Specifically:
423/// - returns 64 if the most significant elements are equal.
424/// - returns 48 if the common prefix is between 48 and 63 bits.
425/// - returns 32 if the common prefix is between 32 and 47 bits.
426/// - returns 16 if the common prefix is between 16 and 31 bits.
427/// - returns 0 if the common prefix is fewer than 16 bits.
428fn get_common_prefix_tier_depth(key1: &RpoDigest, key2: &RpoDigest) -> u8 {
429 let e1 = get_key_prefix(key1);
430 let e2 = get_key_prefix(key2);
431 let ex = (e1 ^ e2).leading_zeros() as u8;
432 (ex / 16) * 16
433}
434
435/// Computes node value for leaves at tiers 16, 32, or 48.
436///
437/// Node value is computed as: hash(key || value, domain = depth).
438pub fn hash_upper_leaf(key: RpoDigest, value: Word, depth: u8) -> RpoDigest {
439 const NUM_UPPER_TIERS: usize = TieredSmt::TIER_DEPTHS.len() - 1;
440 debug_assert!(TieredSmt::TIER_DEPTHS[..NUM_UPPER_TIERS].contains(&depth));
441 Rpo256::merge_in_domain(&[key, value.into()], depth.into())
442}
443
444/// Computes node value for leaves at the bottom tier (depth 64).
445///
446/// Node value is computed as: hash([key_0, value_0, ..., key_n, value_n], domain=64).
447///
448/// TODO: when hashing in domain is implemented for `hash_elements()`, combine this function with
449/// `hash_upper_leaf()` function.
450pub fn hash_bottom_leaf(values: &[(RpoDigest, Word)]) -> RpoDigest {
451 let mut elements = Vec::with_capacity(values.len() * 8);
452 for (key, val) in values.iter() {
453 elements.extend_from_slice(key.as_elements());
454 elements.extend_from_slice(val.as_slice());
455 }
456 // TODO: hash in domain
457 Rpo256::hash_elements(&elements)
458}