miden_crypto/merkle/smt/full/
leaf.rs

1use alloc::{string::ToString, vec::Vec};
2use core::cmp::Ordering;
3
4use super::{EMPTY_WORD, Felt, LeafIndex, 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    pub fn new_multiple(entries: Vec<(Word, Word)>) -> Result<Self, SmtLeafError> {
85        if entries.len() < 2 {
86            return Err(SmtLeafError::MultipleLeafRequiresTwoEntries(entries.len()));
87        }
88
89        // Check that all keys map to the same leaf index
90        {
91            let mut keys = entries.iter().map(|(key, _)| key);
92
93            let first_key = *keys.next().expect("ensured at least 2 entries");
94            let first_leaf_index: LeafIndex<SMT_DEPTH> = first_key.into();
95
96            for &next_key in keys {
97                let next_leaf_index: LeafIndex<SMT_DEPTH> = next_key.into();
98
99                if next_leaf_index != first_leaf_index {
100                    return Err(SmtLeafError::InconsistentMultipleLeafKeys {
101                        key_1: first_key,
102                        key_2: next_key,
103                    });
104                }
105            }
106        }
107
108        Ok(Self::Multiple(entries))
109    }
110
111    // PUBLIC ACCESSORS
112    // ---------------------------------------------------------------------------------------------
113
114    /// Returns true if the leaf is empty
115    pub fn is_empty(&self) -> bool {
116        matches!(self, Self::Empty(_))
117    }
118
119    /// Returns the leaf's index in the [`super::Smt`]
120    pub fn index(&self) -> LeafIndex<SMT_DEPTH> {
121        match self {
122            SmtLeaf::Empty(leaf_index) => *leaf_index,
123            SmtLeaf::Single((key, _)) => (*key).into(),
124            SmtLeaf::Multiple(entries) => {
125                // Note: All keys are guaranteed to have the same leaf index
126                let (first_key, _) = entries[0];
127                first_key.into()
128            },
129        }
130    }
131
132    /// Returns the number of entries stored in the leaf
133    pub fn num_entries(&self) -> u64 {
134        match self {
135            SmtLeaf::Empty(_) => 0,
136            SmtLeaf::Single(_) => 1,
137            SmtLeaf::Multiple(entries) => {
138                entries.len().try_into().expect("shouldn't have more than 2^64 entries")
139            },
140        }
141    }
142
143    /// Computes the hash of the leaf
144    pub fn hash(&self) -> Word {
145        match self {
146            SmtLeaf::Empty(_) => EMPTY_WORD,
147            SmtLeaf::Single((key, value)) => Rpo256::merge(&[*key, *value]),
148            SmtLeaf::Multiple(kvs) => {
149                let elements: Vec<Felt> = kvs.iter().copied().flat_map(kv_to_elements).collect();
150                Rpo256::hash_elements(&elements)
151            },
152        }
153    }
154
155    // ITERATORS
156    // ---------------------------------------------------------------------------------------------
157
158    /// Returns the key-value pairs in the leaf
159    pub fn entries(&self) -> Vec<&(Word, Word)> {
160        match self {
161            SmtLeaf::Empty(_) => Vec::new(),
162            SmtLeaf::Single(kv_pair) => vec![kv_pair],
163            SmtLeaf::Multiple(kv_pairs) => kv_pairs.iter().collect(),
164        }
165    }
166
167    // CONVERSIONS
168    // ---------------------------------------------------------------------------------------------
169
170    /// Converts a leaf to a list of field elements
171    pub fn to_elements(&self) -> Vec<Felt> {
172        self.clone().into_elements()
173    }
174
175    /// Converts a leaf to a list of field elements
176    pub fn into_elements(self) -> Vec<Felt> {
177        self.into_entries().into_iter().flat_map(kv_to_elements).collect()
178    }
179
180    /// Converts a leaf the key-value pairs in the leaf
181    pub fn into_entries(self) -> Vec<(Word, Word)> {
182        match self {
183            SmtLeaf::Empty(_) => Vec::new(),
184            SmtLeaf::Single(kv_pair) => vec![kv_pair],
185            SmtLeaf::Multiple(kv_pairs) => kv_pairs,
186        }
187    }
188
189    // HELPERS
190    // ---------------------------------------------------------------------------------------------
191
192    /// Returns the value associated with `key` in the leaf, or `None` if `key` maps to another
193    /// leaf.
194    pub(super) fn get_value(&self, key: &Word) -> Option<Word> {
195        // Ensure that `key` maps to this leaf
196        if self.index() != (*key).into() {
197            return None;
198        }
199
200        match self {
201            SmtLeaf::Empty(_) => Some(EMPTY_WORD),
202            SmtLeaf::Single((key_in_leaf, value_in_leaf)) => {
203                if key == key_in_leaf {
204                    Some(*value_in_leaf)
205                } else {
206                    Some(EMPTY_WORD)
207                }
208            },
209            SmtLeaf::Multiple(kv_pairs) => {
210                for (key_in_leaf, value_in_leaf) in kv_pairs {
211                    if key == key_in_leaf {
212                        return Some(*value_in_leaf);
213                    }
214                }
215
216                Some(EMPTY_WORD)
217            },
218        }
219    }
220
221    /// Inserts key-value pair into the leaf; returns the previous value associated with `key`, if
222    /// any.
223    ///
224    /// The caller needs to ensure that `key` has the same leaf index as all other keys in the leaf
225    pub(super) fn insert(&mut self, key: Word, value: Word) -> Option<Word> {
226        match self {
227            SmtLeaf::Empty(_) => {
228                *self = SmtLeaf::new_single(key, value);
229                None
230            },
231            SmtLeaf::Single(kv_pair) => {
232                if kv_pair.0 == key {
233                    // the key is already in this leaf. Update the value and return the previous
234                    // value
235                    let old_value = kv_pair.1;
236                    kv_pair.1 = value;
237                    Some(old_value)
238                } else {
239                    // Another entry is present in this leaf. Transform the entry into a list
240                    // entry, and make sure the key-value pairs are sorted by key
241                    let mut pairs = vec![*kv_pair, (key, value)];
242                    pairs.sort_by(|(key_1, _), (key_2, _)| cmp_keys(*key_1, *key_2));
243
244                    *self = SmtLeaf::Multiple(pairs);
245
246                    None
247                }
248            },
249            SmtLeaf::Multiple(kv_pairs) => {
250                match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) {
251                    Ok(pos) => {
252                        let old_value = kv_pairs[pos].1;
253                        kv_pairs[pos].1 = value;
254
255                        Some(old_value)
256                    },
257                    Err(pos) => {
258                        kv_pairs.insert(pos, (key, value));
259
260                        None
261                    },
262                }
263            },
264        }
265    }
266
267    /// Removes key-value pair from the leaf stored at key; returns the previous value associated
268    /// with `key`, if any. Also returns an `is_empty` flag, indicating whether the leaf became
269    /// empty, and must be removed from the data structure it is contained in.
270    pub(super) fn remove(&mut self, key: Word) -> (Option<Word>, bool) {
271        match self {
272            SmtLeaf::Empty(_) => (None, false),
273            SmtLeaf::Single((key_at_leaf, value_at_leaf)) => {
274                if *key_at_leaf == key {
275                    // our key was indeed stored in the leaf, so we return the value that was stored
276                    // in it, and indicate that the leaf should be removed
277                    let old_value = *value_at_leaf;
278
279                    // Note: this is not strictly needed, since the caller is expected to drop this
280                    // `SmtLeaf` object.
281                    *self = SmtLeaf::new_empty(key.into());
282
283                    (Some(old_value), true)
284                } else {
285                    // another key is stored at leaf; nothing to update
286                    (None, false)
287                }
288            },
289            SmtLeaf::Multiple(kv_pairs) => {
290                match kv_pairs.binary_search_by(|kv_pair| cmp_keys(kv_pair.0, key)) {
291                    Ok(pos) => {
292                        let old_value = kv_pairs[pos].1;
293
294                        kv_pairs.remove(pos);
295                        debug_assert!(!kv_pairs.is_empty());
296
297                        if kv_pairs.len() == 1 {
298                            // convert the leaf into `Single`
299                            *self = SmtLeaf::Single(kv_pairs[0]);
300                        }
301
302                        (Some(old_value), false)
303                    },
304                    Err(_) => {
305                        // other keys are stored at leaf; nothing to update
306                        (None, false)
307                    },
308                }
309            },
310        }
311    }
312}
313
314impl Serializable for SmtLeaf {
315    fn write_into<W: ByteWriter>(&self, target: &mut W) {
316        // Write: num entries
317        self.num_entries().write_into(target);
318
319        // Write: leaf index
320        let leaf_index: u64 = self.index().value();
321        leaf_index.write_into(target);
322
323        // Write: entries
324        for (key, value) in self.entries() {
325            key.write_into(target);
326            value.write_into(target);
327        }
328    }
329}
330
331impl Deserializable for SmtLeaf {
332    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
333        // Read: num entries
334        let num_entries = source.read_u64()?;
335
336        // Read: leaf index
337        let leaf_index: LeafIndex<SMT_DEPTH> = {
338            let value = source.read_u64()?;
339            LeafIndex::new_max_depth(value)
340        };
341
342        // Read: entries
343        let mut entries: Vec<(Word, Word)> = Vec::new();
344        for _ in 0..num_entries {
345            let key: Word = source.read()?;
346            let value: Word = source.read()?;
347
348            entries.push((key, value));
349        }
350
351        Self::new(entries, leaf_index)
352            .map_err(|err| DeserializationError::InvalidValue(err.to_string()))
353    }
354}
355
356// HELPER FUNCTIONS
357// ================================================================================================
358
359/// Converts a key-value tuple to an iterator of `Felt`s
360pub(crate) fn kv_to_elements((key, value): (Word, Word)) -> impl Iterator<Item = Felt> {
361    let key_elements = key.into_iter();
362    let value_elements = value.into_iter();
363
364    key_elements.chain(value_elements)
365}
366
367/// Compares two keys, compared element-by-element using their integer representations starting with
368/// the most significant element.
369pub(crate) fn cmp_keys(key_1: Word, key_2: Word) -> Ordering {
370    for (v1, v2) in key_1.iter().zip(key_2.iter()).rev() {
371        let v1 = v1.as_int();
372        let v2 = v2.as_int();
373        if v1 != v2 {
374            return v1.cmp(&v2);
375        }
376    }
377
378    Ordering::Equal
379}