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