miden_processor/host/advice/
inputs.rs

1use alloc::vec::Vec;
2
3use miden_core::{
4    AdviceMap, Felt, Word,
5    crypto::merkle::{InnerNodeInfo, MerkleStore},
6    errors::InputError,
7    utils::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
8};
9
10// ADVICE INPUTS
11// ================================================================================================
12
13/// Inputs container to initialize advice provider for the execution of Miden VM programs.
14///
15/// The program may request nondeterministic advice inputs from the prover. These inputs are secret
16/// inputs. This means that the prover does not need to share them with the verifier.
17///
18/// There are three types of advice inputs:
19///
20/// 1. Single advice stack which can contain any number of elements.
21/// 2. Key-mapped element lists which can be pushed onto the advice stack.
22/// 3. Merkle store, which is used to provide nondeterministic inputs for instructions that operates
23///    with Merkle trees.
24#[cfg(not(feature = "testing"))]
25#[derive(Clone, Debug, Default, PartialEq, Eq)]
26pub struct AdviceInputs {
27    stack: Vec<Felt>,
28    map: AdviceMap,
29    store: MerkleStore,
30}
31
32impl AdviceInputs {
33    // CONSTRUCTORS
34    // --------------------------------------------------------------------------------------------
35
36    /// Attempts to extend the stack values with the given sequence of integers, returning an error
37    /// if any of the numbers fails while converting to an element `[Felt]`.
38    pub fn with_stack_values<I>(mut self, iter: I) -> Result<Self, InputError>
39    where
40        I: IntoIterator<Item = u64>,
41    {
42        let stack = iter
43            .into_iter()
44            .map(|v| Felt::try_from(v).map_err(|e| InputError::NotFieldElement(v, e)))
45            .collect::<Result<Vec<_>, _>>()?;
46
47        self.stack.extend(stack.iter());
48        Ok(self)
49    }
50
51    /// Extends the stack with the given elements.
52    pub fn with_stack<I>(mut self, iter: I) -> Self
53    where
54        I: IntoIterator<Item = Felt>,
55    {
56        self.stack.extend(iter);
57        self
58    }
59
60    /// Extends the map of values with the given argument, replacing previously inserted items.
61    pub fn with_map<I>(mut self, iter: I) -> Self
62    where
63        I: IntoIterator<Item = (Word, Vec<Felt>)>,
64    {
65        self.map.extend(iter);
66        self
67    }
68
69    /// Replaces the [MerkleStore] with the provided argument.
70    pub fn with_merkle_store(mut self, store: MerkleStore) -> Self {
71        self.store = store;
72        self
73    }
74
75    // PUBLIC MUTATORS
76    // --------------------------------------------------------------------------------------------
77
78    /// Extends the stack with the given elements.
79    pub fn extend_stack<I>(&mut self, iter: I)
80    where
81        I: IntoIterator<Item = Felt>,
82    {
83        self.stack.extend(iter);
84    }
85
86    /// Extends the map of values with the given argument, replacing previously inserted items.
87    pub fn extend_map<I>(&mut self, iter: I)
88    where
89        I: IntoIterator<Item = (Word, Vec<Felt>)>,
90    {
91        self.map.extend(iter);
92    }
93
94    /// Extends the [MerkleStore] with the given nodes.
95    pub fn extend_merkle_store<I>(&mut self, iter: I)
96    where
97        I: Iterator<Item = InnerNodeInfo>,
98    {
99        self.store.extend(iter);
100    }
101
102    /// Extends the contents of this instance with the contents of the other instance.
103    pub fn extend(&mut self, other: Self) {
104        self.stack.extend(other.stack);
105        self.map.extend(other.map);
106        self.store.extend(other.store.inner_nodes());
107    }
108
109    // PUBLIC ACCESSORS
110    // --------------------------------------------------------------------------------------------
111
112    /// Returns a reference to the advice stack.
113    pub fn stack(&self) -> &[Felt] {
114        &self.stack
115    }
116
117    /// Fetch a values set mapped by the given key.
118    pub fn mapped_values(&self, key: &Word) -> Option<&[Felt]> {
119        self.map.get(key)
120    }
121
122    /// Returns the underlying [MerkleStore].
123    pub const fn merkle_store(&self) -> &MerkleStore {
124        &self.store
125    }
126
127    // DESTRUCTORS
128    // --------------------------------------------------------------------------------------------
129
130    /// Decomposes these `[Self]` into their raw components.
131    #[allow(clippy::type_complexity)]
132    pub(crate) fn into_parts(self) -> (Vec<Felt>, AdviceMap, MerkleStore) {
133        let Self { stack, map, store } = self;
134        (stack, map, store)
135    }
136}
137
138impl Serializable for AdviceInputs {
139    fn write_into<W: ByteWriter>(&self, target: &mut W) {
140        let Self { stack, map, store } = self;
141        stack.write_into(target);
142        map.write_into(target);
143        store.write_into(target);
144    }
145}
146
147impl Deserializable for AdviceInputs {
148    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
149        let stack = Vec::<Felt>::read_from(source)?;
150        let map = AdviceMap::read_from(source)?;
151        let store = MerkleStore::read_from(source)?;
152        Ok(Self { stack, map, store })
153    }
154}
155
156// TESTING
157// ================================================================================================
158
159#[cfg(feature = "testing")]
160#[derive(Clone, Debug, Default, PartialEq, Eq)]
161pub struct AdviceInputs {
162    pub stack: Vec<Felt>,
163    pub map: AdviceMap,
164    pub store: MerkleStore,
165}
166
167// TESTS
168// ================================================================================================
169
170#[cfg(test)]
171mod tests {
172    use winter_utils::{Deserializable, Serializable};
173
174    use crate::AdviceInputs;
175
176    #[test]
177    fn test_advice_inputs_eq() {
178        let advice1 = AdviceInputs::default();
179        let advice2 = AdviceInputs::default();
180
181        assert_eq!(advice1, advice2);
182
183        let advice1 = AdviceInputs::default().with_stack_values([1, 2, 3].iter().copied()).unwrap();
184        let advice2 = AdviceInputs::default().with_stack_values([1, 2, 3].iter().copied()).unwrap();
185
186        assert_eq!(advice1, advice2);
187    }
188
189    #[test]
190    fn test_advice_inputs_serialization() {
191        let advice1 = AdviceInputs::default().with_stack_values([1, 2, 3].iter().copied()).unwrap();
192        let bytes = advice1.to_bytes();
193        let advice2 = AdviceInputs::read_from_bytes(&bytes).unwrap();
194
195        assert_eq!(advice1, advice2);
196    }
197}