miden_crypto/merkle/smt/full/
leaf.rs

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