miden_core/mast/serialization/mod.rs
1//! MAST forest serialization keeps one fixed structural layout for normal and hashless payloads.
2//!
3//! The main goal is to keep random access cheap in both modes. Node structure
4//! stays in one fixed-width section. Variable-size data lives in separate sections. Internal node
5//! digests also live in a separate section so hashless payloads can omit them without changing the
6//! structural layout.
7//!
8//! Wire flags describe serializer intent, not reader trust policy. Trusted [`MastForest`] reads
9//! reject hashless payloads. [`crate::mast::UntrustedMastForest`] accepts them and rebuilds
10//! non-external digests before use. If a non-hashless payload is sent down the untrusted path,
11//! validation recomputes those digests and requires them to match the serialized values.
12//! Budgeted untrusted reads always bound wire counts during layout scanning via
13//! [`ByteReader::max_alloc`]. Validation also gets a second check:
14//! - later hashless helper allocations are charged against a validation budget before the
15//! corresponding `Vec` or CSR scaffolding is created
16//! - that budget is derived from the wire budget by a coarse multiplier; this is intentionally a
17//! simple bound for common callers, not an exact peak-memory formula
18//!
19//! The main layers fit together like this:
20//!
21//! ```text
22//! wire bytes
23//! |
24//! +--> ForestLayout -----------> MastForestWireView ----+
25//! | absolute offsets trusted cache view |
26//! | v
27//! +--> UntrustedMastForest ----validate----> ResolvedSerializedForest ---> MastForest
28//! bytes + parsed state digest-backed view trusted runtime
29//!
30//! MastForestView is the shared random-access API implemented by MastForestWireView and
31//! MastForest.
32//! ```
33//!
34//! The format is:
35//!
36//! (Metadata)
37//! - MAGIC (4 bytes) + FLAGS (1 byte) + VERSION (3 bytes)
38//!
39//! (Counts)
40//! - internal nodes count (`usize`)
41//! - external nodes count (`usize`)
42//!
43//! (Procedure roots section)
44//! - procedure roots (`Vec<u32>` as MastNodeId values)
45//!
46//! (Basic block data section)
47//! - basic block data (padded operations + batch metadata)
48//!
49//! (Node entries section)
50//! - fixed-width structural node entries (`Vec<MastNodeEntry>`)
51//! - `Block` entries store offsets into the basic-block section above
52//!
53//! (External digest section)
54//! - digests for `External` nodes only (`Vec<Word>`, ordered by node index)
55//! - lookup is dense-by-kind: the Nth external node uses slot N in this section
56//!
57//! (Node hash section - omitted if FLAGS bit 1 is set)
58//! - digests for all non-external nodes (`Vec<Word>`, ordered by node index)
59//! - lookup is also dense-by-kind: the Nth non-external node uses slot N in this section
60//!
61//! (Advice map section)
62//! - Advice map (`AdviceMap`)
63//!
64//! (No trailing debug section)
65//!
66//! Readers reject any trailing payload after the advice map. Package-owned debug sections are now
67//! the only supported debug serialization path.
68//!
69//! In hashless format, the internal node-hash section is omitted. External node digests still stay
70//! on the wire because they cannot be rebuilt from local structure. This keeps hashless focused on
71//! the untrusted-validation use case: trusted reads reject `HASHLESS`, and the untrusted path
72//! rebuilds the data it actually trusts before use.
73//!
74//! Readers recover per-node digest lookup by scanning node entries once and building a compact
75//! "slot by node index" table. This preserves random access without forcing all digests into the
76//! same contiguous array on the wire.
77//!
78//! Public entry points adopt these policies:
79//! - [`MastForest::read_from_bytes`]: trusted dense execution payload, no hashless support.
80//! - [`MastForestWireView::new`]: trusted wire-backed cache access; rejects hashless and legacy
81//! debug-bearing payloads.
82//! - [`crate::mast::SparseMastForest::read_from_bytes`]: separate trusted sparse replay payloads
83//! for serialized trace-generation inputs. Sparse payloads preserve the sparse node and digest
84//! maps produced by tracing; they do not share the dense `MastForest` wire format and are not an
85//! untrusted validation boundary. They are version-local and must not be persisted across
86//! releases.
87//! - [`crate::mast::UntrustedMastForest::read_from_bytes`] /
88//! [`crate::mast::UntrustedMastForest::read_from_bytes_with_options`]: untrusted parsing plus
89//! later validation before use.
90
91#[cfg(test)]
92use alloc::string::ToString;
93use alloc::{boxed::Box, format, vec::Vec};
94use core::{mem::size_of, panic::Location};
95
96use miden_utils_sync::OnceLockCompat;
97
98use super::{MastForest, MastNode, MastNodeId};
99use crate::{
100 Word,
101 advice::AdviceMap,
102 mast::node::MastNodeExt,
103 serde::{
104 BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
105 SliceReader,
106 },
107};
108
109mod info;
110pub use info::{MastNodeEntry, MastNodeInfo};
111
112mod view;
113use view::WireAdviceMapView;
114pub use view::{AdviceMapView, AdviceValueView, MastForestView};
115
116mod layout;
117pub(super) use layout::ForestLayout;
118use layout::{OffsetTrackingReader, TrackingReader, WireFlags, read_header_and_scan_layout};
119
120mod sparse;
121
122mod resolved;
123use resolved::{ResolvedSerializedForest, basic_block_offset_for_node_index};
124
125mod basic_blocks;
126use basic_blocks::{BasicBlockDataBuilder, basic_block_data_len};
127
128pub(super) fn basic_block_content_key(basic_block: &crate::mast::BasicBlockNode) -> Vec<u8> {
129 let mut builder = BasicBlockDataBuilder::new();
130 builder.encode_basic_block(basic_block);
131 builder.finalize()
132}
133
134#[cfg(test)]
135mod seed_gen;
136
137#[cfg(test)]
138mod tests;
139
140// TYPE ALIASES
141// ================================================================================================
142
143/// Specifies an offset into the `node_data` section of an encoded [`MastForest`].
144type NodeDataOffset = u32;
145
146/// Default multiplier for the untrusted validation allocation budget.
147///
148/// The budgeted byte reader limits wire-driven parsing. Hashless validation also needs transient
149/// per-node allocations for the slot table and rebuilt digest data.
150/// The generic untrusted path also retains a recorded copy of the consumed
151/// serialized payload for deferred validation.
152///
153/// This convenience multiplier is therefore a coarse "wire bytes plus worst-case helper
154/// headroom" bound:
155/// - `* 6` covers the helper-allocation model introduced with explicit validation budgeting
156/// - `+ 1 * bytes_len` covers the retained serialized copy recorded during untrusted reads
157///
158/// It is deliberately conservative and exists to make the default
159/// [`crate::mast::UntrustedMastForest::read_from_bytes`] path usable without forcing callers to
160/// size each helper allocation themselves. Callers with stricter limits should use
161/// [`crate::mast::UntrustedMastForest::read_from_bytes_with_options`] and choose an explicit wire
162/// budget; the validation helper budget is derived from it.
163const DEFAULT_UNTRUSTED_ALLOCATION_BUDGET_MULTIPLIER: usize = 7;
164
165/// Byte-read budget multiplier for trusted full deserialization from a byte slice.
166///
167/// The budget is intentionally finite to reject malicious length prefixes, but larger than the
168/// source length because collection deserialization uses conservative per-element size estimates.
169const TRUSTED_BYTE_READ_BUDGET_MULTIPLIER: usize = 64;
170
171// CONSTANTS
172// ================================================================================================
173
174/// Magic bytes for detecting that a file is binary-encoded MAST.
175///
176/// The header is `b"MAST"` + flags byte + version bytes.
177///
178/// This repurposes the old `b"MAST\0"` terminator as the flags byte.
179const MAGIC: &[u8; 4] = b"MAST";
180
181/// Flag indicating that the internal node-hash section is omitted from the wire payload.
182///
183/// External digests still remain serialized in their own section because they cannot be rebuilt
184/// from local structure.
185pub(super) const FLAG_HASHLESS: u8 = 0x02;
186
187/// Mask for reserved flag bits that must be zero.
188///
189/// Bit 0 and bits 2-7 are reserved for future use. If any are set, deserialization fails.
190const FLAGS_RESERVED_MASK: u8 = 0xfd;
191
192/// The format version.
193///
194/// If future modifications are made to this format, the version should be incremented by 1. A
195/// version of `[255, 255, 255]` is reserved for future extensions that require extending the
196/// version field itself, but should be considered invalid for now.
197///
198/// Version history:
199/// - [0, 0, 0]: Initial format.
200/// - [0, 0, 1]: Added batch metadata to basic blocks (operations serialized in padded form with
201/// indptr, padding, and group metadata for exact OpBatch reconstruction). Added asm-op metadata
202/// and debug-variable storage in CSR layout (eliminates per-node metadata sections and round-trip
203/// conversions). Header changed from `MAST\0` to `MAST` + flags byte.
204/// - [0, 0, 2]: AssemblyOps moved out of inline metadata into a dedicated DebugInfo section.
205/// Removed `should_break` field from AssemblyOp serialization (#2646). Removed `breakpoint`
206/// instruction (#2655).
207/// - [0, 0, 3]: Added HASHLESS flag (bit 1). Trusted deserialization rejects HASHLESS. Split
208/// fixed-width node entries from digest storage. External digests moved to a dedicated section.
209/// Hashless serialization omits the general node-hash section entirely. Removed the unused
210/// metadata-count field from the wire header and added explicit internal/external node counts.
211/// - [0, 0, 4]: Removed the legacy inline metadata wire slots entirely. All assembly op metadata
212/// and debug variable metadata are now stored in the DebugInfo section as separate indexed
213/// records. MAST nodes are metadata-free identifiers. Reserved bit 0 and removed the forest-level
214/// debug-presence flag.
215/// - [0, 0, 5]: Replaced opcode 0x50's HPERM semantics with COMPRESS. Rejecting version 4 prevents
216/// an old serialized node from retaining its stored digest while being executed with the new
217/// operation semantics on load paths that do not recompute node digests.
218///
219/// Legacy wire versions (pre-#3192 decorator terminology):
220/// [0,0,1] stored metadata as serialized decorator variants in CSR per-node slots.
221/// [0,0,2] removed AssemblyOp from the decorator enum and stored them separately in DebugInfo.
222/// [0,0,3] removed the unused decorator-count wire field.
223/// [0,0,4] eliminated the decorator wire slots entirely.
224const VERSION: [u8; 3] = [0, 0, 5];
225
226// MAST FOREST SERIALIZATION/DESERIALIZATION
227// ================================================================================================
228
229impl Serializable for MastForest {
230 fn write_into<W: ByteWriter>(&self, target: &mut W) {
231 self.write_into_with_options(target, false);
232 }
233
234 /// Returns the exact serialized size in bytes without allocating or serializing the forest.
235 ///
236 /// # Panics
237 ///
238 /// Panics if the serialized size exceeds [`usize::MAX`].
239 fn get_size_hint(&self) -> usize {
240 self.serialized_size_hint(false)
241 }
242}
243
244impl MastForest {
245 pub(super) fn serialized_size_hint(&self, hashless: bool) -> usize {
246 let node_count = self.nodes.len();
247 let external_count = self.nodes.iter().take_while(|node| node.is_external()).count();
248 let internal_count = node_count - external_count;
249
250 let basic_block_len: usize = self
251 .nodes
252 .iter()
253 .filter_map(|node| match node {
254 MastNode::Block(block) => Some(basic_block_data_len(block)),
255 _ => None,
256 })
257 .try_fold(0usize, usize::checked_add)
258 .expect("MAST forest serialized size exceeds usize::MAX");
259 let digest_count = if hashless { external_count } else { node_count };
260 let roots_size = self
261 .roots
262 .len()
263 .checked_mul(size_of::<u32>())
264 .expect("MAST forest serialized size exceeds usize::MAX");
265 let entries_size = node_count
266 .checked_mul(MastNodeEntry::SERIALIZED_SIZE)
267 .expect("MAST forest serialized size exceeds usize::MAX");
268 let digests_size = digest_count
269 .checked_mul(Word::SERIALIZED_SIZE)
270 .expect("MAST forest serialized size exceeds usize::MAX");
271
272 [
273 MAGIC.len() + size_of::<u8>() + VERSION.len(),
274 internal_count.get_size_hint(),
275 external_count.get_size_hint(),
276 self.roots.len().get_size_hint(),
277 roots_size,
278 basic_block_len.get_size_hint(),
279 basic_block_len,
280 entries_size,
281 digests_size,
282 self.advice_map.get_size_hint(),
283 ]
284 .into_iter()
285 .try_fold(0usize, usize::checked_add)
286 .expect("MAST forest serialized size exceeds usize::MAX")
287 }
288
289 /// Internal serialization with options.
290 ///
291 /// Current writers encode normal execution payloads or hashless validation payloads.
292 /// Both forms use the finalized dense node order already stored in the `MastForest`; writers
293 /// validate that order but do not sort nodes while writing.
294 fn write_into_with_options<W: ByteWriter>(&self, target: &mut W, hashless: bool) {
295 self.validate_dense_node_order()
296 .expect("dense MAST forest must be in final dense order before serialization");
297
298 let mut basic_block_data_builder = BasicBlockDataBuilder::new();
299
300 // magic & flags
301 target.write_bytes(MAGIC);
302 let flags = if hashless { FLAG_HASHLESS } else { 0 };
303 target.write_u8(flags);
304
305 // version
306 target.write_bytes(&VERSION);
307
308 // header counts
309 let node_count = self.nodes.len();
310 let external_node_count = self.nodes.iter().take_while(|node| node.is_external()).count();
311 let internal_node_count = node_count - external_node_count;
312 target.write_usize(internal_node_count);
313 target.write_usize(external_node_count);
314
315 // roots
316 let roots: Vec<u32> = self.roots.iter().copied().map(u32::from).collect();
317 roots.write_into(target);
318
319 let mut mast_node_entries = Vec::with_capacity(self.nodes.len());
320 let mut external_digests = Vec::with_capacity(external_node_count);
321 let mut node_hashes = Vec::new();
322
323 for mast_node in self.nodes.iter() {
324 let ops_offset = if let MastNode::Block(basic_block) = mast_node {
325 basic_block_data_builder.encode_basic_block(basic_block)
326 } else {
327 0
328 };
329
330 mast_node_entries.push(MastNodeEntry::new(mast_node, ops_offset));
331 if mast_node.is_external() {
332 external_digests.push(mast_node.digest());
333 } else if !hashless {
334 node_hashes.push(mast_node.digest());
335 }
336 }
337
338 let basic_block_data = basic_block_data_builder.finalize();
339 basic_block_data.write_into(target);
340
341 for mast_node_entry in mast_node_entries {
342 mast_node_entry.write_into(target);
343 }
344
345 for digest in external_digests {
346 digest.write_into(target);
347 }
348
349 if !hashless {
350 for digest in node_hashes {
351 digest.write_into(target);
352 }
353 }
354
355 self.advice_map.write_into(target);
356 }
357}
358
359pub(super) fn write_hashless_into<W: ByteWriter>(forest: &MastForest, target: &mut W) {
360 forest.write_into_with_options(target, true);
361}
362
363/// Trusted read backing mode for read-only MAST forest access.
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub enum MastForestReadMode {
366 /// Deserialize the full trusted cache into a materialized [`MastForest`].
367 Materialized,
368 /// Borrow complete trusted cache bytes and serve read-only data by random access.
369 WireBacked,
370}
371
372/// Read-only trusted MAST forest handle.
373#[derive(Debug)]
374pub enum MastForestReadView<'a> {
375 /// A fully materialized forest.
376 Materialized(MastForest),
377 /// A trusted wire-backed cache view.
378 WireBacked(Box<MastForestWireView<'a>>),
379}
380
381/// A trusted wire-backed view over serialized MAST forest bytes.
382///
383/// This view accepts complete payloads with hashes. It validates the header and the fixed-width
384/// structural sections needed for random access, but it does not fully materialize the forest.
385/// Hashless payloads are rejected because trusted cache bytes must be complete. Trailing payloads
386/// are rejected because debug metadata now belongs to package-owned debug sections.
387/// Internal digest limbs are decoded on access, so an in-range node may still produce a decoding
388/// error. External digests are decoded during construction to validate their ordering.
389///
390/// Use this when callers need random access to roots or node metadata without deserializing the
391/// full forest. For strict trusted deserialization, use
392/// [`crate::mast::MastForest::read_from_bytes`].
393///
394/// # Examples
395///
396/// ```
397/// use miden_core::{
398/// mast::{BasicBlockNodeBuilder, DenseMastForestBuilder, MastForestWireView},
399/// operations::Operation,
400/// serde::Serializable,
401/// };
402///
403/// let mut builder = DenseMastForestBuilder::new();
404/// let block_id = builder.push_node(BasicBlockNodeBuilder::new(vec![Operation::Add])).unwrap();
405/// builder.mark_root(block_id);
406/// let forest = builder.build().unwrap();
407///
408/// let mut bytes = Vec::new();
409/// forest.write_into(&mut bytes);
410///
411/// let view = MastForestWireView::new(&bytes).unwrap();
412/// assert_eq!(view.node_count(), forest.nodes().len());
413/// assert!(view.node_info_at(0).is_ok());
414/// ```
415#[derive(Debug)]
416pub struct MastForestWireView<'a> {
417 bytes: &'a [u8],
418 layout: ForestLayout,
419 advice_map: WireAdviceMapView<'a>,
420 resolved: OnceLockCompat<Result<ResolvedSerializedForest<'a>, DeserializationError>>,
421}
422
423impl<'a> MastForestWireView<'a> {
424 /// Creates a new view from serialized bytes.
425 ///
426 /// The input must include all node hashes. Structural parsing is
427 /// delegated to the same single-pass scanner used by reader-based deserialization paths.
428 ///
429 /// This constructor validates the header and sections needed for node/roots/random-access
430 /// metadata, checks dense node ordering and backward child references, indexes `AdviceMap` keys
431 /// for on-demand lookup, and rejects trailing payloads.
432 ///
433 /// Treat this as a trusted cache API, not as an untrusted-validation entry point. It is
434 /// appropriate for local tools that need random access over serialized structure, but callers
435 /// handling adversarial bytes should use [`crate::mast::UntrustedMastForest`] instead.
436 ///
437 /// In particular, this constructor does **not** protect callers from untrusted-input concerns
438 /// that are enforced by [`crate::mast::UntrustedMastForest::validate`]. It does not:
439 /// - verify that serialized non-external digests match the structure they describe
440 /// - validate basic-block batch invariants
441 /// - materialize or expose package-owned debug sections
442 ///
443 /// For strict materialized validation, use
444 /// [`crate::mast::MastForest::read_from_bytes`].
445 ///
446 /// Digest lookup follows the wire layout:
447 /// - Non-external node digests are read from the internal-hash section on demand. Invalid field
448 /// limbs produce an error from `node_digest_at` and `node_info_at`, even for in-range
449 /// indices.
450 /// - External node digests are read from the external-digest section and decoded during
451 /// construction to check their ordering.
452 ///
453 /// # Examples
454 ///
455 /// ```
456 /// use miden_core::{
457 /// mast::{BasicBlockNodeBuilder, DenseMastForestBuilder, MastForestWireView},
458 /// operations::Operation,
459 /// serde::Serializable,
460 /// };
461 ///
462 /// let mut builder = DenseMastForestBuilder::new();
463 /// let block_id = builder.push_node(BasicBlockNodeBuilder::new(vec![Operation::Add])).unwrap();
464 /// builder.mark_root(block_id);
465 /// let forest = builder.build().unwrap();
466 ///
467 /// let mut bytes = Vec::new();
468 /// forest.write_into(&mut bytes);
469 ///
470 /// let view = MastForestWireView::new(&bytes).unwrap();
471 /// assert_eq!(view.node_count(), 1);
472 /// ```
473 pub fn new(bytes: &'a [u8]) -> Result<Self, DeserializationError> {
474 let mut reader = SliceReader::new(bytes);
475 let mut scanner = TrackingReader::new(&mut reader);
476 let (_flags, layout) = read_header_and_scan_layout(&mut scanner, false)?;
477 let advice_map = WireAdviceMapView::new(bytes, layout.advice_map_offset())?;
478 check_no_trailing_payload(bytes, advice_map.end_offset())?;
479 ResolvedSerializedForest::new(bytes, layout)?.validate_dense_node_order()?;
480
481 Ok(Self {
482 bytes,
483 layout,
484 advice_map,
485 resolved: OnceLockCompat::new(),
486 })
487 }
488
489 /// Returns the number of nodes in the serialized forest.
490 pub fn node_count(&self) -> usize {
491 self.layout.node_count
492 }
493
494 /// Returns the number of procedure roots in the serialized forest.
495 pub fn procedure_root_count(&self) -> usize {
496 self.layout.roots_count
497 }
498
499 /// Returns the procedure root id at the specified index.
500 ///
501 /// Returns an error if `index >= self.procedure_root_count()`.
502 pub fn procedure_root_at(&self, index: usize) -> Result<MastNodeId, DeserializationError> {
503 self.layout.read_procedure_root_at(self.bytes, index)
504 }
505
506 /// Returns the `MastNodeInfo` at the specified index.
507 ///
508 /// Returns an error if `index >= self.node_count()` or the node's digest cannot be decoded.
509 ///
510 /// # Examples
511 ///
512 /// ```
513 /// use miden_core::{
514 /// mast::{BasicBlockNodeBuilder, DenseMastForestBuilder, MastForestWireView},
515 /// operations::Operation,
516 /// serde::Serializable,
517 /// };
518 ///
519 /// let mut builder = DenseMastForestBuilder::new();
520 /// let block_id = builder.push_node(BasicBlockNodeBuilder::new(vec![Operation::Add])).unwrap();
521 /// builder.mark_root(block_id);
522 /// let forest = builder.build().unwrap();
523 ///
524 /// let mut bytes = Vec::new();
525 /// forest.write_into(&mut bytes);
526 ///
527 /// let view = MastForestWireView::new(&bytes).unwrap();
528 /// assert!(view.node_info_at(0).is_ok());
529 /// ```
530 pub fn node_info_at(&self, index: usize) -> Result<MastNodeInfo, DeserializationError> {
531 Ok(MastNodeInfo::from_entry(
532 self.node_entry_at(index)?,
533 self.node_digest_at(index)?,
534 ))
535 }
536
537 /// Returns the fixed-width structural node entry at the specified index.
538 ///
539 /// Returns an error if `index >= self.node_count()`.
540 pub fn node_entry_at(&self, index: usize) -> Result<MastNodeEntry, DeserializationError> {
541 self.layout.read_node_entry_at(self.bytes, index)
542 }
543
544 /// Returns the digest for the node at the specified index.
545 ///
546 /// Returns an error if `index >= self.node_count()` or the digest cannot be decoded.
547 /// Non-external digest limbs are validated on access.
548 pub fn node_digest_at(&self, index: usize) -> Result<Word, DeserializationError> {
549 self.resolved()?.node_digest_at(index)
550 }
551
552 /// Returns a read-only view over the serialized forest advice map.
553 pub fn advice_map(&self) -> AdviceMapView<'_> {
554 AdviceMapView::wire(&self.advice_map)
555 }
556
557 fn resolved(&self) -> Result<&ResolvedSerializedForest<'a>, DeserializationError> {
558 self.resolved
559 .get_or_init(|| ResolvedSerializedForest::new(self.bytes, self.layout))
560 .as_ref()
561 .map_err(Clone::clone)
562 }
563}
564
565fn check_no_trailing_payload(
566 bytes: &[u8],
567 debug_info_offset: usize,
568) -> Result<(), DeserializationError> {
569 let payload = bytes.get(debug_info_offset..).ok_or(DeserializationError::UnexpectedEOF)?;
570 if payload.is_empty() {
571 return Ok(());
572 }
573 Err(extra_bytes_after_mast_forest_payload_error())
574}
575
576fn extra_bytes_after_mast_forest_payload_error() -> DeserializationError {
577 DeserializationError::InvalidValue("extra bytes after MastForest payload".into())
578}
579
580impl MastForest {
581 /// Reads trusted MAST forest bytes using the requested backing mode.
582 ///
583 /// [`MastForestReadMode::Materialized`] is equivalent to [`Self::read_from_bytes`].
584 /// [`MastForestReadMode::WireBacked`] returns a trusted random-access cache view and rejects
585 /// hashless and trailing payloads because trusted cache bytes must be complete execution
586 /// payloads.
587 pub fn read_view_from_bytes(
588 bytes: &[u8],
589 mode: MastForestReadMode,
590 ) -> Result<MastForestReadView<'_>, DeserializationError> {
591 match mode {
592 MastForestReadMode::Materialized => {
593 Self::read_from_bytes(bytes).map(MastForestReadView::Materialized)
594 },
595 MastForestReadMode::WireBacked => {
596 MastForestWireView::new(bytes).map(Box::new).map(MastForestReadView::WireBacked)
597 },
598 }
599 }
600}
601
602impl MastForestView for MastForestWireView<'_> {
603 fn node_count(&self) -> usize {
604 MastForestWireView::node_count(self)
605 }
606
607 fn node_entry_at(&self, index: usize) -> Result<MastNodeEntry, DeserializationError> {
608 MastForestWireView::node_entry_at(self, index)
609 }
610
611 fn node_digest_at(&self, index: usize) -> Result<Word, DeserializationError> {
612 MastForestWireView::node_digest_at(self, index)
613 }
614
615 fn procedure_root_count(&self) -> usize {
616 MastForestWireView::procedure_root_count(self)
617 }
618
619 fn procedure_root_at(&self, index: usize) -> Result<MastNodeId, DeserializationError> {
620 MastForestWireView::procedure_root_at(self, index)
621 }
622
623 fn advice_map(&self) -> AdviceMapView<'_> {
624 MastForestWireView::advice_map(self)
625 }
626}
627
628impl MastForestView for MastForestReadView<'_> {
629 fn node_count(&self) -> usize {
630 match self {
631 MastForestReadView::Materialized(forest) => MastForestView::node_count(forest),
632 MastForestReadView::WireBacked(view) => view.node_count(),
633 }
634 }
635
636 fn node_entry_at(&self, index: usize) -> Result<MastNodeEntry, DeserializationError> {
637 match self {
638 MastForestReadView::Materialized(forest) => {
639 MastForestView::node_entry_at(forest, index)
640 },
641 MastForestReadView::WireBacked(view) => view.node_entry_at(index),
642 }
643 }
644
645 fn node_digest_at(&self, index: usize) -> Result<Word, DeserializationError> {
646 match self {
647 MastForestReadView::Materialized(forest) => {
648 MastForestView::node_digest_at(forest, index)
649 },
650 MastForestReadView::WireBacked(view) => view.node_digest_at(index),
651 }
652 }
653
654 fn procedure_root_count(&self) -> usize {
655 match self {
656 MastForestReadView::Materialized(forest) => {
657 MastForestView::procedure_root_count(forest)
658 },
659 MastForestReadView::WireBacked(view) => view.procedure_root_count(),
660 }
661 }
662
663 fn procedure_root_at(&self, index: usize) -> Result<MastNodeId, DeserializationError> {
664 match self {
665 MastForestReadView::Materialized(forest) => {
666 MastForestView::procedure_root_at(forest, index)
667 },
668 MastForestReadView::WireBacked(view) => view.procedure_root_at(index),
669 }
670 }
671
672 fn advice_map(&self) -> AdviceMapView<'_> {
673 match self {
674 MastForestReadView::Materialized(forest) => MastForestView::advice_map(forest),
675 MastForestReadView::WireBacked(view) => view.advice_map(),
676 }
677 }
678}
679
680impl MastForestView for MastForest {
681 fn node_count(&self) -> usize {
682 self.nodes.len()
683 }
684
685 fn node_entry_at(&self, index: usize) -> Result<MastNodeEntry, DeserializationError> {
686 let node = self.nodes.as_slice().get(index).ok_or_else(|| {
687 DeserializationError::InvalidValue(format!("node index {index} out of bounds"))
688 })?;
689 let ops_offset = if matches!(node, MastNode::Block(_)) {
690 basic_block_offset_for_node_index(self.nodes.as_slice(), index)?
691 } else {
692 0
693 };
694
695 Ok(MastNodeEntry::new(node, ops_offset))
696 }
697
698 fn node_digest_at(&self, index: usize) -> Result<Word, DeserializationError> {
699 self.nodes.as_slice().get(index).map(MastNode::digest).ok_or_else(|| {
700 DeserializationError::InvalidValue(format!("node index {index} out of bounds"))
701 })
702 }
703
704 fn procedure_root_count(&self) -> usize {
705 self.roots.len()
706 }
707
708 fn procedure_root_at(&self, index: usize) -> Result<MastNodeId, DeserializationError> {
709 self.roots.get(index).copied().ok_or_else(|| {
710 DeserializationError::InvalidValue(format!(
711 "root index {} out of bounds for {} roots",
712 index,
713 self.roots.len()
714 ))
715 })
716 }
717
718 fn advice_map(&self) -> AdviceMapView<'_> {
719 AdviceMapView::materialized(&self.advice_map)
720 }
721}
722
723// TEST HELPERS
724// ================================================================================================
725
726#[cfg(test)]
727impl MastForestWireView<'_> {
728 fn debug_info_offset(&self) -> usize {
729 self.advice_map.end_offset()
730 }
731
732 fn node_entry_offset(&self) -> usize {
733 self.layout.node_entry_offset()
734 }
735
736 fn external_digest_offset(&self) -> usize {
737 self.layout.external_digest_offset()
738 }
739
740 fn node_hash_offset(&self) -> Option<usize> {
741 self.layout.node_hash_offset()
742 }
743
744 fn digest_slot_at(&self, index: usize) -> usize {
745 self.resolved()
746 .expect("digest slots should be readable for a valid serialized view")
747 .digest_slot_at(index)
748 }
749}
750
751#[cfg(test)]
752fn read_u8_at(bytes: &[u8], offset: &mut usize) -> Result<u8, DeserializationError> {
753 read_slice_at(bytes, offset, 1).map(|slice| slice[0])
754}
755
756#[cfg(test)]
757fn read_array_at<const N: usize>(
758 bytes: &[u8],
759 offset: &mut usize,
760) -> Result<[u8; N], DeserializationError> {
761 let slice = read_slice_at(bytes, offset, N)?;
762 let mut result = [0u8; N];
763 result.copy_from_slice(slice);
764 Ok(result)
765}
766
767#[cfg(test)]
768fn read_slice_at<'a>(
769 bytes: &'a [u8],
770 offset: &mut usize,
771 len: usize,
772) -> Result<&'a [u8], DeserializationError> {
773 let end = offset
774 .checked_add(len)
775 .ok_or_else(|| DeserializationError::InvalidValue("offset overflow".to_string()))?;
776 if end > bytes.len() {
777 return Err(DeserializationError::UnexpectedEOF);
778 }
779 let slice = &bytes[*offset..end];
780 *offset = end;
781 Ok(slice)
782}
783
784// NOTE: Mirrors ByteReader::read_usize (vint64) decoding to preserve wire compatibility.
785#[cfg(test)]
786fn read_usize_at(bytes: &[u8], offset: &mut usize) -> Result<usize, DeserializationError> {
787 if *offset >= bytes.len() {
788 return Err(DeserializationError::UnexpectedEOF);
789 }
790 let first_byte = bytes[*offset];
791 let length = first_byte.trailing_zeros() as usize + 1;
792
793 let result = if length == 9 {
794 let _marker = read_u8_at(bytes, offset)?;
795 let value = read_array_at::<8>(bytes, offset)?;
796 u64::from_le_bytes(value)
797 } else {
798 let mut encoded = [0u8; 8];
799 let value = read_slice_at(bytes, offset, length)?;
800 encoded[..length].copy_from_slice(value);
801 u64::from_le_bytes(encoded) >> length
802 };
803
804 if result > usize::MAX as u64 {
805 return Err(DeserializationError::InvalidValue(format!(
806 "Encoded value must be less than {}, but {} was provided",
807 usize::MAX,
808 result
809 )));
810 }
811
812 Ok(result as usize)
813}
814
815impl Deserializable for MastForest {
816 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
817 let (_flags, forest) = decode_from_reader(source, false)?;
818 forest.into_materialized()
819 }
820
821 fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
822 let budget = bytes.len().saturating_mul(TRUSTED_BYTE_READ_BUDGET_MULTIPLIER);
823 let mut reader = BudgetedReader::new(SliceReader::new(bytes), budget);
824 let forest = Self::read_from(&mut reader)?;
825 if reader.has_more_bytes() {
826 return Err(extra_bytes_after_mast_forest_payload_error());
827 }
828 Ok(forest)
829 }
830}
831
832impl super::UntrustedMastForest {
833 pub(super) fn into_materialized(self) -> Result<MastForest, DeserializationError> {
834 let resolved = if let Some(allocation_budget) = self.remaining_allocation_budget {
835 ResolvedSerializedForest::new_with_allocation_budget(
836 &self.bytes,
837 self.layout,
838 allocation_budget,
839 )?
840 } else {
841 ResolvedSerializedForest::new(&self.bytes, self.layout)?
842 };
843
844 resolved.materialize(self.advice_map)
845 }
846}
847
848pub(super) fn read_untrusted_with_flags_and_caller<R: ByteReader>(
849 source: &mut R,
850 caller: &'static Location<'static>,
851) -> Result<(super::UntrustedMastForest, u8), DeserializationError> {
852 let (flags, forest) = decode_from_reader(source, true)?;
853 log_untrusted_overspecification(flags, caller);
854 Ok((forest, flags.bits()))
855}
856
857pub(super) fn read_untrusted_with_flags_allocation_budget_and_caller<R: ByteReader>(
858 source: &mut R,
859 allocation_budget: usize,
860 caller: &'static Location<'static>,
861) -> Result<(super::UntrustedMastForest, u8), DeserializationError> {
862 let (flags, forest) = decode_from_reader_inner(source, true, Some(allocation_budget))?;
863 log_untrusted_overspecification(flags, caller);
864 Ok((forest, flags.bits()))
865}
866
867fn log_untrusted_overspecification(flags: WireFlags, caller: &'static Location<'static>) {
868 if !flags.is_hashless() {
869 log::warn!(
870 "UntrustedMastForest expected HASHLESS input at {}:{}:{}; supplied artifact includes wire node hashes, and validation will recompute them and require them to match",
871 caller.file(),
872 caller.line(),
873 caller.column(),
874 );
875 }
876}
877
878fn decode_from_reader<R: ByteReader>(
879 source: &mut R,
880 allow_hashless: bool,
881) -> Result<(WireFlags, super::UntrustedMastForest), DeserializationError> {
882 decode_from_reader_inner(source, allow_hashless, None)
883}
884
885fn decode_from_reader_inner<R: ByteReader>(
886 source: &mut R,
887 allow_hashless: bool,
888 remaining_allocation_budget: Option<usize>,
889) -> Result<(WireFlags, super::UntrustedMastForest), DeserializationError> {
890 let mut recording = TrackingReader::new_recording(source);
891 let (flags, layout) = read_header_and_scan_layout(&mut recording, allow_hashless)?;
892 debug_assert_eq!(recording.offset(), layout.advice_map_offset());
893
894 let advice_map = AdviceMap::read_from(&mut recording)?;
895 Ok((
896 flags,
897 super::UntrustedMastForest {
898 bytes: recording.into_recorded(),
899 layout,
900 advice_map,
901 remaining_allocation_budget,
902 },
903 ))
904}
905
906pub(super) fn reserve_allocation<T>(
907 remaining_budget: &mut usize,
908 count: usize,
909 label: &str,
910) -> Result<(), DeserializationError> {
911 let bytes_needed = count
912 .checked_mul(size_of::<T>())
913 .ok_or_else(|| DeserializationError::InvalidValue(format!("{label} size overflow")))?;
914 if bytes_needed > *remaining_budget {
915 return Err(DeserializationError::InvalidValue(format!(
916 "{label} requires {bytes_needed} bytes, exceeding the remaining untrusted allocation budget of {} bytes",
917 *remaining_budget
918 )));
919 }
920
921 *remaining_budget -= bytes_needed;
922 Ok(())
923}
924
925pub(super) fn default_untrusted_allocation_budget(bytes_len: usize) -> usize {
926 bytes_len.saturating_mul(DEFAULT_UNTRUSTED_ALLOCATION_BUDGET_MULTIPLIER)
927}
928
929// UNTRUSTED DESERIALIZATION
930// ================================================================================================
931
932impl Deserializable for super::UntrustedMastForest {
933 /// Deserializes an [`super::UntrustedMastForest`] from a byte reader.
934 ///
935 /// Note: This method does not apply budgeting. For untrusted input, prefer using
936 /// [`read_from_bytes`](Self::read_from_bytes) which applies budgeted deserialization.
937 ///
938 /// After deserialization, callers should use [`super::UntrustedMastForest::validate()`]
939 /// to verify structural integrity and recompute all node hashes before using
940 /// the forest.
941 #[track_caller]
942 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
943 super::UntrustedMastForest::read_from_reader(source)
944 }
945
946 /// Deserializes an [`super::UntrustedMastForest`] from bytes using budgeted deserialization.
947 ///
948 /// This method uses the default untrusted wire/validation budget from
949 /// [`super::UntrustedMastForest::read_from_bytes`].
950 ///
951 /// After deserialization, callers should use [`super::UntrustedMastForest::validate()`]
952 /// to verify structural integrity and recompute all node hashes before using
953 /// the forest.
954 #[track_caller]
955 fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
956 super::UntrustedMastForest::read_from_bytes(bytes)
957 }
958}