Skip to main content

miden_core/mast/serialization/
sparse.rs

1use alloc::{collections::BTreeMap, format, string::ToString, vec::Vec};
2
3use super::{
4    TRUSTED_BYTE_READ_BUDGET_MULTIPLIER,
5    basic_blocks::{BasicBlockDataBuilder, BasicBlockDataDecoder},
6};
7use crate::{
8    Word,
9    advice::AdviceMap,
10    mast::{
11        BasicBlockNodeBuilder, CallNodeBuilder, DynNodeBuilder, ExternalNodeBuilder,
12        JoinNodeBuilder, LoopNodeBuilder, MastForest, MastForestContributor, MastNode, MastNodeExt,
13        MastNodeId, SparseMastForest, SplitNodeBuilder,
14    },
15    serde::{
16        BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
17        SliceReader, read_bounded_len,
18    },
19};
20
21const SPARSE_BLOCK: u8 = 0;
22const SPARSE_JOIN: u8 = 1;
23const SPARSE_SPLIT: u8 = 2;
24const SPARSE_LOOP: u8 = 3;
25const SPARSE_CALL: u8 = 4;
26const SPARSE_SYSCALL: u8 = 5;
27const SPARSE_DYN: u8 = 6;
28const SPARSE_DYNCALL: u8 = 7;
29const SPARSE_EXTERNAL: u8 = 8;
30
31// WRITER
32// ================================================================================================
33
34/// Writes version-local sparse trace replay data.
35///
36/// This format preserves the sparse maps produced by execution tracing. It does not prove that
37/// this sparse view is a subset of a committed [`MastForest`], and it does not share the dense
38/// [`MastForest`] wire format. Checking full-node hashes does not authenticate opaque child
39/// digests or establish source membership. The format is not suitable for persistence across
40/// releases.
41fn write_sparse_into<W: ByteWriter>(forest: &SparseMastForest, target: &mut W) {
42    write_node_ids(forest.procedure_roots(), target);
43    write_sparse_nodes(forest.nodes(), target);
44    write_digest_entries(forest.digest_entries(), target);
45    forest.advice_map().write_into(target);
46}
47
48fn write_node_ids<W: ByteWriter>(ids: &[MastNodeId], target: &mut W) {
49    target.write_usize(ids.len());
50    for id in ids {
51        id.write_into(target);
52    }
53}
54
55fn write_sparse_nodes<W: ByteWriter>(nodes: &BTreeMap<MastNodeId, MastNode>, target: &mut W) {
56    target.write_usize(nodes.len());
57    for (&id, node) in nodes {
58        id.write_into(target);
59        write_sparse_node(node, target);
60    }
61}
62
63fn write_digest_entries<W: ByteWriter>(digests: &BTreeMap<MastNodeId, Word>, target: &mut W) {
64    target.write_usize(digests.len());
65    for (&id, &digest) in digests {
66        id.write_into(target);
67        digest.write_into(target);
68    }
69}
70
71fn write_sparse_node<W: ByteWriter>(node: &MastNode, target: &mut W) {
72    match node {
73        MastNode::Block(block) => {
74            target.write_u8(SPARSE_BLOCK);
75            node.digest().write_into(target);
76
77            let mut basic_block_data = BasicBlockDataBuilder::new();
78            let ops_offset = basic_block_data.encode_basic_block(block);
79            debug_assert_eq!(ops_offset, 0);
80            let basic_block_data = basic_block_data.finalize();
81            target.write_usize(basic_block_data.len());
82            target.write_bytes(&basic_block_data);
83        },
84        MastNode::Join(join) => {
85            target.write_u8(SPARSE_JOIN);
86            node.digest().write_into(target);
87            join.first().write_into(target);
88            join.second().write_into(target);
89        },
90        MastNode::Split(split) => {
91            target.write_u8(SPARSE_SPLIT);
92            node.digest().write_into(target);
93            split.on_true().write_into(target);
94            split.on_false().write_into(target);
95        },
96        MastNode::Loop(loop_node) => {
97            target.write_u8(SPARSE_LOOP);
98            node.digest().write_into(target);
99            loop_node.body().write_into(target);
100        },
101        MastNode::Call(call) => {
102            target.write_u8(if call.is_syscall() { SPARSE_SYSCALL } else { SPARSE_CALL });
103            node.digest().write_into(target);
104            call.callee().write_into(target);
105        },
106        MastNode::Dyn(dyn_node) => {
107            target.write_u8(if dyn_node.is_dyncall() {
108                SPARSE_DYNCALL
109            } else {
110                SPARSE_DYN
111            });
112            node.digest().write_into(target);
113        },
114        MastNode::External(_) => {
115            target.write_u8(SPARSE_EXTERNAL);
116            node.digest().write_into(target);
117        },
118    }
119}
120
121// TRAIT IMPLS
122// ================================================================================================
123
124impl Serializable for SparseMastForest {
125    fn write_into<W: ByteWriter>(&self, target: &mut W) {
126        write_sparse_into(self, target);
127    }
128}
129
130impl Deserializable for SparseMastForest {
131    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
132        let forest = read_sparse_from(source)?;
133        forest
134            .validate()
135            .map_err(|error| DeserializationError::InvalidValue(error.to_string()))?;
136        Ok(forest)
137    }
138
139    fn min_serialized_size() -> usize {
140        usize::min_serialized_size()
141    }
142
143    /// Reads a bounded sparse replay payload and checks its full-node hashes.
144    ///
145    /// Digest-only entries and external nodes remain opaque. This does not prove membership in
146    /// a particular source forest. Trailing bytes are rejected.
147    fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
148        read_sparse_from_bytes(bytes, false)
149    }
150}
151
152impl SparseMastForest {
153    /// Reads trusted replay data without recomputing node hashes.
154    ///
155    /// Structural checks still apply. The caller supplies any byte-consumption budget through
156    /// `source`; use the default byte-slice reader for untrusted input.
157    pub fn read_from_trusted<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
158        read_sparse_from(source)
159    }
160
161    /// Reads trusted replay bytes without recomputing node hashes. Rejects trailing bytes.
162    pub fn read_from_bytes_trusted(bytes: &[u8]) -> Result<Self, DeserializationError> {
163        read_sparse_from_bytes(bytes, true)
164    }
165}
166
167fn read_sparse_from_bytes(
168    bytes: &[u8],
169    trusted: bool,
170) -> Result<SparseMastForest, DeserializationError> {
171    let budget = if trusted {
172        bytes.len().saturating_mul(TRUSTED_BYTE_READ_BUDGET_MULTIPLIER)
173    } else {
174        bytes.len()
175    };
176    let mut reader = BudgetedReader::new(SliceReader::new(bytes), budget);
177    let forest = if trusted {
178        SparseMastForest::read_from_trusted(&mut reader)?
179    } else {
180        SparseMastForest::read_from(&mut reader)?
181    };
182    if reader.has_more_bytes() {
183        return Err(DeserializationError::InvalidValue(
184            "extra bytes after SparseMastForest payload".to_string(),
185        ));
186    }
187    Ok(forest)
188}
189
190// READER
191// ================================================================================================
192
193fn read_sparse_from<R: ByteReader>(
194    source: &mut R,
195) -> Result<SparseMastForest, DeserializationError> {
196    let roots = read_node_ids(source, "procedure root")?;
197    let nodes = read_sparse_nodes(source)?;
198    let digest_entries = read_digest_entries(source)?;
199    let advice_map = read_empty_advice_map(source)?;
200
201    SparseMastForest::from_serialized_parts(nodes, digest_entries, roots, advice_map)
202}
203
204fn read_empty_advice_map<R: ByteReader>(source: &mut R) -> Result<AdviceMap, DeserializationError> {
205    let count = source.read_usize()?;
206    if count != 0 {
207        return Err(DeserializationError::InvalidValue(
208            "sparse MAST replay payload must not carry advice map entries".to_string(),
209        ));
210    }
211
212    Ok(AdviceMap::default())
213}
214
215fn read_node_ids<R: ByteReader>(
216    source: &mut R,
217    label: &str,
218) -> Result<Vec<MastNodeId>, DeserializationError> {
219    let count = read_bounded_count(source, u32::min_serialized_size(), label)?;
220    let mut ids = Vec::with_capacity(count);
221    for _ in 0..count {
222        ids.push(read_node_id(source, label)?);
223    }
224    Ok(ids)
225}
226
227fn read_sparse_nodes<R: ByteReader>(
228    source: &mut R,
229) -> Result<Vec<(MastNodeId, MastNode)>, DeserializationError> {
230    let count = read_bounded_count(source, sparse_node_min_size(), "full node count")?;
231    let mut nodes = Vec::with_capacity(count);
232    let mut previous_id = None;
233
234    for _ in 0..count {
235        let id = read_node_id(source, "full node")?;
236        validate_strictly_increasing_id(previous_id, id, "full node")?;
237        let node = read_sparse_node(source, id)?;
238        nodes.push((id, node));
239        previous_id = Some(id);
240    }
241
242    Ok(nodes)
243}
244
245fn read_digest_entries<R: ByteReader>(
246    source: &mut R,
247) -> Result<Vec<(MastNodeId, Word)>, DeserializationError> {
248    let count =
249        read_bounded_count(source, sparse_digest_entry_min_size(), "digest-only node count")?;
250    let mut digests = Vec::with_capacity(count);
251    let mut previous_id = None;
252
253    for _ in 0..count {
254        let id = read_node_id(source, "digest-only node")?;
255        validate_strictly_increasing_id(previous_id, id, "digest-only node")?;
256        let digest = Word::read_from(source)?;
257        digests.push((id, digest));
258        previous_id = Some(id);
259    }
260
261    Ok(digests)
262}
263
264fn read_sparse_node<R: ByteReader>(
265    source: &mut R,
266    node_id: MastNodeId,
267) -> Result<MastNode, DeserializationError> {
268    let tag = source.read_u8()?;
269    let digest = Word::read_from(source)?;
270
271    let result = match tag {
272        SPARSE_BLOCK => {
273            let len = read_bounded_count(source, 1, "basic block data length")?;
274            let data = source.read_vec(len)?;
275            let decoder = BasicBlockDataDecoder::new(&data);
276            let op_batches = decoder.decode_operations_exact()?;
277            BasicBlockNodeBuilder::from_op_batches(op_batches, digest)
278                .build()
279                .map(Into::into)
280        },
281        SPARSE_JOIN => {
282            let first = read_node_id(source, "join first child")?;
283            let second = read_node_id(source, "join second child")?;
284            JoinNodeBuilder::new([first, second])
285                .with_digest(digest)
286                .build_linked()
287                .map(Into::into)
288        },
289        SPARSE_SPLIT => {
290            let on_true = read_node_id(source, "split true child")?;
291            let on_false = read_node_id(source, "split false child")?;
292            SplitNodeBuilder::new([on_true, on_false])
293                .with_digest(digest)
294                .build_linked()
295                .map(Into::into)
296        },
297        SPARSE_LOOP => {
298            let body = read_node_id(source, "loop body")?;
299            LoopNodeBuilder::new(body).with_digest(digest).build_linked().map(Into::into)
300        },
301        SPARSE_CALL | SPARSE_SYSCALL => {
302            let callee = read_node_id(source, "call callee")?;
303            let builder = if tag == SPARSE_SYSCALL {
304                CallNodeBuilder::new_syscall(callee)
305            } else {
306                CallNodeBuilder::new(callee)
307            };
308            builder.with_digest(digest).build_linked().map(Into::into)
309        },
310        SPARSE_DYN | SPARSE_DYNCALL => {
311            let builder = if tag == SPARSE_DYNCALL {
312                DynNodeBuilder::new_dyncall()
313            } else {
314                DynNodeBuilder::new_dyn()
315            };
316            Ok(builder.with_digest(digest).build().into())
317        },
318        SPARSE_EXTERNAL => Ok(ExternalNodeBuilder::new(digest).build().into()),
319        _ => {
320            return Err(DeserializationError::InvalidValue(format!(
321                "invalid sparse MAST node tag {tag}"
322            )));
323        },
324    };
325
326    result.map_err(|err| {
327        DeserializationError::InvalidValue(format!(
328            "failed to build sparse MAST node {}: {}",
329            node_id.0, err
330        ))
331    })
332}
333
334fn read_bounded_count<R: ByteReader>(
335    source: &mut R,
336    element_size: usize,
337    label: &str,
338) -> Result<usize, DeserializationError> {
339    read_bounded_len(source, label, element_size)
340}
341
342fn sparse_node_min_size() -> usize {
343    u32::min_serialized_size() + u8::min_serialized_size() + Word::min_serialized_size()
344}
345
346fn sparse_digest_entry_min_size() -> usize {
347    u32::min_serialized_size() + Word::min_serialized_size()
348}
349
350fn read_node_id<R: ByteReader>(
351    source: &mut R,
352    label: &str,
353) -> Result<MastNodeId, DeserializationError> {
354    let raw = u32::read_from(source)?;
355    MastNodeId::from_u32_with_node_count(raw, MastForest::MAX_NODES).map_err(|err| {
356        DeserializationError::InvalidValue(format!("invalid {label} id {raw}: {err}"))
357    })
358}
359
360fn validate_strictly_increasing_id(
361    previous: Option<MastNodeId>,
362    current: MastNodeId,
363    label: &str,
364) -> Result<(), DeserializationError> {
365    if previous.is_some_and(|previous| previous >= current) {
366        return Err(DeserializationError::InvalidValue(format!(
367            "{label} ids must be strictly increasing"
368        )));
369    }
370    Ok(())
371}