Skip to main content

miden_protocol/note/
script.rs

1use alloc::string::{String, ToString};
2use alloc::sync::Arc;
3use alloc::vec::Vec;
4use core::fmt::Display;
5use core::num::TryFromIntError;
6
7use miden_core::mast::MastNodeExt;
8use miden_crypto_derive::WordWrapper;
9use miden_mast_package::Package;
10use miden_mast_package::debug_info::PackageDebugInfo;
11use miden_processor::LoadedMastForest;
12
13use super::Felt;
14use crate::assembly::Path;
15use crate::assembly::mast::{MastForest, MastNodeId};
16use crate::errors::NoteError;
17use crate::package::{loaded_mast_forest, package_debug_info};
18use crate::utils::create_external_node_forest;
19use crate::utils::serde::{
20    ByteReader,
21    ByteWriter,
22    Deserializable,
23    DeserializationError,
24    Serializable,
25};
26use crate::vm::AdviceMap;
27use crate::{PrettyPrint, Word};
28
29/// The attribute name used to mark the entrypoint procedure in a note script library.
30const NOTE_SCRIPT_ATTRIBUTE: &str = "note_script";
31
32// NOTE SCRIPT ROOT
33// ================================================================================================
34
35/// The MAST root of a [`NoteScript`].
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, WordWrapper)]
37pub struct NoteScriptRoot(Word);
38
39impl From<NoteScriptRoot> for Word {
40    fn from(root: NoteScriptRoot) -> Self {
41        root.0
42    }
43}
44
45impl Display for NoteScriptRoot {
46    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
47        Display::fmt(&self.0, f)
48    }
49}
50
51impl Serializable for NoteScriptRoot {
52    fn write_into<W: ByteWriter>(&self, target: &mut W) {
53        target.write(self.0);
54    }
55
56    fn get_size_hint(&self) -> usize {
57        self.0.get_size_hint()
58    }
59}
60
61impl Deserializable for NoteScriptRoot {
62    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
63        let word: Word = source.read()?;
64        Ok(Self::from_raw(word))
65    }
66}
67
68// NOTE SCRIPT
69// ================================================================================================
70
71/// An executable program of a note.
72///
73/// A note's script represents a program which must be executed for a note to be consumed. As such
74/// it defines the rules and side effects of consuming a given note.
75#[derive(Debug, Clone)]
76pub struct NoteScript {
77    mast: Arc<MastForest>,
78    entrypoint: MastNodeId,
79    package_debug_info: Option<Arc<PackageDebugInfo>>,
80}
81
82impl NoteScript {
83    // CONSTRUCTORS
84    // --------------------------------------------------------------------------------------------
85
86    /// Returns a new [NoteScript] deserialized from the provided bytes.
87    ///
88    /// # Errors
89    /// Returns an error if note script deserialization fails.
90    pub fn from_bytes(bytes: &[u8]) -> Result<Self, NoteError> {
91        Self::read_from_bytes(bytes).map_err(NoteError::NoteScriptDeserializationError)
92    }
93
94    /// Returns a new [NoteScript] instantiated from the provided components.
95    ///
96    /// # Panics
97    /// Panics if the specified entrypoint is not in the provided MAST forest.
98    pub fn from_parts(mast: Arc<MastForest>, entrypoint: MastNodeId) -> Self {
99        assert!(mast.get_node_by_id(entrypoint).is_some());
100        Self {
101            mast,
102            entrypoint,
103            package_debug_info: None,
104        }
105    }
106
107    /// Returns a new [NoteScript] instantiated from the provided library.
108    ///
109    /// The library must contain exactly one procedure with the `@note_script` attribute,
110    /// which will be used as the entrypoint.
111    ///
112    /// # Errors
113    /// Returns an error if:
114    /// - The library does not contain a procedure with the `@note_script` attribute.
115    /// - The library contains multiple procedures with the `@note_script` attribute.
116    pub fn from_library(library: &Package) -> Result<Self, NoteError> {
117        let mut entrypoint = None;
118
119        for export in library.manifest.exports() {
120            if let Some(proc_export) = export.as_procedure() {
121                // Check for @note_script attribute
122                if proc_export.attributes.has(NOTE_SCRIPT_ATTRIBUTE) {
123                    if entrypoint.is_some() {
124                        return Err(NoteError::NoteScriptMultipleProceduresWithAttribute);
125                    }
126                    entrypoint = Some(
127                        proc_export.node.ok_or(NoteError::NoteScriptNoProcedureWithAttribute)?,
128                    );
129                }
130            }
131        }
132
133        let entrypoint = entrypoint.ok_or(NoteError::NoteScriptNoProcedureWithAttribute)?;
134
135        Ok(Self {
136            mast: library.mast_forest().clone(),
137            entrypoint,
138            package_debug_info: package_debug_info(library),
139        })
140    }
141
142    /// Returns a new [NoteScript] containing only a reference to a procedure in the provided
143    /// library.
144    ///
145    /// This method is useful when a library contains multiple note scripts and you need to
146    /// extract a specific one by its fully qualified path (e.g.,
147    /// `miden::standards::notes::burn::main`).
148    ///
149    /// The procedure at the specified path must have the `@note_script` attribute.
150    ///
151    /// Note: This method creates a minimal [MastForest] containing only an external node
152    /// referencing the procedure's digest, rather than copying the entire library. The actual
153    /// procedure code will be resolved at runtime via the `MastForestStore`.
154    ///
155    /// # Errors
156    /// Returns an error if:
157    /// - The library does not contain a procedure at the specified path.
158    /// - The procedure at the specified path does not have the `@note_script` attribute.
159    pub fn from_library_reference(library: &Package, path: &Path) -> Result<Self, NoteError> {
160        // Find the export matching the path
161        let export = library
162            .manifest
163            .exports()
164            .find(|e| e.path().as_ref() == path)
165            .ok_or_else(|| NoteError::NoteScriptProcedureNotFound(path.to_string().into()))?;
166
167        // Get the procedure export and verify it has the @note_script attribute
168        let proc_export = export
169            .as_procedure()
170            .ok_or_else(|| NoteError::NoteScriptProcedureNotFound(path.to_string().into()))?;
171
172        if !proc_export.attributes.has(NOTE_SCRIPT_ATTRIBUTE) {
173            return Err(NoteError::NoteScriptProcedureMissingAttribute(path.to_string().into()));
174        }
175
176        // Get the digest of the procedure from the library
177        let digest = proc_export.digest;
178
179        // Create a minimal MastForest with just an external node referencing the digest
180        let (mast, entrypoint) = create_external_node_forest(digest);
181
182        Ok(Self {
183            mast: Arc::new(mast),
184            entrypoint,
185            package_debug_info: package_debug_info(library),
186        })
187    }
188
189    // PUBLIC ACCESSORS
190    // --------------------------------------------------------------------------------------------
191
192    /// Returns the commitment of this note script (i.e., the script's MAST root).
193    pub fn root(&self) -> NoteScriptRoot {
194        NoteScriptRoot::from_raw(self.mast[self.entrypoint].digest())
195    }
196
197    /// Returns a reference to the [MastForest] backing this note script.
198    pub fn mast(&self) -> Arc<MastForest> {
199        self.mast.clone()
200    }
201
202    /// Returns the MAST forest and package-owned debug information backing this note script.
203    pub fn loaded_mast_forest(&self) -> LoadedMastForest {
204        loaded_mast_forest(self.mast.clone(), self.package_debug_info.clone())
205    }
206
207    /// Returns an entrypoint node ID of the current script.
208    pub fn entrypoint(&self) -> MastNodeId {
209        self.entrypoint
210    }
211
212    /// Removes debug info from this note script, if any.
213    pub fn clear_debug_info(&mut self) {
214        self.package_debug_info = None;
215    }
216
217    /// Returns a new [NoteScript] with the provided advice map entries merged into the
218    /// underlying [MastForest].
219    ///
220    /// This allows adding advice map entries to an already-compiled note script,
221    /// which is useful when the entries are determined after script compilation.
222    pub fn with_advice_map(self, advice_map: AdviceMap) -> Self {
223        if advice_map.is_empty() {
224            return self;
225        }
226
227        let mast = (*self.mast).clone().with_advice_map(advice_map);
228        Self {
229            mast: Arc::new(mast),
230            entrypoint: self.entrypoint,
231            package_debug_info: self.package_debug_info,
232        }
233    }
234}
235
236impl PartialEq for NoteScript {
237    fn eq(&self, other: &Self) -> bool {
238        self.mast == other.mast && self.entrypoint == other.entrypoint
239    }
240}
241
242impl Eq for NoteScript {}
243
244// CONVERSIONS INTO NOTE SCRIPT
245// ================================================================================================
246
247impl From<&NoteScript> for Vec<Felt> {
248    fn from(script: &NoteScript) -> Self {
249        let mut bytes = script.mast.to_bytes();
250        let len = bytes.len();
251
252        // Pad the data so that it can be encoded with u32
253        let missing = if !len.is_multiple_of(4) { 4 - (len % 4) } else { 0 };
254        bytes.resize(bytes.len() + missing, 0);
255
256        let final_size = 2 + bytes.len();
257        let mut result = Vec::with_capacity(final_size);
258
259        // Push the length, this is used to remove the padding later
260        result.push(Felt::from(u32::from(script.entrypoint)));
261        result.push(Felt::new_unchecked(len as u64));
262
263        // A Felt can not represent all u64 values, so the data is encoded using u32.
264        let mut encoded: &[u8] = &bytes;
265        while encoded.len() >= 4 {
266            let (data, rest) =
267                encoded.split_first_chunk::<4>().expect("The length has been checked");
268            let number = u32::from_le_bytes(*data);
269            result.push(Felt::from(number));
270
271            encoded = rest;
272        }
273
274        result
275    }
276}
277
278impl From<NoteScript> for Vec<Felt> {
279    fn from(value: NoteScript) -> Self {
280        (&value).into()
281    }
282}
283
284impl AsRef<NoteScript> for NoteScript {
285    fn as_ref(&self) -> &NoteScript {
286        self
287    }
288}
289
290// CONVERSIONS FROM NOTE SCRIPT
291// ================================================================================================
292
293impl TryFrom<&[Felt]> for NoteScript {
294    type Error = DeserializationError;
295
296    fn try_from(elements: &[Felt]) -> Result<Self, Self::Error> {
297        if elements.len() < 2 {
298            return Err(DeserializationError::UnexpectedEOF);
299        }
300
301        let entrypoint: u32 = elements[0]
302            .as_canonical_u64()
303            .try_into()
304            .map_err(|err: TryFromIntError| DeserializationError::InvalidValue(err.to_string()))?;
305        let len = elements[1].as_canonical_u64();
306        let mut data = Vec::with_capacity(elements.len() * 4);
307
308        for &felt in &elements[2..] {
309            let element: u32 =
310                felt.as_canonical_u64().try_into().map_err(|err: TryFromIntError| {
311                    DeserializationError::InvalidValue(err.to_string())
312                })?;
313            data.extend(element.to_le_bytes())
314        }
315        data.truncate(len as usize);
316
317        // TODO: Use UntrustedMastForest and check where else we deserialize mast forests.
318        let mast = MastForest::read_from_bytes(&data)?;
319        let entrypoint = MastNodeId::from_u32_safe(entrypoint, &mast)?;
320        Ok(NoteScript::from_parts(Arc::new(mast), entrypoint))
321    }
322}
323
324impl TryFrom<Vec<Felt>> for NoteScript {
325    type Error = DeserializationError;
326
327    fn try_from(value: Vec<Felt>) -> Result<Self, Self::Error> {
328        value.as_slice().try_into()
329    }
330}
331
332// SERIALIZATION
333// ================================================================================================
334
335impl Serializable for NoteScript {
336    fn write_into<W: ByteWriter>(&self, target: &mut W) {
337        self.mast.write_into(target);
338        target.write_u32(u32::from(self.entrypoint));
339    }
340
341    fn get_size_hint(&self) -> usize {
342        // TODO: this is a temporary workaround. Replace mast.to_bytes().len() with
343        // MastForest::get_size_hint() (or a similar size-hint API) once it becomes
344        // available.
345        let mast_size = self.mast.to_bytes().len();
346        let u32_size = 0u32.get_size_hint();
347
348        mast_size + u32_size
349    }
350}
351
352impl Deserializable for NoteScript {
353    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
354        let mast = MastForest::read_from(source)?;
355        let entrypoint = MastNodeId::from_u32_safe(source.read_u32()?, &mast)?;
356
357        Ok(Self::from_parts(Arc::new(mast), entrypoint))
358    }
359}
360
361// PRETTY-PRINTING
362// ================================================================================================
363
364impl PrettyPrint for NoteScript {
365    fn render(&self) -> miden_core::prettier::Document {
366        use miden_core::prettier::*;
367        let entrypoint = self.mast[self.entrypoint].to_pretty_print(&self.mast);
368
369        indent(4, const_text("begin") + nl() + entrypoint.render()) + nl() + const_text("end")
370    }
371}
372
373impl Display for NoteScript {
374    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
375        self.pretty_print(f)
376    }
377}
378
379// TESTS
380// ================================================================================================
381
382#[cfg(test)]
383mod tests {
384
385    use super::{Felt, NoteScript, Vec};
386    use crate::testing::assembler::assemble_test_library;
387    use crate::testing::note::DEFAULT_NOTE_SCRIPT;
388
389    #[test]
390    fn test_note_script_to_from_felt() {
391        let script_src = DEFAULT_NOTE_SCRIPT;
392        let library =
393            assemble_test_library("test-note-script-roundtrip", "test::note_roundtrip", script_src);
394        let note_script = NoteScript::from_library(&library).unwrap();
395
396        let encoded: Vec<Felt> = (&note_script).into();
397        let decoded: NoteScript = encoded.try_into().unwrap();
398
399        assert_eq!(note_script, decoded);
400    }
401
402    #[test]
403    fn test_note_script_preserves_package_debug_info() {
404        let library = assemble_test_library(
405            "test-note-script-debug-info",
406            "test::note_debug_info",
407            DEFAULT_NOTE_SCRIPT,
408        );
409        let note_script = NoteScript::from_library(&library).unwrap();
410
411        assert!(note_script.loaded_mast_forest().package_debug_info().unwrap().is_some());
412    }
413
414    #[test]
415    fn test_note_script_with_advice_map() {
416        use miden_core::advice::AdviceMap;
417
418        use crate::Word;
419
420        let library = assemble_test_library(
421            "test-note-script-with-advice-map",
422            "test::note_with_advice_map",
423            DEFAULT_NOTE_SCRIPT,
424        );
425        let script = NoteScript::from_library(&library).unwrap();
426
427        assert!(script.mast().advice_map().is_empty());
428
429        // Empty advice map should be a no-op
430        let original_root = script.root();
431        let script = script.with_advice_map(AdviceMap::default());
432        assert_eq!(original_root, script.root());
433
434        // Non-empty advice map should add entries
435        let key = Word::from([5u32, 6, 7, 8]);
436        let value = vec![Felt::new_unchecked(100)];
437        let mut advice_map = AdviceMap::default();
438        advice_map.insert(key, value.clone());
439
440        let script = script.with_advice_map(advice_map);
441
442        let mast = script.mast();
443        let stored = mast.advice_map().get(&key).expect("entry should be present");
444        assert_eq!(stored.as_ref(), value.as_slice());
445    }
446}