miden_processor/host/advice/
inputs.rs

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