Skip to main content

miden_crypto/merkle/smt/full/
leaf.rs

1use alloc::{string::ToString, vec::Vec};
2use core::cmp::Ordering;
3
4use super::EMPTY_WORD;
5use crate::{
6    Felt, Word,
7    hash::poseidon2::Poseidon2,
8    merkle::smt::{LeafIndex, MAX_LEAF_ENTRIES, SMT_DEPTH, SmtLeafError},
9    utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
10};
11
12/// The number of field elements in a key-value pair (two Words, 4 Felts each).
13const DOUBLE_WORD_LEN: usize = 8;
14
15/// Represents a leaf node in the Sparse Merkle Tree.
16///
17/// A leaf can be empty, hold a single key-value pair, or multiple key-value pairs.
18#[derive(Clone, Debug, PartialEq, Eq)]
19#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
20pub enum SmtLeaf {
21    /// An empty leaf at the specified index.
22    Empty(LeafIndex<SMT_DEPTH>),
23    /// A leaf containing a single key-value pair.
24    Single((Word, Word)),
25    /// A leaf containing multiple key-value pairs.
26    Multiple(Vec<(Word, Word)>),
27}
28
29impl SmtLeaf {
30    // CONSTRUCTORS
31    // ---------------------------------------------------------------------------------------------
32
33    /// Returns a new leaf with the specified entries
34    ///
35    /// # Errors
36    ///   - Returns an error if 2 keys in `entries` map to a different leaf index
37    ///   - Returns an error if 1 or more keys in `entries` map to a leaf index different from
38    ///     `leaf_index`
39    pub fn new(
40        entries: Vec<(Word, Word)>,
41        leaf_index: LeafIndex<SMT_DEPTH>,
42    ) -> Result<Self, SmtLeafError> {
43        match entries.len() {
44            0 => Ok(Self::new_empty(leaf_index)),
45            1 => {
46                let (key, value) = entries[0];
47
48                let computed_index = LeafIndex::<SMT_DEPTH>::from(key);
49                if computed_index != leaf_index {
50                    return Err(SmtLeafError::InconsistentSingleLeafIndices {
51                        key,
52                        expected_leaf_index: leaf_index,
53                        actual_leaf_index: computed_index,
54                    });
55                }
56
57                Ok(Self::new_single(key, value))
58            },
59            _ => {
60                let leaf = Self::new_multiple(entries)?;
61
62                // `new_multiple()` checked that all keys map to the same leaf index. We still need
63                // to ensure that leaf index is `leaf_index`.
64                if leaf.index() != leaf_index {
65                    Err(SmtLeafError::InconsistentMultipleLeafIndices {
66                        leaf_index_from_keys: leaf.index(),
67                        leaf_index_supplied: leaf_index,
68                    })
69                } else {
70                    Ok(leaf)
71                }
72            },
73        }
74    }
75
76    /// Returns a new empty leaf with the specified leaf index
77    pub fn new_empty(leaf_index: LeafIndex<SMT_DEPTH>) -> Self {
78        Self::Empty(leaf_index)
79    }
80
81    /// Returns a new single leaf with the specified entry. The leaf index is derived from the
82    /// entry's key.
83    pub fn new_single(key: Word, value: Word) -> Self {
84        Self::Single((key, value))
85    }
86
87    /// Returns a new multiple leaf with the specified entries. The leaf index is derived from the
88    /// entries' keys.
89    ///
90    /// # Errors
91    ///   - Returns an error if 2 keys in `entries` map to a different leaf index
92    ///   - Returns an error if the number of entries exceeds [`MAX_LEAF_ENTRIES`]
93    pub fn new_multiple(entries: Vec<(Word, Word)>) -> Result<Self, SmtLeafError> {
94        if entries.len() < 2 {
95            return Err(SmtLeafError::MultipleLeafRequiresTwoEntries(entries.len()));
96        }
97
98        if entries.len() > MAX_LEAF_ENTRIES {
99            return Err(SmtLeafError::TooManyLeafEntries { actual: entries.len() });
100        }
101
102        // Check that all keys map to the same leaf index
103        {
104            let mut keys = entries.iter().map(|(key, _)| key);
105
106            let first_key = *keys.next().expect("ensured at least 2 entries");
107            let first_leaf_index: LeafIndex<SMT_DEPTH> = first_key.into();
108
109            for &next_key in keys {
110                let next_leaf_index: LeafIndex<SMT_DEPTH> = next_key.into();
111
112                if next_leaf_index != first_leaf_index {
113                    return Err(SmtLeafError::InconsistentMultipleLeafKeys {
114                        key_1: first_key,
115                        key_2: next_key,
116                    });
117                }
118            }
119        }
120
121        Ok(Self::Multiple(entries))
122    }
123
124    // PUBLIC ACCESSORS
125    // ---------------------------------------------------------------------------------------------
126
127    /// Returns true if the leaf is empty
128    pub fn is_empty(&self) -> bool {
129        matches!(self, Self::Empty(_))
130    }
131
132    /// Returns the leaf's index in the [`super::Smt`]
133    pub fn index(&self) -> LeafIndex<SMT_DEPTH> {
134        match self {
135            SmtLeaf::Empty(leaf_index) => *leaf_index,
136            SmtLeaf::Single((key, _)) => (*key).into(),
137            SmtLeaf::Multiple(entries) => {
138                // Note: All keys are guaranteed to have the same leaf index
139                let (first_key, _) = entries[0];
140                first_key.into()
141            },
142        }
143    }
144
145    /// Returns the number of entries stored in the leaf
146    pub fn num_entries(&self) -> usize {
147        match self {
148            SmtLeaf::Empty(_) => 0,
149            SmtLeaf::Single(_) => 1,
150            SmtLeaf::Multiple(entries) => entries.len(),
151        }
152    }
153
154    /// Computes the hash of the leaf
155    pub fn hash(&self) -> Word {
156        match self {
157            SmtLeaf::Empty(_) => EMPTY_WORD,
158            SmtLeaf::Single((key, value)) => Poseidon2::merge(&[*key, *value]),
159            SmtLeaf::Multiple(kvs) => {
160                let elements: Vec<Felt> = kvs.iter().copied().flat_map(kv_to_elements).collect();
161                Poseidon2::hash_elements(&elements)
162            },
163        }
164    }
165
166    // ITERATORS
167    // ---------------------------------------------------------------------------------------------
168
169    /// Returns a slice with key-value pairs in the leaf.
170    pub fn entries(&self) -> &[(Word, Word)] {
171        match self {
172            SmtLeaf::Empty(_) => &[],
173            SmtLeaf::Single(kv_pair) => core::slice::from_ref(kv_pair),
174            SmtLeaf::Multiple(kv_pairs) => kv_pairs,
175        }
176    }
177
178    // CONVERSIONS
179    // ---------------------------------------------------------------------------------------------
180
181    /// Returns an iterator over the field elements representing this leaf.
182    pub fn to_elements(&self) -> impl Iterator<Item = Felt> + '_ {
183        self.entries().iter().copied().flat_map(kv_to_elements)
184    }
185
186    /// Converts a leaf to a list of field elements.
187    pub fn into_elements(self) -> Vec<Felt> {
188        self.into_entries().into_iter().flat_map(kv_to_elements).collect()
189    }
190
191    /// Converts a leaf the key-value pairs in the leaf
192    pub fn into_entries(self) -> Vec<(Word, Word)> {
193        match self {
194            SmtLeaf::Empty(_) => Vec::new(),
195            SmtLeaf::Single(kv_pair) => vec![kv_pair],
196            SmtLeaf::Multiple(kv_pairs) => kv_pairs,
197        }
198    }
199
200    /// Converts a list of elements into a leaf
201    pub fn try_from_elements(
202        elements: &[Felt],
203        leaf_index: LeafIndex<SMT_DEPTH>,
204    ) -> Result<SmtLeaf, SmtLeafError> {
205        if elements.is_empty() {
206            return Ok(SmtLeaf::new_empty(leaf_index));
207        }
208
209        // Elements should be organized into a contiguous array of K/V Words (4 Felts each).
210        if !elements.len().is_multiple_of(DOUBLE_WORD_LEN) {
211            return Err(SmtLeafError::DecodingError(
212                "elements length is not a multiple of 8".into(),
213            ));
214        }
215
216        let num_entries = elements.len() / DOUBLE_WORD_LEN;
217
218        if num_entries == 1 {
219            // Single entry.
220            let key = Word::new([elements[0], elements[1], elements[2], elements[3]]);
221            let value = Word::new([elements[4], elements[5], elements[6], elements[7]]);
222            Ok(SmtLeaf::new_single(key, value))
223        } else {
224            // Multiple entries.
225            let mut entries = Vec::with_capacity(num_entries);
226            // Read k/v pairs from each entry.
227            for i in 0..num_entries {
228                let base_idx = i * DOUBLE_WORD_LEN;
229                let key = Word::new([
230                    elements[base_idx],
231                    elements[base_idx + 1],
232                    elements[base_idx + 2],
233                    elements[base_idx + 3],
234                ]);
235                let value = Word::new([
236                    elements[base_idx + 4],
237                    elements[base_idx + 5],
238                    elements[base_idx + 6],
239                    elements[base_idx + 7],
240                ]);
241                entries.push((key, value));
242            }
243            let leaf = SmtLeaf::new_multiple(entries)?;
244            Ok(leaf)
245        }
246    }
247
248    // HELPERS
249    // ---------------------------------------------------------------------------------------------
250
251    /// Returns the value associated with `key` in the leaf, or `None` if `key` maps to another
252    /// leaf.
253    pub(in crate::merkle::smt) fn get_value(&self, key: &Word) -> Option<Word> {
254        // Ensure that `key` maps to this leaf
255        if self.index() != (*key).into() {
256            return None;
257        }
258
259        match self {
260            SmtLeaf::Empty(_) => Some(EMPTY_WORD),
261            SmtLeaf::Single((key_in_leaf, value_in_leaf)) => {
262                if key == key_in_leaf {
263                    Some(*value_in_leaf)
264                } else {
265                    Some(EMPTY_WORD)
266                }
267            },
268            SmtLeaf::Multiple(kv_pairs) => {
269                for (key_in_leaf, value_in_leaf) in kv_pairs {
270                    if key == key_in_leaf {
271                        return Some(*value_in_leaf);
272                    }
273                }
274
275                Some(EMPTY_WORD)
276            },
277        }
278    }
279
280    /// Inserts key-value pair into the leaf; returns the previous value associated with `key`, if
281    /// any.
282    ///
283    /// The caller needs to ensure that `key` has the same leaf index as all other keys in the leaf
284    ///
285    /// # Errors
286    /// Returns an error if inserting the key-value pair would exceed [`MAX_LEAF_ENTRIES`] (1024
287    /// entries) in the leaf.
288    pub(in crate::merkle::smt) fn insert(
289        &mut self,
290        key: Word,
291        value: Word,
292    ) -> Result<Option<Word>, SmtLeafError> {
293        match self {
294            SmtLeaf::Empty(_) => {
295                *self = SmtLeaf::new_single(key, value);
296                Ok(None)
297            },
298            SmtLeaf::Single(kv_pair) => {
299                if kv_pair.0 == key {
300                    // the key is already in this leaf. Update the value and return the previous
301                    // value
302                    let old_value = kv_pair.1;
303                    kv_pair.1 = value;
304                    Ok(Some(old_value))
305                } else {
306                    // Another entry is present in this leaf. Transform the entry into a list
307                    // entry, and make sure the key-value pairs are sorted by key
308                    // This stays within MAX_LEAF_ENTRIES limit. We're only adding one entry to a
309                    // single leaf
310                    let mut pairs = vec![*kv_pair, (key, value)];
311                    pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2));
312                    *self = SmtLeaf::Multiple(pairs);
313                    Ok(None)
314                }
315            },
316            SmtLeaf::Multiple(kv_pairs) => {
317                match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) {
318                    Ok(pos) => {
319                        let old_value = kv_pairs[pos].1;
320                        kv_pairs[pos].1 = value;
321                        Ok(Some(old_value))
322                    },
323                    Err(pos) => {
324                        if kv_pairs.len() >= MAX_LEAF_ENTRIES {
325                            return Err(SmtLeafError::TooManyLeafEntries {
326                                actual: kv_pairs.len() + 1,
327                            });
328                        }
329                        kv_pairs.insert(pos, (key, value));
330                        Ok(None)
331                    },
332                }
333            },
334        }
335    }
336
337    /// Removes key-value pair from the leaf stored at key; returns the previous value associated
338    /// with `key`, if any. Also returns an `is_empty` flag, indicating whether the leaf became
339    /// empty, and must be removed from the data structure it is contained in.
340    pub(in crate::merkle::smt) fn remove(&mut self, key: Word) -> (Option<Word>, bool) {
341        match self {
342            SmtLeaf::Empty(_) => (None, false),
343            SmtLeaf::Single((key_at_leaf, value_at_leaf)) => {
344                if *key_at_leaf == key {
345                    // our key was indeed stored in the leaf, so we return the value that was stored
346                    // in it, and indicate that the leaf should be removed
347                    let old_value = *value_at_leaf;
348
349                    // Note: this is not strictly needed, since the caller is expected to drop this
350                    // `SmtLeaf` object.
351                    *self = SmtLeaf::new_empty(key.into());
352
353                    (Some(old_value), true)
354                } else {
355                    // another key is stored at leaf; nothing to update
356                    (None, false)
357                }
358            },
359            SmtLeaf::Multiple(kv_pairs) => {
360                match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) {
361                    Ok(pos) => {
362                        let old_value = kv_pairs[pos].1;
363
364                        let _ = kv_pairs.remove(pos);
365                        debug_assert!(!kv_pairs.is_empty());
366
367                        if kv_pairs.len() == 1 {
368                            // convert the leaf into `Single`
369                            *self = SmtLeaf::Single(kv_pairs[0]);
370                        }
371
372                        (Some(old_value), false)
373                    },
374                    Err(_) => {
375                        // other keys are stored at leaf; nothing to update
376                        (None, false)
377                    },
378                }
379            },
380        }
381    }
382}
383
384impl Serializable for SmtLeaf {
385    fn write_into<W: ByteWriter>(&self, target: &mut W) {
386        // Write: num entries
387        self.num_entries().write_into(target);
388
389        // Write: leaf index
390        let leaf_index: u64 = self.index().value();
391        leaf_index.write_into(target);
392
393        // Write: entries
394        for (key, value) in self.entries() {
395            key.write_into(target);
396            value.write_into(target);
397        }
398    }
399}
400
401impl Deserializable for SmtLeaf {
402    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
403        // Read: num entries
404        let num_entries = source.read_usize()?;
405
406        // Read: leaf index
407        let leaf_index: LeafIndex<SMT_DEPTH> = {
408            let value = source.read_u64()?;
409            LeafIndex::new_max_depth(value)
410        };
411
412        // Read: entries
413        let mut entries: Vec<(Word, Word)> = Vec::new();
414        for _ in 0..num_entries {
415            let key: Word = source.read()?;
416            let value: Word = source.read()?;
417
418            entries.push((key, value));
419        }
420
421        Self::new(entries, leaf_index)
422            .map_err(|err| DeserializationError::InvalidValue(err.to_string()))
423    }
424}
425
426// HELPER FUNCTIONS
427// ================================================================================================
428
429/// Converts a key-value tuple to an iterator of `Felt`s
430pub(crate) fn kv_to_elements((key, value): (Word, Word)) -> impl Iterator<Item = Felt> {
431    let key_elements = key.into_iter();
432    let value_elements = value.into_iter();
433
434    key_elements.chain(value_elements)
435}
436
437/// Compares two keys, compared element-by-element using their integer representations starting with
438/// the most significant element.
439pub(crate) fn cmp_keys(key_1: Word, key_2: Word) -> Ordering {
440    for (v1, v2) in key_1.iter().zip(key_2.iter()).rev() {
441        let v1 = (*v1).as_canonical_u64();
442        let v2 = (*v2).as_canonical_u64();
443        if v1 != v2 {
444            return v1.cmp(&v2);
445        }
446    }
447
448    Ordering::Equal
449}