miden_protocol/note/
script.rs1use 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
29const NOTE_SCRIPT_ATTRIBUTE: &str = "note_script";
31
32#[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#[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 pub fn from_bytes(bytes: &[u8]) -> Result<Self, NoteError> {
91 Self::read_from_bytes(bytes).map_err(NoteError::NoteScriptDeserializationError)
92 }
93
94 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 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 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 pub fn from_library_reference(library: &Package, path: &Path) -> Result<Self, NoteError> {
160 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 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 let digest = proc_export.digest;
178
179 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 pub fn root(&self) -> NoteScriptRoot {
194 NoteScriptRoot::from_raw(self.mast[self.entrypoint].digest())
195 }
196
197 pub fn mast(&self) -> Arc<MastForest> {
199 self.mast.clone()
200 }
201
202 pub fn loaded_mast_forest(&self) -> LoadedMastForest {
204 loaded_mast_forest(self.mast.clone(), self.package_debug_info.clone())
205 }
206
207 pub fn entrypoint(&self) -> MastNodeId {
209 self.entrypoint
210 }
211
212 pub fn clear_debug_info(&mut self) {
214 self.package_debug_info = None;
215 }
216
217 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
244impl 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 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 result.push(Felt::from(u32::from(script.entrypoint)));
261 result.push(Felt::new_unchecked(len as u64));
262
263 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
290impl 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 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
332impl 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 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
361impl 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#[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> = (¬e_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 let original_root = script.root();
431 let script = script.with_advice_map(AdviceMap::default());
432 assert_eq!(original_root, script.root());
433
434 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}