use alloc::{
collections::{BTreeMap, BTreeSet},
string::String,
sync::Arc,
vec::Vec,
};
use core::{
fmt,
ops::{Index, IndexMut},
};
use miden_utils_sync::OnceLockCompat;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
mod node;
#[cfg(any(test, feature = "arbitrary"))]
pub use node::arbitrary;
pub(crate) use node::collect_immediate_placements;
pub use node::{
BasicBlockNode, BasicBlockNodeBuilder, CallNode, CallNodeBuilder, DecoratedOpLink,
DecoratorOpLinkIterator, DecoratorStore, DynNode, DynNodeBuilder, ExternalNode,
ExternalNodeBuilder, JoinNode, JoinNodeBuilder, LoopNode, LoopNodeBuilder,
MastForestContributor, MastNode, MastNodeBuilder, MastNodeExt, OP_BATCH_SIZE, OP_GROUP_SIZE,
OpBatch, OperationOrDecorator, SplitNode, SplitNodeBuilder,
};
use crate::{
Felt, LexicographicWord, Word,
advice::AdviceMap,
operations::{AssemblyOp, DebugVarInfo, Decorator},
serde::{
BudgetedReader, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
SliceReader,
},
utils::{Idx, IndexVec, hash_string_to_word},
};
mod debuginfo;
pub use debuginfo::{
AsmOpIndexError, DebugInfo, DebugVarId, DecoratedLinks, DecoratedLinksIter,
DecoratorIndexError, NodeToDecoratorIds, OpToAsmOpId, OpToDebugVarIds, OpToDecoratorIds,
};
mod serialization;
mod merger;
pub(crate) use merger::MastForestMerger;
pub use merger::MastForestRootMap;
mod multi_forest_node_iterator;
pub(crate) use multi_forest_node_iterator::*;
mod node_fingerprint;
pub use node_fingerprint::{DecoratorFingerprint, MastNodeFingerprint};
mod node_builder_utils;
pub use node_builder_utils::build_node_with_remapped_ids;
#[cfg(test)]
mod tests;
#[derive(Clone, Debug, Default)]
pub struct MastForest {
nodes: IndexVec<MastNodeId, MastNode>,
roots: Vec<MastNodeId>,
advice_map: AdviceMap,
debug_info: DebugInfo,
commitment_cache: OnceLockCompat<Word>,
}
impl MastForest {
pub fn new() -> Self {
Self {
nodes: IndexVec::new(),
roots: Vec::new(),
advice_map: AdviceMap::default(),
debug_info: DebugInfo::new(),
commitment_cache: OnceLockCompat::new(),
}
}
}
impl PartialEq for MastForest {
fn eq(&self, other: &Self) -> bool {
self.nodes == other.nodes
&& self.roots == other.roots
&& self.advice_map == other.advice_map
&& self.debug_info == other.debug_info
}
}
impl Eq for MastForest {}
impl MastForest {
const MAX_NODES: usize = (1 << 30) - 1;
pub fn make_root(&mut self, new_root_id: MastNodeId) {
assert!(new_root_id.to_usize() < self.nodes.len());
if !self.roots.contains(&new_root_id) {
self.roots.push(new_root_id);
self.commitment_cache.take();
}
}
pub fn remove_nodes(
&mut self,
nodes_to_remove: &BTreeSet<MastNodeId>,
) -> BTreeMap<MastNodeId, MastNodeId> {
if nodes_to_remove.is_empty() {
return BTreeMap::new();
}
let old_nodes = core::mem::replace(&mut self.nodes, IndexVec::new());
let old_root_ids = core::mem::take(&mut self.roots);
let (retained_nodes, id_remappings) = remove_nodes(old_nodes.into_inner(), nodes_to_remove);
self.remap_and_add_nodes(retained_nodes, &id_remappings);
self.remap_and_add_roots(old_root_ids, &id_remappings);
self.debug_info.remap_asm_op_storage(&id_remappings);
self.debug_info.remap_debug_var_storage(&id_remappings);
self.commitment_cache.take();
id_remappings
}
pub fn clear_debug_info(&mut self) {
self.debug_info = DebugInfo::empty_for_nodes(self.nodes.len());
}
pub fn compact(self) -> (MastForest, MastForestRootMap) {
MastForest::merge([&self])
.expect("Failed to compact MastForest: this should never happen during self-merge")
}
pub fn merge<'forest>(
forests: impl IntoIterator<Item = &'forest MastForest>,
) -> Result<(MastForest, MastForestRootMap), MastForestError> {
MastForestMerger::merge(forests)
}
}
impl MastForest {
fn remap_and_add_nodes(
&mut self,
nodes_to_add: Vec<MastNode>,
id_remappings: &BTreeMap<MastNodeId, MastNodeId>,
) {
assert!(self.nodes.is_empty());
let node_builders =
nodes_to_add.into_iter().map(|node| node.to_builder(self)).collect::<Vec<_>>();
self.debug_info.clear_mappings();
for live_node_builder in node_builders {
live_node_builder.remap_children(id_remappings).add_to_forest(self).unwrap();
}
}
fn remap_and_add_roots(
&mut self,
old_root_ids: Vec<MastNodeId>,
id_remappings: &BTreeMap<MastNodeId, MastNodeId>,
) {
assert!(self.roots.is_empty());
for old_root_id in old_root_ids {
let new_root_id = id_remappings.get(&old_root_id).copied().unwrap_or(old_root_id);
self.make_root(new_root_id);
}
}
}
fn remove_nodes(
mast_nodes: Vec<MastNode>,
nodes_to_remove: &BTreeSet<MastNodeId>,
) -> (Vec<MastNode>, BTreeMap<MastNodeId, MastNodeId>) {
assert!(mast_nodes.len() < u32::MAX as usize);
let mut retained_nodes = Vec::with_capacity(mast_nodes.len());
let mut id_remappings = BTreeMap::new();
for (old_node_index, old_node) in mast_nodes.into_iter().enumerate() {
let old_node_id: MastNodeId = MastNodeId(old_node_index as u32);
if !nodes_to_remove.contains(&old_node_id) {
let new_node_id: MastNodeId = MastNodeId(retained_nodes.len() as u32);
id_remappings.insert(old_node_id, new_node_id);
retained_nodes.push(old_node);
}
}
(retained_nodes, id_remappings)
}
impl MastForest {
#[inline(always)]
pub fn get_node_by_id(&self, node_id: MastNodeId) -> Option<&MastNode> {
self.nodes.get(node_id)
}
#[inline(always)]
pub fn find_procedure_root(&self, digest: Word) -> Option<MastNodeId> {
self.roots.iter().find(|&&root_id| self[root_id].digest() == digest).copied()
}
pub fn is_procedure_root(&self, node_id: MastNodeId) -> bool {
self.roots.contains(&node_id)
}
pub fn procedure_digests(&self) -> impl Iterator<Item = Word> + '_ {
self.roots.iter().map(|&root_id| self[root_id].digest())
}
pub fn local_procedure_digests(&self) -> impl Iterator<Item = Word> + '_ {
self.roots.iter().filter_map(|&root_id| {
let node = &self[root_id];
if node.is_external() { None } else { Some(node.digest()) }
})
}
pub fn procedure_roots(&self) -> &[MastNodeId] {
&self.roots
}
pub fn num_procedures(&self) -> u32 {
self.roots
.len()
.try_into()
.expect("MAST forest contains more than 2^32 procedures.")
}
pub fn compute_nodes_commitment<'a>(
&self,
node_ids: impl IntoIterator<Item = &'a MastNodeId>,
) -> Word {
let mut digests: Vec<Word> = node_ids.into_iter().map(|&id| self[id].digest()).collect();
digests.sort_unstable_by_key(|word| LexicographicWord::from(*word));
miden_crypto::hash::poseidon2::Poseidon2::merge_many(&digests)
}
pub fn commitment(&self) -> Word {
*self.commitment_cache.get_or_init(|| self.compute_nodes_commitment(&self.roots))
}
pub fn num_nodes(&self) -> u32 {
self.nodes.len() as u32
}
pub fn nodes(&self) -> &[MastNode] {
self.nodes.as_slice()
}
pub fn advice_map(&self) -> &AdviceMap {
&self.advice_map
}
pub fn advice_map_mut(&mut self) -> &mut AdviceMap {
&mut self.advice_map
}
pub fn write_stripped<W: ByteWriter>(&self, target: &mut W) {
use serialization::StrippedMastForest;
StrippedMastForest(self).write_into(target);
}
}
impl MastForest {
pub fn decorators(&self) -> &[Decorator] {
self.debug_info.decorators()
}
#[inline]
pub fn decorator_by_id(&self, decorator_id: DecoratorId) -> Option<&Decorator> {
self.debug_info.decorator(decorator_id)
}
#[inline]
pub(crate) fn decorator_indices_for_op(
&self,
node_id: MastNodeId,
local_op_idx: usize,
) -> &[DecoratorId] {
self.debug_info.decorators_for_operation(node_id, local_op_idx)
}
#[inline]
pub fn decorators_for_op<'a>(
&'a self,
node_id: MastNodeId,
local_op_idx: usize,
) -> impl Iterator<Item = &'a Decorator> + 'a {
self.decorator_indices_for_op(node_id, local_op_idx)
.iter()
.map(move |&decorator_id| &self[decorator_id])
}
#[inline]
pub fn before_enter_decorators(&self, node_id: MastNodeId) -> &[DecoratorId] {
self.debug_info.before_enter_decorators(node_id)
}
#[inline]
pub fn after_exit_decorators(&self, node_id: MastNodeId) -> &[DecoratorId] {
self.debug_info.after_exit_decorators(node_id)
}
#[inline]
pub(crate) fn decorator_links_for_node<'a>(
&'a self,
node_id: MastNodeId,
) -> Result<DecoratedLinks<'a>, DecoratorIndexError> {
self.debug_info.decorator_links_for_node(node_id)
}
pub fn add_decorator(&mut self, decorator: Decorator) -> Result<DecoratorId, MastForestError> {
self.debug_info.add_decorator(decorator)
}
pub fn add_debug_var(
&mut self,
debug_var: DebugVarInfo,
) -> Result<DebugVarId, MastForestError> {
self.debug_info.add_debug_var(debug_var)
}
pub fn debug_vars_for_operation(
&self,
node_id: MastNodeId,
local_op_idx: usize,
) -> &[DebugVarId] {
self.debug_info.debug_vars_for_operation(node_id, local_op_idx)
}
pub fn debug_var(&self, debug_var_id: DebugVarId) -> Option<&DebugVarInfo> {
self.debug_info.debug_var(debug_var_id)
}
#[inline]
pub(crate) fn register_node_decorators(
&mut self,
node_id: MastNodeId,
before_enter: &[DecoratorId],
after_exit: &[DecoratorId],
) {
self.debug_info.register_node_decorators(node_id, before_enter, after_exit);
}
pub fn get_assembly_op(
&self,
node_id: MastNodeId,
target_op_idx: Option<usize>,
) -> Option<&AssemblyOp> {
match target_op_idx {
Some(op_idx) => self.debug_info.asm_op_for_operation(node_id, op_idx),
None => self.debug_info.first_asm_op_for_node(node_id),
}
}
}
impl MastForest {
pub fn validate(&self) -> Result<(), MastForestError> {
for (node_id_idx, node) in self.nodes.iter().enumerate() {
let node_id =
MastNodeId::new_unchecked(node_id_idx.try_into().expect("too many nodes"));
if let MastNode::Block(basic_block) = node {
basic_block.validate_batch_invariants().map_err(|error_msg| {
MastForestError::InvalidBatchPadding(node_id, error_msg)
})?;
}
}
for (digest, _) in self.debug_info.procedure_names() {
if self.find_procedure_root(digest).is_none() {
return Err(MastForestError::InvalidProcedureNameDigest(digest));
}
}
Ok(())
}
fn validate_node_hashes(&self) -> Result<(), MastForestError> {
use crate::chiplets::hasher;
fn check_no_forward_ref(
node_id: MastNodeId,
child_id: MastNodeId,
) -> Result<(), MastForestError> {
if child_id.0 >= node_id.0 {
return Err(MastForestError::ForwardReference(node_id, child_id));
}
Ok(())
}
for (node_idx, node) in self.nodes.iter().enumerate() {
let node_id = MastNodeId::new_unchecked(node_idx as u32);
let computed_digest = match node {
MastNode::Block(block) => {
let op_groups: Vec<Felt> =
block.op_batches().iter().flat_map(|batch| *batch.groups()).collect();
hasher::hash_elements(&op_groups)
},
MastNode::Join(join) => {
let left_id = join.first();
let right_id = join.second();
check_no_forward_ref(node_id, left_id)?;
check_no_forward_ref(node_id, right_id)?;
let left_digest = self.nodes[left_id].digest();
let right_digest = self.nodes[right_id].digest();
hasher::merge_in_domain(&[left_digest, right_digest], JoinNode::DOMAIN)
},
MastNode::Split(split) => {
let true_id = split.on_true();
let false_id = split.on_false();
check_no_forward_ref(node_id, true_id)?;
check_no_forward_ref(node_id, false_id)?;
let true_digest = self.nodes[true_id].digest();
let false_digest = self.nodes[false_id].digest();
hasher::merge_in_domain(&[true_digest, false_digest], SplitNode::DOMAIN)
},
MastNode::Loop(loop_node) => {
let body_id = loop_node.body();
check_no_forward_ref(node_id, body_id)?;
let body_digest = self.nodes[body_id].digest();
hasher::merge_in_domain(&[body_digest, Word::default()], LoopNode::DOMAIN)
},
MastNode::Call(call) => {
let callee_id = call.callee();
check_no_forward_ref(node_id, callee_id)?;
let callee_digest = self.nodes[callee_id].digest();
let domain = if call.is_syscall() {
CallNode::SYSCALL_DOMAIN
} else {
CallNode::CALL_DOMAIN
};
hasher::merge_in_domain(&[callee_digest, Word::default()], domain)
},
MastNode::Dyn(dyn_node) => {
if dyn_node.is_dyncall() {
DynNode::DYNCALL_DEFAULT_DIGEST
} else {
DynNode::DYN_DEFAULT_DIGEST
}
},
MastNode::External(_) => {
continue;
},
};
let stored_digest = node.digest();
if computed_digest != stored_digest {
return Err(MastForestError::HashMismatch {
node_id,
expected: stored_digest,
computed: computed_digest,
});
}
}
Ok(())
}
}
impl MastForest {
pub fn resolve_error_message(&self, code: Felt) -> Option<Arc<str>> {
let key = code.as_canonical_u64();
self.debug_info.error_message(key)
}
pub fn register_error(&mut self, msg: Arc<str>) -> Felt {
let code: Felt = error_code_from_msg(&msg);
self.debug_info.insert_error_code(code.as_canonical_u64(), msg);
code
}
}
impl MastForest {
pub fn procedure_name(&self, digest: &Word) -> Option<&str> {
self.debug_info.procedure_name(digest)
}
pub fn procedure_names(&self) -> impl Iterator<Item = (Word, &Arc<str>)> {
self.debug_info.procedure_names()
}
pub fn insert_procedure_name(&mut self, digest: Word, name: Arc<str>) {
assert!(
self.find_procedure_root(digest).is_some(),
"attempted to insert procedure name for digest that is not a procedure root"
);
self.debug_info.insert_procedure_name(digest, name);
}
pub fn debug_info(&self) -> &DebugInfo {
&self.debug_info
}
pub fn debug_info_mut(&mut self) -> &mut DebugInfo {
&mut self.debug_info
}
}
#[cfg(test)]
impl MastForest {
pub fn all_decorators(&self, node_id: MastNodeId) -> Vec<(usize, DecoratorId)> {
let node = &self[node_id];
if !node.is_basic_block() {
let before_enter_decorators: Vec<_> = self
.before_enter_decorators(node_id)
.iter()
.map(|&deco_id| (0, deco_id))
.collect();
let after_exit_decorators: Vec<_> = self
.after_exit_decorators(node_id)
.iter()
.map(|&deco_id| (1, deco_id))
.collect();
return [before_enter_decorators, after_exit_decorators].concat();
}
let block = node.unwrap_basic_block();
let before_enter_decorators: Vec<_> = self
.before_enter_decorators(node_id)
.iter()
.map(|&deco_id| (0, deco_id))
.collect();
let op_indexed_decorators: Vec<_> =
self.decorator_links_for_node(node_id).unwrap().into_iter().collect();
let after_exit_decorators: Vec<_> = self
.after_exit_decorators(node_id)
.iter()
.map(|&deco_id| (block.num_operations() as usize, deco_id))
.collect();
[before_enter_decorators, op_indexed_decorators, after_exit_decorators].concat()
}
}
impl Index<MastNodeId> for MastForest {
type Output = MastNode;
#[inline(always)]
fn index(&self, node_id: MastNodeId) -> &Self::Output {
&self.nodes[node_id]
}
}
impl IndexMut<MastNodeId> for MastForest {
#[inline(always)]
fn index_mut(&mut self, node_id: MastNodeId) -> &mut Self::Output {
&mut self.nodes[node_id]
}
}
impl Index<DecoratorId> for MastForest {
type Output = Decorator;
#[inline(always)]
fn index(&self, decorator_id: DecoratorId) -> &Self::Output {
self.debug_info.decorator(decorator_id).expect("DecoratorId out of bounds")
}
}
impl IndexMut<DecoratorId> for MastForest {
#[inline(always)]
fn index_mut(&mut self, decorator_id: DecoratorId) -> &mut Self::Output {
self.debug_info.decorator_mut(decorator_id).expect("DecoratorId out of bounds")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[cfg_attr(all(feature = "arbitrary", test), miden_test_serde_macros::serde_test)]
pub struct MastNodeId(u32);
pub type Remapping = BTreeMap<MastNodeId, MastNodeId>;
impl MastNodeId {
pub fn from_u32_safe(
value: u32,
mast_forest: &MastForest,
) -> Result<Self, DeserializationError> {
Self::from_u32_with_node_count(value, mast_forest.nodes.len())
}
pub fn from_usize_safe(
node_id: usize,
mast_forest: &MastForest,
) -> Result<Self, DeserializationError> {
let node_id: u32 = node_id.try_into().map_err(|_| {
DeserializationError::InvalidValue(format!(
"node id '{node_id}' does not fit into a u32"
))
})?;
MastNodeId::from_u32_safe(node_id, mast_forest)
}
pub fn new_unchecked(value: u32) -> Self {
Self(value)
}
pub(super) fn from_u32_with_node_count(
id: u32,
node_count: usize,
) -> Result<Self, DeserializationError> {
if (id as usize) < node_count {
Ok(Self(id))
} else {
Err(DeserializationError::InvalidValue(format!(
"Invalid deserialized MAST node ID '{id}', but {node_count} is the number of nodes in the forest",
)))
}
}
pub fn remap(&self, remapping: &Remapping) -> Self {
*remapping.get(self).unwrap_or(self)
}
}
impl From<u32> for MastNodeId {
fn from(value: u32) -> Self {
MastNodeId::new_unchecked(value)
}
}
impl Idx for MastNodeId {}
impl From<MastNodeId> for u32 {
fn from(value: MastNodeId) -> Self {
value.0
}
}
impl fmt::Display for MastNodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "MastNodeId({})", self.0)
}
}
#[cfg(any(test, feature = "arbitrary"))]
impl proptest::prelude::Arbitrary for MastNodeId {
type Parameters = ();
fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
use proptest::prelude::*;
any::<u32>().prop_map(MastNodeId).boxed()
}
type Strategy = proptest::prelude::BoxedStrategy<Self>;
}
pub struct SubtreeIterator<'a> {
forest: &'a MastForest,
discovered: Vec<MastNodeId>,
unvisited: Vec<MastNodeId>,
}
impl<'a> SubtreeIterator<'a> {
pub fn new(root: &MastNodeId, forest: &'a MastForest) -> Self {
let discovered = vec![];
let unvisited = vec![*root];
SubtreeIterator { forest, discovered, unvisited }
}
}
impl Iterator for SubtreeIterator<'_> {
type Item = MastNodeId;
fn next(&mut self) -> Option<MastNodeId> {
while let Some(id) = self.unvisited.pop() {
let node = &self.forest[id];
if !node.has_children() {
return Some(id);
} else {
self.discovered.push(id);
node.append_children_to(&mut self.unvisited);
}
}
self.discovered.pop()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct DecoratorId(u32);
impl DecoratorId {
pub fn from_u32_safe(
value: u32,
mast_forest: &MastForest,
) -> Result<Self, DeserializationError> {
Self::from_u32_bounded(value, mast_forest.debug_info.num_decorators())
}
pub fn from_u32_bounded(value: u32, bound: usize) -> Result<Self, DeserializationError> {
if (value as usize) < bound {
Ok(Self(value))
} else {
Err(DeserializationError::InvalidValue(format!(
"Invalid deserialized MAST decorator id '{}', but allows only {} decorators",
value, bound,
)))
}
}
pub(crate) fn new_unchecked(value: u32) -> Self {
Self(value)
}
}
impl From<u32> for DecoratorId {
fn from(value: u32) -> Self {
DecoratorId::new_unchecked(value)
}
}
impl Idx for DecoratorId {}
impl From<DecoratorId> for u32 {
fn from(value: DecoratorId) -> Self {
value.0
}
}
impl fmt::Display for DecoratorId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "DecoratorId({})", self.0)
}
}
impl Serializable for DecoratorId {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
self.0.write_into(target)
}
}
impl Deserializable for DecoratorId {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let value = u32::read_from(source)?;
Ok(Self(value))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct AsmOpId(u32);
impl AsmOpId {
pub const fn new(value: u32) -> Self {
Self(value)
}
}
impl From<u32> for AsmOpId {
fn from(value: u32) -> Self {
AsmOpId::new(value)
}
}
impl Idx for AsmOpId {}
impl From<AsmOpId> for u32 {
fn from(id: AsmOpId) -> Self {
id.0
}
}
impl fmt::Display for AsmOpId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "AsmOpId({})", self.0)
}
}
impl Serializable for AsmOpId {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
self.0.write_into(target)
}
}
impl Deserializable for AsmOpId {
fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
let value = u32::read_from(source)?;
Ok(Self(value))
}
}
pub fn error_code_from_msg(msg: impl AsRef<str>) -> Felt {
hash_string_to_word(msg.as_ref())[0]
}
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum MastForestError {
#[error("MAST forest decorator count exceeds the maximum of {} decorators", u32::MAX)]
TooManyDecorators,
#[error("MAST forest node count exceeds the maximum of {} nodes", MastForest::MAX_NODES)]
TooManyNodes,
#[error("node id {0} is greater than or equal to forest length {1}")]
NodeIdOverflow(MastNodeId, usize),
#[error("decorator id {0} is greater than or equal to decorator count {1}")]
DecoratorIdOverflow(DecoratorId, usize),
#[error("basic block cannot be created from an empty list of operations")]
EmptyBasicBlock,
#[error(
"decorator root of child with node id {0} is missing but is required for fingerprint computation"
)]
ChildFingerprintMissing(MastNodeId),
#[error("advice map key {0} already exists when merging forests")]
AdviceMapKeyCollisionOnMerge(Word),
#[error("decorator storage error: {0}")]
DecoratorError(DecoratorIndexError),
#[error("digest is required for deserialization")]
DigestRequiredForDeserialization,
#[error("invalid batch in basic block node {0:?}: {1}")]
InvalidBatchPadding(MastNodeId, String),
#[error("procedure name references digest that is not a procedure root: {0:?}")]
InvalidProcedureNameDigest(Word),
#[error(
"node {0:?} references child {1:?} which comes after it in the forest (forward reference)"
)]
ForwardReference(MastNodeId, MastNodeId),
#[error("hash mismatch for node {node_id:?}: expected {expected:?}, computed {computed:?}")]
HashMismatch {
node_id: MastNodeId,
expected: Word,
computed: Word,
},
}
#[cfg(feature = "serde")]
impl serde::Serialize for MastForest {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let bytes = Serializable::to_bytes(self);
serializer.serialize_bytes(&bytes)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for MastForest {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let bytes = Vec::<u8>::deserialize(deserializer)?;
let mut slice_reader = SliceReader::new(&bytes);
Deserializable::read_from(&mut slice_reader).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone)]
pub struct UntrustedMastForest(MastForest);
impl UntrustedMastForest {
pub fn validate(self) -> Result<MastForest, MastForestError> {
let forest = self.0;
forest.validate()?;
forest.validate_node_hashes()?;
Ok(forest)
}
pub fn read_from_bytes(bytes: &[u8]) -> Result<Self, DeserializationError> {
Self::read_from_bytes_with_budget(bytes, bytes.len())
}
pub fn read_from_bytes_with_budget(
bytes: &[u8],
budget: usize,
) -> Result<Self, DeserializationError> {
let mut reader = BudgetedReader::new(SliceReader::new(bytes), budget);
Self::read_from(&mut reader)
}
}