Skip to main content

miden_core/program/
mod.rs

1use alloc::{sync::Arc, vec::Vec};
2use core::fmt;
3
4#[cfg(feature = "serde")]
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    Felt, WORD_SIZE, Word,
9    advice::AdviceMap,
10    mast::{MastForest, MastNode, MastNodeExt, MastNodeId},
11    serde::{ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable},
12    utils::ToElements,
13};
14
15mod kernel;
16pub use kernel::{Kernel, KernelError};
17
18mod stack;
19pub use stack::{InputError, MIN_STACK_DEPTH, OutputError, StackInputs, StackOutputs};
20
21// PROGRAM
22// ===============================================================================================
23
24/// An executable program for Miden VM.
25///
26/// A program consists of a MAST forest, an entrypoint defining the MAST node at which the program
27/// execution begins, and a definition of the kernel against which the program must be executed
28/// (the kernel can be an empty kernel).
29#[derive(Clone, Debug, PartialEq, Eq)]
30#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
31#[cfg_attr(
32    all(feature = "arbitrary", test),
33    miden_test_serde_macros::serde_test(binary_serde(true))
34)]
35pub struct Program {
36    mast_forest: Arc<MastForest>,
37    /// The "entrypoint" is the node where execution of the program begins.
38    entrypoint: MastNodeId,
39    kernel: Kernel,
40}
41
42/// Constructors
43impl Program {
44    /// Construct a new [`Program`] from the given MAST forest and entrypoint. The kernel is assumed
45    /// to be empty.
46    ///
47    /// # Panics:
48    /// - if `mast_forest` doesn't contain the specified entrypoint.
49    /// - if the specified entrypoint is not a procedure root in the `mast_forest`.
50    pub fn new(mast_forest: Arc<MastForest>, entrypoint: MastNodeId) -> Self {
51        Self::with_kernel(mast_forest, entrypoint, Kernel::default())
52    }
53
54    /// Construct a new [`Program`] from the given MAST forest, entrypoint, and kernel.
55    ///
56    /// # Panics:
57    /// - if `mast_forest` doesn't contain the specified entrypoint.
58    /// - if the specified entrypoint is not a procedure root in the `mast_forest`.
59    pub fn with_kernel(
60        mast_forest: Arc<MastForest>,
61        entrypoint: MastNodeId,
62        kernel: Kernel,
63    ) -> Self {
64        assert!(mast_forest.get_node_by_id(entrypoint).is_some(), "invalid entrypoint");
65        assert!(mast_forest.is_procedure_root(entrypoint), "entrypoint not a procedure");
66
67        Self { mast_forest, entrypoint, kernel }
68    }
69
70    /// Produces a new program with the existing [`MastForest`] and where all key/values in the
71    /// provided advice map are added to the internal advice map.
72    pub fn with_advice_map(self, advice_map: AdviceMap) -> Self {
73        let mut mast_forest = (*self.mast_forest).clone();
74        mast_forest.advice_map_mut().extend(advice_map);
75        Self {
76            mast_forest: Arc::new(mast_forest),
77            ..self
78        }
79    }
80}
81
82// ------------------------------------------------------------------------------------------------
83/// Public accessors
84impl Program {
85    /// Returns the hash of the program's entrypoint.
86    ///
87    /// Equivalently, returns the hash of the root of the entrypoint procedure.
88    pub fn hash(&self) -> Word {
89        self.mast_forest[self.entrypoint].digest()
90    }
91
92    /// Returns the entrypoint associated with this program.
93    pub fn entrypoint(&self) -> MastNodeId {
94        self.entrypoint
95    }
96
97    /// Returns a reference to the underlying [`MastForest`].
98    pub fn mast_forest(&self) -> &Arc<MastForest> {
99        &self.mast_forest
100    }
101
102    /// Returns the kernel associated with this program.
103    pub fn kernel(&self) -> &Kernel {
104        &self.kernel
105    }
106
107    /// Returns the [`MastNode`] associated with the provided [`MastNodeId`] if valid, or else
108    /// `None`.
109    ///
110    /// This is the fallible version of indexing (e.g. `program[node_id]`).
111    #[inline(always)]
112    pub fn get_node_by_id(&self, node_id: MastNodeId) -> Option<&MastNode> {
113        self.mast_forest.get_node_by_id(node_id)
114    }
115
116    /// Returns the [`MastNodeId`] of the procedure root associated with a given digest, if any.
117    #[inline(always)]
118    pub fn find_procedure_root(&self, digest: Word) -> Option<MastNodeId> {
119        self.mast_forest.find_procedure_root(digest)
120    }
121
122    /// Returns the number of procedures in this program.
123    pub fn num_procedures(&self) -> u32 {
124        self.mast_forest.num_procedures()
125    }
126
127    /// Returns basic information about this program (i.e., program hash and kernel).
128    pub fn to_info(&self) -> ProgramInfo {
129        ProgramInfo::new(self.hash(), self.kernel().clone())
130    }
131}
132
133// ------------------------------------------------------------------------------------------------
134/// Serialization
135#[cfg(feature = "std")]
136impl Program {
137    /// Writes this [Program] to the provided file path.
138    pub fn write_to_file<P>(&self, path: P) -> std::io::Result<()>
139    where
140        P: AsRef<std::path::Path>,
141    {
142        let path = path.as_ref();
143        if let Some(dir) = path.parent() {
144            std::fs::create_dir_all(dir)?;
145        }
146
147        // NOTE: We're protecting against unwinds here due to i/o errors that will get turned into
148        // panics if writing to the underlying file fails. This is because ByteWriter does not have
149        // fallible APIs, thus WriteAdapter has to panic if writes fail. This could be fixed, but
150        // that has to happen upstream in miden-crypto
151        std::panic::catch_unwind(|| match std::fs::File::create(path) {
152            Ok(ref mut file) => {
153                self.write_into(file);
154                Ok(())
155            },
156            Err(err) => Err(err),
157        })
158        .map_err(|p| match p.downcast::<std::io::Error>() {
159            Ok(err) => *err,
160            // Propagate unknown panics
161            Err(err) => std::panic::resume_unwind(err),
162        })?
163    }
164}
165
166impl Serializable for Program {
167    fn write_into<W: ByteWriter>(&self, target: &mut W) {
168        self.mast_forest.write_into(target);
169        self.kernel.write_into(target);
170        target.write_u32(self.entrypoint.into());
171    }
172}
173
174impl Deserializable for Program {
175    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
176        let mast_forest = Arc::new(source.read()?);
177        let kernel = source.read()?;
178        let entrypoint = MastNodeId::from_u32_safe(source.read_u32()?, &mast_forest)?;
179
180        if !mast_forest.is_procedure_root(entrypoint) {
181            return Err(DeserializationError::InvalidValue(format!(
182                "entrypoint {entrypoint} is not a procedure"
183            )));
184        }
185
186        Ok(Self::with_kernel(mast_forest, entrypoint, kernel))
187    }
188}
189
190// ------------------------------------------------------------------------------------------------
191// Pretty-printing
192
193impl crate::prettier::PrettyPrint for Program {
194    fn render(&self) -> crate::prettier::Document {
195        use crate::prettier::*;
196        let entrypoint = self.mast_forest[self.entrypoint()].to_pretty_print(&self.mast_forest);
197
198        indent(4, const_text("begin") + nl() + entrypoint.render()) + nl() + const_text("end")
199    }
200}
201
202impl fmt::Display for Program {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        use crate::prettier::PrettyPrint;
205        self.pretty_print(f)
206    }
207}
208
209// PROGRAM INFO
210// ===============================================================================================
211
212/// A program information set consisting of its MAST root and set of kernel procedure roots used
213/// for its compilation.
214///
215/// This will be used as public inputs of the proof so we bind its verification to the kernel and
216/// root used to execute the program. This way, we extend the correctness of the proof to the
217/// security guarantees provided by the kernel. We also allow the user to easily prove the
218/// membership of a given kernel procedure for a given proof, without compromising its
219/// zero-knowledge properties.
220#[derive(Debug, Clone, Default, PartialEq, Eq)]
221pub struct ProgramInfo {
222    program_hash: Word,
223    kernel: Kernel,
224}
225
226impl ProgramInfo {
227    /// Creates a new instance of a program info.
228    pub const fn new(program_hash: Word, kernel: Kernel) -> Self {
229        Self { program_hash, kernel }
230    }
231
232    /// Returns the program hash computed from its code block root.
233    pub const fn program_hash(&self) -> &Word {
234        &self.program_hash
235    }
236
237    /// Returns the program kernel used during the compilation.
238    pub const fn kernel(&self) -> &Kernel {
239        &self.kernel
240    }
241
242    /// Returns the list of procedures of the kernel used during the compilation.
243    pub fn kernel_procedures(&self) -> &[Word] {
244        self.kernel.proc_hashes()
245    }
246}
247
248impl From<Program> for ProgramInfo {
249    fn from(program: Program) -> Self {
250        let program_hash = program.hash();
251        let kernel = program.kernel().clone();
252
253        Self { program_hash, kernel }
254    }
255}
256
257// ------------------------------------------------------------------------------------------------
258// Serialization
259
260impl Serializable for ProgramInfo {
261    fn write_into<W: ByteWriter>(&self, target: &mut W) {
262        self.program_hash.write_into(target);
263        self.kernel.write_into(target);
264    }
265}
266
267impl Deserializable for ProgramInfo {
268    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
269        let program_hash = source.read()?;
270        let kernel = source.read()?;
271        Ok(Self { program_hash, kernel })
272    }
273}
274
275// ------------------------------------------------------------------------------------------------
276// ToElements implementation
277
278impl ToElements for ProgramInfo {
279    fn to_elements(&self) -> Vec<Felt> {
280        let num_kernel_proc_elements = self.kernel.proc_hashes().len() * WORD_SIZE;
281        let mut result = Vec::with_capacity(2 * WORD_SIZE + num_kernel_proc_elements);
282
283        // append program hash elements where we pad with zero so as to make the fixed length
284        // public inputs section of the public inputs of length a multiple of 8 i.e., double-word
285        // aligned
286        result.extend_from_slice(self.program_hash.as_elements());
287        result.extend_from_slice(&[Felt::ZERO; 4]);
288
289        // append kernel procedure hash elements
290        // we reverse the digests in order to make reducing them using auxiliary randomness easier
291        // we also pad them to the next multiple of 8
292        for proc_hash in self.kernel.proc_hashes() {
293            let mut proc_hash_elements = proc_hash.as_elements().to_vec();
294            pad_next_mul_8(&mut proc_hash_elements);
295            proc_hash_elements.reverse();
296            result.extend_from_slice(&proc_hash_elements);
297        }
298        result
299    }
300}
301
302// HELPER
303// ===============================================================================================
304
305/// Pads a vector of field elements using zeros to the next multiple of 8.
306fn pad_next_mul_8(input: &mut Vec<Felt>) {
307    let output_len = input.len().next_multiple_of(8);
308    input.resize(output_len, Felt::ZERO);
309}