Skip to main content

miden_core/advice/
map.rs

1use alloc::{
2    collections::{
3        BTreeMap,
4        btree_map::{Entry, IntoIter},
5    },
6    sync::Arc,
7    vec::Vec,
8};
9
10use crate::{
11    Felt, WORD_SIZE, Word,
12    chiplets::hasher,
13    serde::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
14};
15
16// ADVICE MAP
17// ================================================================================================
18
19/// Defines a set of non-deterministic (advice) inputs which the VM can access by their keys.
20///
21/// Each key maps to one or more field element. To access the elements, the VM can move the values
22/// associated with a given key onto the advice stack using `adv.push_mapval` instruction. The VM
23/// can also insert new values into the advice map during execution.
24///
25/// This type is a policy-free container. Execution-specific size limits for live advice map state
26/// are enforced by the processor's `AdviceProvider`, which owns the active execution options and
27/// live resource accounting.
28#[derive(Debug, Clone, Default, PartialEq, Eq)]
29#[cfg_attr(
30    all(feature = "arbitrary", test),
31    miden_test_serialization_macros::serialization_test
32)]
33pub struct AdviceMap(BTreeMap<Word, Arc<[Felt]>>);
34
35/// Pair representing a key-value entry in an [`AdviceMap`]
36type MapEntry = (Word, Arc<[Felt]>);
37
38impl AdviceMap {
39    /// Returns the values associated with given key.
40    pub fn get(&self, key: &Word) -> Option<&Arc<[Felt]>> {
41        self.0.get(key)
42    }
43
44    /// Returns true if the key has a corresponding value in the map.
45    pub fn contains_key(&self, key: &Word) -> bool {
46        self.0.contains_key(key)
47    }
48
49    /// Inserts a value, returning the previous value if the key was already set.
50    pub fn insert(&mut self, key: Word, value: impl Into<Arc<[Felt]>>) -> Option<Arc<[Felt]>> {
51        self.0.insert(key, value.into())
52    }
53
54    /// Removes the value associated with the key and returns the removed element.
55    pub fn remove(&mut self, key: &Word) -> Option<Arc<[Felt]>> {
56        self.0.remove(key)
57    }
58
59    /// Return an iteration over all entries in the map.
60    pub fn iter(&self) -> impl Iterator<Item = (&Word, &Arc<[Felt]>)> {
61        self.0.iter()
62    }
63
64    /// Returns the number of key value pairs in the advice map.
65    pub fn len(&self) -> usize {
66        self.0.len()
67    }
68
69    /// Returns true if the advice map is empty.
70    pub fn is_empty(&self) -> bool {
71        self.0.is_empty()
72    }
73
74    /// Returns the total number of field elements stored in this advice map's keys and values.
75    ///
76    /// Each key is a word, so every entry contributes [`WORD_SIZE`] key elements plus the number
77    /// of value elements associated with that key. Returns `None` if the count overflows `usize`.
78    pub fn total_element_count(&self) -> Option<usize> {
79        self.0.values().try_fold(0usize, |total, values| {
80            WORD_SIZE
81                .checked_add(values.len())
82                .and_then(|entry_elements| total.checked_add(entry_elements))
83        })
84    }
85
86    /// Returns a commitment to this advice map.
87    ///
88    /// Entries are committed in key order. Each entry is hashed as the key elements followed by the
89    /// value elements. [`hasher::hash_elements`] binds the entry length, and
90    /// [`hasher::hash_words`] folds the ordered entry commitments into the final map commitment.
91    pub fn commitment(&self) -> Word {
92        let entry_commitments = self
93            .iter()
94            .map(|(key, values)| {
95                let mut elements = Vec::with_capacity(WORD_SIZE + values.len());
96                elements.extend_from_slice(key.as_elements());
97                elements.extend_from_slice(values);
98                hasher::hash_elements(&elements)
99            })
100            .collect::<Vec<_>>();
101
102        hasher::hash_words(&entry_commitments)
103    }
104
105    /// Gets the given key's corresponding entry in the map for in-place manipulation.
106    pub fn entry(&mut self, key: Word) -> Entry<'_, Word, Arc<[Felt]>> {
107        self.0.entry(key)
108    }
109
110    /// Merges all entries from the given [`AdviceMap`] into the current advice map.
111    ///
112    /// If an entry from the new map already exists with the same key but different value,
113    /// an error is returned containing the existing entry along with the value that would replace
114    /// it. The current map remains unchanged.
115    pub fn merge(&mut self, other: &Self) -> Result<(), (MapEntry, Arc<[Felt]>)> {
116        if let Some(conflict) = self.find_conflicting_entry(other) {
117            Err(conflict)
118        } else {
119            self.merge_new(other);
120            Ok(())
121        }
122    }
123
124    /// Merges entries from `other`, but only for keys not already present in `self`.
125    fn merge_new(&mut self, other: &Self) {
126        for (key, value) in other.iter() {
127            self.0.entry(*key).or_insert_with(|| value.clone());
128        }
129    }
130
131    /// Finds the first key that exists in both `self` and `other` with different values.
132    ///
133    /// # Returns
134    /// - `Some` containing the conflicting key, its value from `self`, and the value from `other`.
135    /// - `None` if there are no conflicting values.
136    fn find_conflicting_entry(&self, other: &Self) -> Option<(MapEntry, Arc<[Felt]>)> {
137        for (key, new_value) in other.iter() {
138            if let Some(existing_value) = self.get(key)
139                && existing_value != new_value
140            {
141                // Found a conflict.
142                return Some(((*key, existing_value.clone()), new_value.clone()));
143            }
144        }
145        // No conflicts found.
146        None
147    }
148}
149
150impl From<BTreeMap<Word, Arc<[Felt]>>> for AdviceMap {
151    fn from(value: BTreeMap<Word, Arc<[Felt]>>) -> Self {
152        Self(value)
153    }
154}
155
156impl From<BTreeMap<Word, Vec<Felt>>> for AdviceMap {
157    fn from(value: BTreeMap<Word, Vec<Felt>>) -> Self {
158        value.into_iter().collect()
159    }
160}
161
162impl IntoIterator for AdviceMap {
163    type Item = (Word, Arc<[Felt]>);
164    type IntoIter = IntoIter<Word, Arc<[Felt]>>;
165
166    fn into_iter(self) -> Self::IntoIter {
167        self.0.into_iter()
168    }
169}
170
171impl<V> FromIterator<(Word, V)> for AdviceMap
172where
173    V: Into<Arc<[Felt]>>,
174{
175    fn from_iter<I>(iter: I) -> Self
176    where
177        I: IntoIterator<Item = (Word, V)>,
178    {
179        iter.into_iter()
180            .map(|(key, value)| (key, value.into()))
181            .collect::<BTreeMap<Word, Arc<[Felt]>>>()
182            .into()
183    }
184}
185
186impl<V> Extend<(Word, V)> for AdviceMap
187where
188    V: Into<Arc<[Felt]>>,
189{
190    fn extend<I>(&mut self, iter: I)
191    where
192        I: IntoIterator<Item = (Word, V)>,
193    {
194        self.0.extend(iter.into_iter().map(|(key, value)| (key, value.into())))
195    }
196}
197
198impl Serializable for AdviceMap {
199    fn write_into<W: ByteWriter>(&self, target: &mut W) {
200        target.write_usize(self.0.len());
201        for (key, values) in self.0.iter() {
202            target.write((key, values.to_vec()));
203        }
204    }
205
206    /// Returns the exact serialized size in bytes without allocating.
207    ///
208    /// # Panics
209    ///
210    /// Panics if the serialized size exceeds [`usize::MAX`].
211    fn get_size_hint(&self) -> usize {
212        self.0
213            .iter()
214            .try_fold(self.0.len().get_size_hint(), |size, (key, values)| {
215                let values_size = values.len().checked_mul(Felt::min_serialized_size())?;
216                size.checked_add(key.get_size_hint())?
217                    .checked_add(values.len().get_size_hint())?
218                    .checked_add(values_size)
219            })
220            .expect("advice map serialized size exceeds usize::MAX")
221    }
222}
223
224impl Deserializable for AdviceMap {
225    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
226        let mut map = BTreeMap::new();
227        let count = source.read_usize()?;
228        for _ in 0..count {
229            let (key, values): (Word, Vec<Felt>) = source.read()?;
230            if map.insert(key, Arc::from(values)).is_some() {
231                return Err(DeserializationError::InvalidValue(
232                    "duplicate advice map key in serialized payload".into(),
233                ));
234            }
235        }
236        Ok(Self(map))
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use miden_crypto::hash::eidos::Eidos;
243
244    use super::*;
245
246    #[test]
247    fn test_advice_map_serialization() {
248        let mut map1 = AdviceMap::default();
249        map1.insert(Word::default(), vec![Felt::from_u32(1), Felt::from_u32(2)]);
250
251        let bytes = map1.to_bytes();
252
253        let map2 = AdviceMap::read_from_bytes(&bytes).unwrap();
254
255        assert_eq!(map1, map2);
256    }
257
258    #[cfg(feature = "arbitrary")]
259    ::proptest::proptest! {
260        /// The duplicate-key rejection covers the FULL repetition class: a repeated key
261        /// is rejected even when the two values are EQUAL (the map is a set of bindings,
262        /// not a multiset), and for arbitrary keys and values — `write_into` never
263        /// produces a repeated key (the BTreeMap source cannot), but a hand-written
264        /// payload can.
265        #[test]
266        fn prop_rejects_generated_duplicate_key_payloads(
267            (key, first, second) in (
268                proptest::prelude::any::<Word>(),
269                proptest::prelude::any::<Vec<Felt>>(),
270                proptest::prelude::any::<Vec<Felt>>(),
271            ),
272        ) {
273            use crate::serde::ByteWriter;
274
275            for (repeated, label) in [(second, "different value"), (first.clone(), "equal value")]
276            {
277                let mut bytes = Vec::new();
278                bytes.write_usize(2);
279                (key, first.clone()).write_into(&mut bytes);
280                (key, repeated).write_into(&mut bytes);
281
282                let err = AdviceMap::read_from_bytes(&bytes).unwrap_err();
283                let DeserializationError::InvalidValue(message) = err else {
284                    panic!("expected InvalidValue for a duplicate key with {label}, got {err:?}");
285                };
286                assert_eq!(
287                    message, "duplicate advice map key in serialized payload",
288                    "expected the duplicate-key rejection for {label}",
289                );
290            }
291        }
292    }
293
294    #[test]
295    fn advice_map_commitment_matches_eidos_primitive() {
296        let low_key =
297            Word::new([Felt::from_u32(1), Felt::from_u32(2), Felt::from_u32(3), Felt::from_u32(4)]);
298        let high_key =
299            Word::new([Felt::from_u32(9), Felt::from_u32(8), Felt::from_u32(7), Felt::from_u32(6)]);
300        let low_values = [Felt::from_u32(11), Felt::from_u32(12)];
301        let high_values = [Felt::from_u32(21), Felt::from_u32(22), Felt::from_u32(23)];
302
303        // Insert in reverse key order to pin that the BTreeMap's canonical key order is what gets
304        // committed.
305        let map = AdviceMap::from_iter([
306            (high_key, high_values.to_vec()),
307            (low_key, low_values.to_vec()),
308        ]);
309        let low_entry = [low_key.as_elements(), low_values.as_slice()].concat();
310        let high_entry = [high_key.as_elements(), high_values.as_slice()].concat();
311        let expected = Eidos::hash_words(&[
312            Eidos::hash_elements(&low_entry),
313            Eidos::hash_elements(&high_entry),
314        ]);
315
316        assert_eq!(map.commitment(), expected);
317    }
318
319    #[test]
320    #[cfg_attr(
321        target_pointer_width = "32",
322        should_panic(expected = "advice map serialized size exceeds usize::MAX")
323    )]
324    fn size_hint_for_shared_values_exceeding_u32() {
325        // The values occupy 1 MiB, but serializing every reference would exceed 4 GiB.
326        let values: Arc<[Felt]> = vec![Felt::ZERO; 131_072].into();
327        let map: AdviceMap = (0..4096u32)
328            .map(|i| {
329                let key = Word::new([Felt::from_u32(i), Felt::ZERO, Felt::ZERO, Felt::ZERO]);
330                (key, Arc::clone(&values))
331            })
332            .collect();
333
334        let size = map.get_size_hint();
335        let expected = map.len().get_size_hint() as u64
336            + 4096
337                * (Word::SERIALIZED_SIZE as u64 + values.len().get_size_hint() as u64 + 1_048_576);
338        assert!(expected > u64::from(u32::MAX));
339        assert_eq!(size as u64, expected);
340    }
341
342    #[test]
343    fn read_from_rejects_duplicate_keys() {
344        use crate::serde::ByteWriter;
345
346        // Same key twice with different values. `write_into` never produces this, but a
347        // hand-written payload can.
348        let key = Word::default();
349        let mut bytes: Vec<u8> = Vec::new();
350        bytes.write_usize(2);
351        (key, vec![Felt::from_u32(1)]).write_into(&mut bytes);
352        (key, vec![Felt::from_u32(2)]).write_into(&mut bytes);
353
354        let err = AdviceMap::read_from_bytes(&bytes).unwrap_err();
355        assert!(matches!(err, DeserializationError::InvalidValue(_)));
356    }
357}