use std::borrow::Cow;
use std::sync::Arc;
use moonproof_ledger::base_crypto::fab::AlignedValue;
use moonproof_ledger::onchain_runtime::ops::{Key, Op};
use moonproof_ledger::onchain_runtime::result_mode::ResultModeGather;
use moonproof_ledger::onchain_runtime::state::{AlignedValueChecked, StateValue};
use moonproof_ledger::storage::arena::Sp;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::Array as StorageArray;
use moonproof_runtime_ir::ir::{MoonIr, VmInstr};
use moonproof_runtime_ir::RuntimeValue as Value;
use rustc_hash::FxHashMap;
use super::descriptor::{
encode_bool, encode_bytes, encode_default, encode_field, encode_literal, encode_uint,
json_as_u128, FabPlan,
};
use super::error::{IrDriverError, Result};
use super::vm_val::VmVal;
pub struct EvalScope<'a> {
#[allow(dead_code)]
pub ir: &'a MoonIr,
pub locals: &'a FxHashMap<String, Value>,
pub args: &'a FxHashMap<String, Value>,
}
impl EvalScope<'_> {
fn resolve_ref_value<'s>(&'s self, inner: &'s Value) -> Result<Cow<'s, Value>> {
if let Some(obj) = inner.as_object() {
match obj.get("expr").and_then(Value::as_str) {
Some("var") => {
if let Some(name) = obj.get("name").and_then(Value::as_str) {
return self.lookup_var(name);
}
}
Some("literal") => {
if let Some(v) = obj.get("value") {
return Ok(Cow::Borrowed(v));
}
}
_ => {}
}
}
let expr: moonproof_runtime_ir::ir::Expression = crate::ir::interp::decode_value_as(inner)
.map_err(|e| IrDriverError::InvalidIr(format!("ref.value not an Expression: {e}")))?;
self.resolve_expr(&expr).map(Cow::Owned)
}
#[inline]
fn lookup_var(&self, name: &str) -> Result<Cow<'_, Value>> {
if let Some(v) = self.args.get(name) {
return Ok(Cow::Borrowed(v));
}
self.locals
.get(name)
.map(Cow::Borrowed)
.ok_or_else(|| IrDriverError::UnboundVariable(name.to_owned()))
}
pub fn resolve_expr(&self, expr: &moonproof_runtime_ir::ir::Expression) -> Result<Value> {
use moonproof_runtime_ir::ir::Expression as E;
use moonproof_runtime_ir::ir::TypeDescriptor as T;
match expr {
E::Var { name } => {
if let Some(v) = self.args.get(name) {
return Ok(v.clone());
}
self.locals
.get(name)
.cloned()
.ok_or_else(|| IrDriverError::UnboundVariable(name.clone()))
}
E::Literal { value } => Ok(value.clone()),
E::EnumRef { of_type, variant } => match of_type {
T::Enum { elements, name } => {
if !elements.iter().any(|v| v == variant) {
return Err(IrDriverError::TypeMismatch(format!(
"enum {name} has no variant '{variant}' (variants: {elements:?})"
)));
}
Ok(Value::String(variant.clone()))
}
other => Err(IrDriverError::TypeMismatch(format!(
"enum-ref descriptor not an Enum: {other:?}"
))),
},
E::Default { of_type } => {
let av = super::descriptor::encode_default(of_type)?;
super::descriptor::decode_aligned_value_full(of_type, &av)
}
E::New { of_type, arguments } => {
let values = arguments
.iter()
.map(|a| self.resolve_expr(a))
.collect::<Result<Vec<_>>>()?;
super::interp::construct(of_type, values)
}
E::EltRef { value, field, .. } => {
let v = self.resolve_expr(value)?;
v.as_object()
.and_then(|obj| obj.get(field).cloned())
.ok_or_else(|| {
IrDriverError::TypeMismatch(format!("field '{field}' not in struct {v}"))
})
}
other => Err(IrDriverError::unimplemented(format!(
"expression in vm-op ref position: {other:?}"
))),
}
}
}
pub fn decode_op(
instr: &VmInstr,
scope: &EvalScope<'_>,
) -> Result<Op<ResultModeGather, InMemoryDB>> {
let op_name = instr
.op()
.ok_or_else(|| IrDriverError::InvalidIr("vm-op missing 'op' key".into()))?;
match op_name {
"push" => {
let storage = instr_field_bool(instr, "storage")?;
let value = instr_field(instr, "value")?;
let state_value = checked_state_value(&decode_state_value(value, scope)?)?;
Ok(Op::Push {
storage,
value: state_value,
})
}
"idx" => {
let cached = instr_field_bool(instr, "cached")?;
let push_path = instr_field_bool(instr, "pushPath")?;
let path = instr_field(instr, "path")?;
let path_keys = decode_path(path, scope)?;
Ok(Op::Idx {
cached,
push_path,
path: StorageArray::from(path_keys),
})
}
"ins" => {
let cached = instr_field_bool(instr, "cached")?;
let n = instr_int(instr, "ins", "n", scope)?;
Ok(Op::Ins { cached, n })
}
"addi" => Ok(Op::Addi {
immediate: instr_int(instr, "addi", "immediate", scope)?,
}),
"subi" => Ok(Op::Subi {
immediate: instr_int(instr, "subi", "immediate", scope)?,
}),
"popeq" => {
let cached = instr_field_bool(instr, "cached")?;
Ok(Op::Popeq { cached, result: () })
}
"noop" => {
let n_raw =
decode_int_arg(instr_field(instr, "n").unwrap_or(&Value::Null), scope).unwrap_or(0);
let n_u32 = u32::try_from(n_raw).unwrap_or(0);
Ok(Op::Noop { n: n_u32 })
}
"pop" => Ok(Op::Pop),
"lt" => Ok(Op::Lt),
"eq" => Ok(Op::Eq),
"neg" => Ok(Op::Neg),
"size" => Ok(Op::Size),
"member" => Ok(Op::Member),
"rem" => {
let cached = instr_field_bool(instr, "cached")?;
Ok(Op::Rem { cached })
}
"dup" => Ok(Op::Dup {
n: instr_int(instr, "dup", "n", scope)?,
}),
"swap" => Ok(Op::Swap {
n: instr_int(instr, "swap", "n", scope)?,
}),
"concat" => {
let cached = instr_field_bool(instr, "cached")?;
let n = instr_int(instr, "concat", "n", scope)?;
Ok(Op::Concat { cached, n })
}
"ckpt" => Ok(Op::Ckpt),
"add" => Ok(Op::Add),
"sub" => Ok(Op::Sub),
"branch" => Ok(Op::Branch {
skip: instr_int(instr, "branch", "skip", scope)?,
}),
"jmp" => Ok(Op::Jmp {
skip: instr_int(instr, "jmp", "skip", scope)?,
}),
"and" => Ok(Op::And),
"or" => Ok(Op::Or),
"new" => Ok(Op::New),
"type" => Ok(Op::Type),
"log" => Ok(Op::Log),
"root" => Ok(Op::Root),
other => Err(IrDriverError::unimplemented(format!(
"vm op '{other}' not yet handled by the IR driver"
))),
}
}
fn instr_field<'a>(instr: &'a VmInstr, key: &str) -> Result<&'a Value> {
instr
.0
.get(key)
.ok_or_else(|| IrDriverError::InvalidIr(format!("vm-op missing field '{key}'")))
}
fn instr_int<T: TryFrom<u128>>(
instr: &VmInstr,
op: &str,
key: &str,
scope: &EvalScope<'_>,
) -> Result<T> {
let n = decode_int_arg(instr_field(instr, key)?, scope)?;
T::try_from(n).map_err(|_| {
IrDriverError::TypeMismatch(format!(
"{op}.{key} out of {}: {n}",
std::any::type_name::<T>()
))
})
}
fn instr_field_bool(instr: &VmInstr, key: &str) -> Result<bool> {
instr
.0
.get(key)
.and_then(Value::as_bool)
.ok_or_else(|| IrDriverError::InvalidIr(format!("vm-op field '{key}' not a bool")))
}
pub fn decode_int_arg(value: &Value, scope: &EvalScope<'_>) -> Result<u128> {
if value.is_number() || value.is_string() {
return json_as_u128(value);
}
let obj = value
.as_object()
.ok_or_else(|| IrDriverError::InvalidIr(format!("expected object int arg, got {value}")))?;
if let Some(vm_kind) = obj.get("vm").and_then(Value::as_str) {
match vm_kind {
"align" => {
let v = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
json_as_u128(v)
}
"value->int" => {
let inner = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("value->int missing 'value'".into()))?;
decode_int_arg(inner, scope)
}
"ref" => {
let inner = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("ref missing 'value'".into()))?;
let resolved = scope.resolve_ref_value(inner)?;
json_as_u128(&resolved)
}
"add" => {
let left = obj
.get("left")
.ok_or_else(|| IrDriverError::InvalidIr("vm:add missing 'left'".into()))?;
let right = obj
.get("right")
.ok_or_else(|| IrDriverError::InvalidIr("vm:add missing 'right'".into()))?;
let l = decode_int_arg(left, scope)?;
let r = decode_int_arg(right, scope)?;
l.checked_add(r).ok_or_else(|| {
IrDriverError::TypeMismatch(format!("vm:add overflow: {l} + {r} exceeds u128"))
})
}
"max-sizeof" => {
use moonproof_ledger::transient_crypto::fab::AlignmentExt;
let type_obj = obj.get("type").ok_or_else(|| {
IrDriverError::InvalidIr("vm:max-sizeof missing 'type'".into())
})?;
let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
crate::ir::interp::decode_value_as(type_obj).map_err(|e| {
IrDriverError::InvalidIr(format!(
"vm:max-sizeof.type not a TypeDescriptor: {e}"
))
})?;
let av = encode_default(&descriptor)?;
Ok(av.alignment.max_aligned_size() as u128)
}
other => Err(IrDriverError::unimplemented(format!(
"vm wrapper '{other}' in int arg position"
))),
}
} else {
Err(IrDriverError::InvalidIr(format!(
"object int arg has no 'vm' key: {value}"
)))
}
}
fn decode_path(value: &Value, scope: &EvalScope<'_>) -> Result<Vec<Key>> {
let arr = value
.as_array()
.ok_or_else(|| IrDriverError::InvalidIr(format!("path not an array: {value}")))?;
let mut out = Vec::with_capacity(arr.len());
for elt in arr {
out.push(decode_path_elt(elt, scope)?);
}
Ok(out)
}
fn encode_ref_with_type_value(type_obj: &Value, resolved: &Value) -> Result<AlignedValue> {
if let Some(obj) = type_obj.as_object() {
match obj.get("type-name").and_then(Value::as_str) {
Some("Bytes") => {
if let Some(len) = obj.get("length").and_then(Value::as_u64) {
if let Ok(len32) = u32::try_from(len) {
return encode_bytes(len32, resolved);
}
}
}
Some("Boolean") => return encode_bool(resolved),
Some("Field") => return encode_field(resolved),
Some("Uint") => {
if let Some(max_v) = obj.get("maxval") {
if let Ok(max_u128) = json_as_u128(max_v) {
let max_lit = moonproof_runtime_ir::ir::IntLit::from_u128(max_u128);
return encode_uint(&max_lit, resolved);
}
}
}
_ => {}
}
}
let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
crate::ir::interp::decode_value_as(type_obj)
.map_err(|e| IrDriverError::InvalidIr(format!("ref.type not a TypeDescriptor: {e}")))?;
encode_literal(&descriptor, resolved)
}
fn decode_path_elt(value: &Value, scope: &EvalScope<'_>) -> Result<Key> {
if value.as_str() == Some("@stack") {
return Ok(Key::Stack);
}
let obj = value
.as_object()
.ok_or_else(|| IrDriverError::InvalidIr(format!("path elt not an object: {value}")))?;
if let Some(vm_kind) = obj.get("vm").and_then(Value::as_str) {
match vm_kind {
"align" => {
let v = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
let bytes = obj.get("bytes").and_then(Value::as_u64).unwrap_or(1);
let n = json_as_u128(v)?;
let av = align_value_with_bytes(n, bytes)?;
Ok(Key::Value(checked_key(av)?))
}
"stack" => Ok(Key::Stack),
"ref" => {
let inner = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("path ref missing 'value'".into()))?;
let resolved = scope.resolve_ref_value(inner)?;
if let Some(type_obj) = obj.get("type") {
let av = encode_ref_with_type_value(type_obj, &resolved)?;
Ok(Key::Value(checked_key(av)?))
} else {
let n = json_as_u128(&resolved)?;
Ok(Key::Value(checked_key(align_value_with_bytes(n, 1)?)?))
}
}
other => Err(IrDriverError::unimplemented(format!(
"path elt vm wrapper '{other}'"
))),
}
} else {
Err(IrDriverError::InvalidIr(format!(
"path elt has no 'vm' key: {value}"
)))
}
}
pub fn decode_state_value(value: &Value, scope: &EvalScope<'_>) -> Result<StateValue<InMemoryDB>> {
let obj = value
.as_object()
.ok_or_else(|| IrDriverError::InvalidIr(format!("state-value not an object: {value}")))?;
if obj.get("vm").and_then(Value::as_str) != Some("state-value") {
return Err(IrDriverError::InvalidIr(format!(
"expected vm=state-value, got {value}"
)));
}
let kind = obj
.get("kind")
.and_then(Value::as_str)
.ok_or_else(|| IrDriverError::InvalidIr("state-value missing 'kind'".into()))?;
match kind {
"null" => Ok(StateValue::Null),
"cell" | "adt" => {
let inner = obj.get("value").ok_or_else(|| {
IrDriverError::InvalidIr(format!("state-value {kind} missing 'value'"))
})?;
let av = decode_aligned_value(inner, scope)?;
Ok(StateValue::Cell(Sp::new(av)))
}
"map" => {
let entries = obj.get("entries").and_then(Value::as_array);
if let Some(entries) = entries {
if !entries.is_empty() {
return Err(IrDriverError::unimplemented(
"state-value map with non-empty entries (no contract shape uses this yet)",
));
}
}
Ok(StateValue::Map(
moonproof_ledger::storage::storage::HashMap::new(),
))
}
"array" => {
let values = obj.get("values").and_then(Value::as_array).ok_or_else(|| {
IrDriverError::InvalidIr("state-value array missing 'values'".into())
})?;
let inner: Result<Vec<StateValue<InMemoryDB>>> = values
.iter()
.map(|v| decode_state_value(v, scope))
.collect();
Ok(StateValue::Array(StorageArray::from(inner?)))
}
"merkle-tree" => {
let depth_v = obj
.get("depth")
.ok_or_else(|| IrDriverError::InvalidIr("merkle-tree missing 'depth'".into()))?;
let depth_u128 = json_as_u128(depth_v)?;
let depth = u8::try_from(depth_u128).map_err(|_| {
IrDriverError::TypeMismatch(format!(
"merkle-tree depth out of u8 range: {depth_u128}"
))
})?;
let entries = obj.get("entries").and_then(Value::as_array);
if let Some(entries) = entries {
if !entries.is_empty() {
return Err(IrDriverError::unimplemented(
"state-value merkle-tree with pre-populated entries",
));
}
}
Ok(StateValue::BoundedMerkleTree(
moonproof_ledger::transient_crypto::merkle_tree::MerkleTree::<(), InMemoryDB>::blank(depth),
))
}
other => Err(IrDriverError::unimplemented(format!(
"state-value kind '{other}'"
))),
}
}
fn decode_aligned_value(value: &Value, scope: &EvalScope<'_>) -> Result<AlignedValue> {
let obj = value
.as_object()
.ok_or_else(|| IrDriverError::InvalidIr(format!("aligned-value not an object: {value}")))?;
let kind = obj
.get("vm")
.and_then(Value::as_str)
.ok_or_else(|| IrDriverError::InvalidIr("aligned-value missing 'vm'".into()))?;
match kind {
"align" => {
let v = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
let bytes = obj.get("bytes").and_then(Value::as_u64).unwrap_or(1);
let n = json_as_u128(v)?;
align_value_with_bytes(n, bytes)
}
"ref" => {
let type_obj = obj.get("type").ok_or_else(|| {
IrDriverError::InvalidIr("aligned-value ref missing 'type'".into())
})?;
let inner = obj.get("value").ok_or_else(|| {
IrDriverError::InvalidIr("aligned-value ref missing 'value'".into())
})?;
let resolved = scope.resolve_ref_value(inner)?;
encode_ref_with_type_value(type_obj, &resolved)
}
"null" => {
let type_obj = obj.get("type").ok_or_else(|| {
IrDriverError::InvalidIr("aligned-value null missing 'type'".into())
})?;
let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
crate::ir::interp::decode_value_as(type_obj).map_err(|e| {
IrDriverError::InvalidIr(format!("null.type not a TypeDescriptor: {e}"))
})?;
encode_default(&descriptor)
}
"aligned-concat" => {
let values = obj.get("values").and_then(Value::as_array).ok_or_else(|| {
IrDriverError::InvalidIr("aligned-concat missing 'values' array".into())
})?;
let avs: Result<Vec<AlignedValue>> = values
.iter()
.map(|v| decode_aligned_value(v, scope))
.collect();
let avs = avs?;
Ok(AlignedValue::concat(avs.iter()))
}
"coin-commit" => {
let coin_inner = obj
.get("coin")
.ok_or_else(|| IrDriverError::InvalidIr("coin-commit missing 'coin'".into()))?;
let recipient_inner = obj.get("recipient").ok_or_else(|| {
IrDriverError::InvalidIr("coin-commit missing 'recipient'".into())
})?;
let coin_av = decode_aligned_value(coin_inner, scope)?;
let recipient_av = decode_aligned_value(recipient_inner, scope)?;
coin_commit_aligned(&coin_av, &recipient_av)
}
"leaf-hash" => {
let inner = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("leaf-hash missing 'value'".into()))?;
let inner_av = decode_aligned_value(inner, scope)?;
Ok(leaf_hash_aligned(inner_av))
}
other => Err(IrDriverError::unimplemented(format!(
"aligned-value vm wrapper '{other}'"
))),
}
}
fn coin_commit_aligned(
coin_av: &AlignedValue,
recipient_av: &AlignedValue,
) -> Result<AlignedValue> {
let coin: moonproof_ledger::coin_structure::coin::Info =
moonproof_ledger::coin_structure::coin::Info::try_from(&**AsRef::<
moonproof_ledger::base_crypto::fab::Value,
>::as_ref(coin_av))
.map_err(|e| IrDriverError::TypeMismatch(format!("coin-commit coin → CoinInfo: {e:?}")))?;
let recipient: moonproof_ledger::coin_structure::transfer::Recipient =
moonproof_ledger::coin_structure::transfer::Recipient::try_from(&**AsRef::<
moonproof_ledger::base_crypto::fab::Value,
>::as_ref(
recipient_av
))
.map_err(|e| {
IrDriverError::TypeMismatch(format!("coin-commit recipient → Recipient: {e:?}"))
})?;
Ok(AlignedValue::from(coin.commitment(&recipient)))
}
fn leaf_hash_aligned(inner_av: AlignedValue) -> AlignedValue {
let hash = moonproof_ledger::transient_crypto::merkle_tree::leaf_hash(
&moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue(inner_av),
);
let moonproof_ledger::base_crypto::hash::HashOutput(bytes) = hash;
AlignedValue::from(bytes)
}
fn checked_cell_value(av: AlignedValue) -> Result<AlignedValueChecked> {
AlignedValueChecked::try_from(av).map_err(|()| {
IrDriverError::InvalidIr(
"push value is not canonical: a field atom is not below the field modulus, \
or a Merkle tree is not blank"
.into(),
)
})
}
pub(crate) fn checked_state_value(
value: &StateValue<InMemoryDB>,
) -> Result<StateValue<InMemoryDB, AlignedValueChecked>> {
value.try_into_checked().map_err(|()| {
IrDriverError::InvalidIr(
"push value is not canonical: a field atom is not below the field modulus, \
or a Merkle tree is not blank"
.into(),
)
})
}
pub(crate) fn checked_key(av: AlignedValue) -> Result<AlignedValueChecked> {
AlignedValueChecked::try_from(av).map_err(|()| {
IrDriverError::InvalidIr(
"path key has a field atom that is not below the field modulus".into(),
)
})
}
fn align_value_with_bytes(value: u128, bytes: u64) -> Result<AlignedValue> {
let too_wide = |_| {
IrDriverError::TypeMismatch(format!("align value {value} does not fit in {bytes} bytes"))
};
match bytes {
1 => Ok(AlignedValue::from(u8::try_from(value).map_err(too_wide)?)),
2 => Ok(AlignedValue::from(u16::try_from(value).map_err(too_wide)?)),
4 => Ok(AlignedValue::from(u32::try_from(value).map_err(too_wide)?)),
8 => Ok(AlignedValue::from(u64::try_from(value).map_err(too_wide)?)),
16 => Ok(AlignedValue::from(value)),
other => Err(IrDriverError::unimplemented(format!(
"align width {other} bytes"
))),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryFlags {
pub reads_context: bool,
pub touches_effects: bool,
pub mutates_state: bool,
}
impl QueryFlags {
pub const ALL: Self = Self {
reads_context: true,
touches_effects: true,
mutates_state: true,
};
pub const READ_ONLY_STATE: Self = Self {
reads_context: false,
touches_effects: false,
mutates_state: false,
};
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self {
reads_context: self.reads_context || other.reads_context,
touches_effects: self.touches_effects || other.touches_effects,
mutates_state: self.mutates_state || other.mutates_state,
}
}
}
struct StackTracker {
height: usize,
flags: QueryFlags,
}
impl StackTracker {
fn new() -> Self {
Self {
height: 3,
flags: QueryFlags::READ_ONLY_STATE,
}
}
fn note_read(&mut self, idx: usize) {
if idx == 0 {
self.flags.reads_context = true;
} else if idx == 1 {
self.flags.touches_effects = true;
}
}
fn note_write(&mut self, idx: usize) {
if idx == 0 {
self.flags.reads_context = true;
}
if idx <= 1 {
self.flags.touches_effects = true;
}
if idx <= 2 {
self.flags.mutates_state = true;
}
}
fn pop(&mut self, n: usize) -> bool {
if self.height < n {
self.flags = QueryFlags::ALL;
return false;
}
if n > 0 {
let lowest = self.height - n;
self.note_write(lowest);
self.height = lowest;
}
true
}
fn step_op(&mut self, op: &Op<ResultModeGather, InMemoryDB>) -> bool {
match op {
Op::Noop { .. } => true,
Op::Ckpt => {
self.flags.touches_effects = true;
true
}
Op::Push { .. } => {
self.height += 1;
true
}
Op::Pop | Op::Popeq { .. } | Op::Log => self.pop(1),
Op::Type
| Op::Size
| Op::New
| Op::Neg
| Op::Root
| Op::Addi { .. }
| Op::Subi { .. } => {
if !self.pop(1) {
return false;
}
self.height += 1;
true
}
Op::Lt
| Op::Eq
| Op::And
| Op::Or
| Op::Add
| Op::Sub
| Op::Concat { .. }
| Op::Member => {
if !self.pop(2) {
return false;
}
self.height += 1;
true
}
Op::Rem { .. } => {
self.flags.mutates_state = true;
if !self.pop(2) {
return false;
}
self.height += 1;
true
}
Op::Dup { n } => {
let depth = usize::from(*n);
if self.height <= depth {
self.flags = QueryFlags::ALL;
return false;
}
let idx = self.height - 1 - depth;
self.note_read(idx);
self.height += 1;
true
}
Op::Swap { n } => {
let depth = usize::from(*n);
if self.height < depth + 2 {
self.flags = QueryFlags::ALL;
return false;
}
let top = self.height - 1;
let other = self.height - 2 - depth;
self.note_write(top);
self.note_write(other);
true
}
Op::Idx {
push_path, path, ..
} => {
let stack_keys = path.iter().filter(|k| **k == Key::Stack).count();
if !self.pop(stack_keys + 1) {
return false;
}
if *push_path {
self.height += 2 * path.len();
}
self.height += 1;
true
}
Op::Ins { n, .. } => {
self.flags.mutates_state = true;
let popped = usize::from(*n) * 2 + 1;
if !self.pop(popped) {
return false;
}
self.height += 1;
true
}
Op::Branch { .. } | Op::Jmp { .. } | _ => {
self.flags = QueryFlags::ALL;
false
}
}
}
fn step_compiled_op(&mut self, op: &CompiledOp) -> bool {
match op {
CompiledOp::Static(raw) => self.step_op(raw),
CompiledOp::Push { .. } => {
self.height += 1;
true
}
CompiledOp::Idx {
push_path, path, ..
} => {
let stack_keys = path
.iter()
.filter(|k| matches!(k, CompiledPathKey::Static(Key::Stack)))
.count();
if !self.pop(stack_keys + 1) {
return false;
}
if *push_path {
self.height += 2 * path.len();
}
self.height += 1;
true
}
CompiledOp::Ins { n, .. } => {
self.flags.mutates_state = true;
let CompiledIntArg::Static(val) = n else {
self.flags = QueryFlags::ALL;
return false;
};
let Ok(count) = usize::try_from(*val) else {
self.flags = QueryFlags::ALL;
return false;
};
let Some(popped) = count.checked_mul(2).and_then(|v| v.checked_add(1)) else {
self.flags = QueryFlags::ALL;
return false;
};
if !self.pop(popped) {
return false;
}
self.height += 1;
true
}
CompiledOp::Addi { .. } | CompiledOp::Subi { .. } => {
if !self.pop(1) {
return false;
}
self.height += 1;
true
}
CompiledOp::Noop { .. } => true,
CompiledOp::Concat { .. } => {
if !self.pop(2) {
return false;
}
self.height += 1;
true
}
CompiledOp::Dup { n } => {
let CompiledIntArg::Static(val) = n else {
self.flags = QueryFlags::ALL;
return false;
};
let Ok(depth) = usize::try_from(*val) else {
self.flags = QueryFlags::ALL;
return false;
};
if self.height <= depth {
self.flags = QueryFlags::ALL;
return false;
}
let idx = self.height - 1 - depth;
self.note_read(idx);
self.height += 1;
true
}
CompiledOp::Swap { n } => {
let CompiledIntArg::Static(val) = n else {
self.flags = QueryFlags::ALL;
return false;
};
let Ok(depth) = usize::try_from(*val) else {
self.flags = QueryFlags::ALL;
return false;
};
if self.height < depth + 2 {
self.flags = QueryFlags::ALL;
return false;
}
let top = self.height - 1;
let other = self.height - 2 - depth;
self.note_write(top);
self.note_write(other);
true
}
CompiledOp::Branch { .. } | CompiledOp::Jmp { .. } => {
self.flags = QueryFlags::ALL;
false
}
}
}
}
#[must_use]
pub fn analyze_ops(ops: &[Op<ResultModeGather, InMemoryDB>]) -> QueryFlags {
let mut tracker = StackTracker::new();
for op in ops {
if !tracker.step_op(op) {
break;
}
}
tracker.flags
}
#[must_use]
pub fn analyze_compiled_ops(ops: &[CompiledOp]) -> QueryFlags {
let mut tracker = StackTracker::new();
for op in ops {
if !tracker.step_compiled_op(op) {
break;
}
}
tracker.flags
}
#[derive(Debug, Clone)]
pub struct CompiledLedgerQuery {
pub flags: QueryFlags,
pub body: CompiledQueryBody,
}
#[derive(Debug, Clone)]
pub enum CompiledQueryBody {
Static(Vec<Op<ResultModeGather, InMemoryDB>>),
Dynamic(Vec<CompiledOp>),
}
impl CompiledLedgerQuery {
pub fn materialize_dynamic(
ops: &[CompiledOp],
scope: &EvalScope<'_>,
) -> Result<Vec<Op<ResultModeGather, InMemoryDB>>> {
let mut out = Vec::with_capacity(ops.len());
for op in ops {
out.push(op.materialize(scope)?);
}
Ok(out)
}
}
#[derive(Debug, Clone)]
pub enum CompiledOp {
Static(Op<ResultModeGather, InMemoryDB>),
Push {
storage: bool,
value: CompiledStateValue,
},
Idx {
cached: bool,
push_path: bool,
path: Vec<CompiledPathKey>,
},
Ins {
cached: bool,
n: CompiledIntArg,
},
Addi {
immediate: CompiledIntArg,
},
Subi {
immediate: CompiledIntArg,
},
Noop {
n: CompiledIntArg,
},
Dup {
n: CompiledIntArg,
},
Swap {
n: CompiledIntArg,
},
Concat {
cached: bool,
n: CompiledIntArg,
},
Branch {
skip: CompiledIntArg,
},
Jmp {
skip: CompiledIntArg,
},
}
#[derive(Debug, Clone)]
pub enum CompiledStateValue {
Static(StateValue<InMemoryDB, AlignedValueChecked>),
Cell(CompiledAlignedValue),
Array(Vec<CompiledStateValue>),
}
#[derive(Debug, Clone)]
pub enum CompiledAlignedValue {
Static(AlignedValue),
Ref {
expr: CompiledRefExpr,
plan: FabPlan,
},
AlignedConcat(Vec<CompiledAlignedValue>),
CoinCommit {
coin: Box<CompiledAlignedValue>,
recipient: Box<CompiledAlignedValue>,
},
LeafHash(Box<CompiledAlignedValue>),
}
#[derive(Debug, Clone)]
pub enum CompiledPathKey {
Static(Key),
DynamicRef {
expr: CompiledRefExpr,
plan: Option<FabPlan>,
},
}
#[derive(Debug, Clone)]
pub enum CompiledIntArg {
Static(u128),
Ref(CompiledRefExpr),
Add(Box<CompiledIntArg>, Box<CompiledIntArg>),
}
#[derive(Debug, Clone)]
pub enum CompiledRefExpr {
Var(String),
Literal(Value),
Expr(Box<moonproof_runtime_ir::ir::Expression>),
}
#[must_use]
pub fn compile_vm_ops(vm_ops: &[VmInstr]) -> Option<CompiledLedgerQuery> {
let mut compiled = Vec::with_capacity(vm_ops.len());
let mut all_static = true;
for instr in vm_ops {
let op = compile_op(instr).ok()?;
if !matches!(op, CompiledOp::Static(_)) {
all_static = false;
}
compiled.push(op);
}
if all_static {
let static_ops: Vec<Op<ResultModeGather, InMemoryDB>> = compiled
.into_iter()
.map(|op| match op {
CompiledOp::Static(raw) => raw,
_ => unreachable!("all_static verified"),
})
.collect();
let flags = analyze_ops(&static_ops);
Some(CompiledLedgerQuery {
flags,
body: CompiledQueryBody::Static(static_ops),
})
} else {
let flags = analyze_compiled_ops(&compiled);
Some(CompiledLedgerQuery {
flags,
body: CompiledQueryBody::Dynamic(compiled),
})
}
}
fn narrow_int<T: TryFrom<u128>>(op: &str, key: &str, n: u128) -> Result<T> {
T::try_from(n).map_err(|_| {
IrDriverError::TypeMismatch(format!(
"{op}.{key} out of {}: {n}",
std::any::type_name::<T>()
))
})
}
fn compile_int_op(op_name: &str, instr: &VmInstr) -> Result<CompiledOp> {
match op_name {
"ins" => {
let cached = instr_field_bool(instr, "cached")?;
match compile_int_arg(instr_field(instr, "n")?)? {
CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Ins {
cached,
n: narrow_int("ins", "n", n)?,
})),
dynamic => Ok(CompiledOp::Ins { cached, n: dynamic }),
}
}
"addi" => match compile_int_arg(instr_field(instr, "immediate")?)? {
CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Addi {
immediate: narrow_int("addi", "immediate", n)?,
})),
dynamic => Ok(CompiledOp::Addi { immediate: dynamic }),
},
"subi" => match compile_int_arg(instr_field(instr, "immediate")?)? {
CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Subi {
immediate: narrow_int("subi", "immediate", n)?,
})),
dynamic => Ok(CompiledOp::Subi { immediate: dynamic }),
},
"noop" => match instr.0.get("n") {
None | Some(Value::Null) => Ok(CompiledOp::Static(Op::Noop { n: 0 })),
Some(v) => match compile_int_arg(v) {
Ok(CompiledIntArg::Static(n)) => Ok(CompiledOp::Static(Op::Noop {
n: u32::try_from(n).unwrap_or(0),
})),
Ok(dynamic) => Ok(CompiledOp::Noop { n: dynamic }),
Err(_) => Ok(CompiledOp::Static(Op::Noop { n: 0 })),
},
},
"dup" => match compile_int_arg(instr_field(instr, "n")?)? {
CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Dup {
n: narrow_int("dup", "n", n)?,
})),
dynamic => Ok(CompiledOp::Dup { n: dynamic }),
},
"swap" => match compile_int_arg(instr_field(instr, "n")?)? {
CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Swap {
n: narrow_int("swap", "n", n)?,
})),
dynamic => Ok(CompiledOp::Swap { n: dynamic }),
},
"concat" => {
let cached = instr_field_bool(instr, "cached")?;
match compile_int_arg(instr_field(instr, "n")?)? {
CompiledIntArg::Static(n) => Ok(CompiledOp::Static(Op::Concat {
cached,
n: narrow_int("concat", "n", n)?,
})),
dynamic => Ok(CompiledOp::Concat { cached, n: dynamic }),
}
}
"branch" => match compile_int_arg(instr_field(instr, "skip")?)? {
CompiledIntArg::Static(skip) => Ok(CompiledOp::Static(Op::Branch {
skip: narrow_int("branch", "skip", skip)?,
})),
dynamic => Ok(CompiledOp::Branch { skip: dynamic }),
},
"jmp" => match compile_int_arg(instr_field(instr, "skip")?)? {
CompiledIntArg::Static(skip) => Ok(CompiledOp::Static(Op::Jmp {
skip: narrow_int("jmp", "skip", skip)?,
})),
dynamic => Ok(CompiledOp::Jmp { skip: dynamic }),
},
other => Err(IrDriverError::unimplemented(format!(
"vm op '{other}' not yet handled by the IR driver"
))),
}
}
fn compile_op(instr: &VmInstr) -> Result<CompiledOp> {
let op_name = instr
.op()
.ok_or_else(|| IrDriverError::InvalidIr("vm-op missing 'op' key".into()))?;
match op_name {
"push" => {
let storage = instr_field_bool(instr, "storage")?;
let value = compile_state_value(instr_field(instr, "value")?)?;
match value {
CompiledStateValue::Static(sv) => {
Ok(CompiledOp::Static(Op::Push { storage, value: sv }))
}
dynamic => Ok(CompiledOp::Push {
storage,
value: dynamic,
}),
}
}
"idx" => {
let cached = instr_field_bool(instr, "cached")?;
let push_path = instr_field_bool(instr, "pushPath")?;
let path = compile_path(instr_field(instr, "path")?)?;
if path.iter().all(|k| matches!(k, CompiledPathKey::Static(_))) {
let keys: Vec<Key> = path
.into_iter()
.map(|k| match k {
CompiledPathKey::Static(key) => key,
CompiledPathKey::DynamicRef { .. } => unreachable!(),
})
.collect();
Ok(CompiledOp::Static(Op::Idx {
cached,
push_path,
path: StorageArray::from(keys),
}))
} else {
Ok(CompiledOp::Idx {
cached,
push_path,
path,
})
}
}
"ins" | "addi" | "subi" | "noop" | "dup" | "swap" | "concat" | "branch" | "jmp" => {
compile_int_op(op_name, instr)
}
"popeq" => Ok(CompiledOp::Static(Op::Popeq {
cached: instr_field_bool(instr, "cached")?,
result: (),
})),
"rem" => Ok(CompiledOp::Static(Op::Rem {
cached: instr_field_bool(instr, "cached")?,
})),
"pop" => Ok(CompiledOp::Static(Op::Pop)),
"lt" => Ok(CompiledOp::Static(Op::Lt)),
"eq" => Ok(CompiledOp::Static(Op::Eq)),
"neg" => Ok(CompiledOp::Static(Op::Neg)),
"size" => Ok(CompiledOp::Static(Op::Size)),
"member" => Ok(CompiledOp::Static(Op::Member)),
"ckpt" => Ok(CompiledOp::Static(Op::Ckpt)),
"add" => Ok(CompiledOp::Static(Op::Add)),
"sub" => Ok(CompiledOp::Static(Op::Sub)),
"and" => Ok(CompiledOp::Static(Op::And)),
"or" => Ok(CompiledOp::Static(Op::Or)),
"new" => Ok(CompiledOp::Static(Op::New)),
"type" => Ok(CompiledOp::Static(Op::Type)),
"log" => Ok(CompiledOp::Static(Op::Log)),
"root" => Ok(CompiledOp::Static(Op::Root)),
other => Err(IrDriverError::unimplemented(format!(
"vm op '{other}' not yet handled by the IR driver"
))),
}
}
fn compile_ref_expr(inner: &Value) -> Result<CompiledRefExpr> {
if let Some(obj) = inner.as_object() {
match obj.get("expr").and_then(Value::as_str) {
Some("var") => {
if let Some(name) = obj.get("name").and_then(Value::as_str) {
return Ok(CompiledRefExpr::Var(name.to_owned()));
}
}
Some("literal") => {
if let Some(v) = obj.get("value") {
return Ok(CompiledRefExpr::Literal(v.clone()));
}
}
_ => {}
}
}
let expr: moonproof_runtime_ir::ir::Expression = crate::ir::interp::decode_value_as(inner)
.map_err(|e| IrDriverError::InvalidIr(format!("ref.value not an Expression: {e}")))?;
match expr {
moonproof_runtime_ir::ir::Expression::Var { name } => Ok(CompiledRefExpr::Var(name)),
moonproof_runtime_ir::ir::Expression::Literal { value } => {
Ok(CompiledRefExpr::Literal(value))
}
moonproof_runtime_ir::ir::Expression::EnumRef { of_type, variant } => match of_type {
moonproof_runtime_ir::ir::TypeDescriptor::Enum { elements, name } => {
if !elements.iter().any(|v| v == &variant) {
return Err(IrDriverError::TypeMismatch(format!(
"enum {name} has no variant '{variant}' (variants: {elements:?})"
)));
}
Ok(CompiledRefExpr::Literal(Value::String(variant)))
}
other => Err(IrDriverError::TypeMismatch(format!(
"enum-ref descriptor not an Enum: {other:?}"
))),
},
moonproof_runtime_ir::ir::Expression::Default { of_type } => {
let av = encode_default(&of_type)?;
let v = super::descriptor::decode_aligned_value_full(&of_type, &av)?;
Ok(CompiledRefExpr::Literal(v))
}
other => Ok(CompiledRefExpr::Expr(Box::new(other))),
}
}
fn compile_type_plan(type_obj: &Value) -> Result<FabPlan> {
let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
crate::ir::interp::decode_value_as(type_obj)
.map_err(|e| IrDriverError::InvalidIr(format!("ref.type not a TypeDescriptor: {e}")))?;
FabPlan::compile(&descriptor).ok_or_else(|| {
IrDriverError::unimplemented(format!("FabPlan unsupported for descriptor {descriptor:?}"))
})
}
fn compile_int_arg(value: &Value) -> Result<CompiledIntArg> {
if value.is_number() || value.is_string() {
return Ok(CompiledIntArg::Static(json_as_u128(value)?));
}
let obj = value
.as_object()
.ok_or_else(|| IrDriverError::InvalidIr(format!("expected object int arg, got {value}")))?;
let vm_kind = obj.get("vm").and_then(Value::as_str).ok_or_else(|| {
IrDriverError::InvalidIr(format!("object int arg has no 'vm' key: {value}"))
})?;
match vm_kind {
"align" => {
let v = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
Ok(CompiledIntArg::Static(json_as_u128(v)?))
}
"value->int" => {
let inner = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("value->int missing 'value'".into()))?;
compile_int_arg(inner)
}
"ref" => {
let inner = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("ref missing 'value'".into()))?;
match compile_ref_expr(inner)? {
CompiledRefExpr::Literal(v) => Ok(CompiledIntArg::Static(json_as_u128(&v)?)),
dynamic => Ok(CompiledIntArg::Ref(dynamic)),
}
}
"add" => {
let left = obj
.get("left")
.ok_or_else(|| IrDriverError::InvalidIr("vm:add missing 'left'".into()))?;
let right = obj
.get("right")
.ok_or_else(|| IrDriverError::InvalidIr("vm:add missing 'right'".into()))?;
let l = compile_int_arg(left)?;
let r = compile_int_arg(right)?;
match (l, r) {
(CompiledIntArg::Static(lv), CompiledIntArg::Static(rv)) => {
let sum = lv.checked_add(rv).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"vm:add overflow: {lv} + {rv} exceeds u128"
))
})?;
Ok(CompiledIntArg::Static(sum))
}
(l, r) => Ok(CompiledIntArg::Add(Box::new(l), Box::new(r))),
}
}
"max-sizeof" => {
let type_obj = obj
.get("type")
.ok_or_else(|| IrDriverError::InvalidIr("vm:max-sizeof missing 'type'".into()))?;
let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
crate::ir::interp::decode_value_as(type_obj).map_err(|e| {
IrDriverError::InvalidIr(format!(
"vm:max-sizeof.type not a TypeDescriptor: {e}"
))
})?;
let size = if let Some(plan) = FabPlan::compile(&descriptor) {
plan.max_aligned_size()
} else {
use moonproof_ledger::transient_crypto::fab::AlignmentExt;
encode_default(&descriptor)?.alignment.max_aligned_size()
};
Ok(CompiledIntArg::Static(size as u128))
}
other => Err(IrDriverError::unimplemented(format!(
"vm wrapper '{other}' in int arg position"
))),
}
}
fn compile_path(value: &Value) -> Result<Vec<CompiledPathKey>> {
let arr = value
.as_array()
.ok_or_else(|| IrDriverError::InvalidIr(format!("path not an array: {value}")))?;
let mut out = Vec::with_capacity(arr.len());
for elt in arr {
out.push(compile_path_elt(elt)?);
}
Ok(out)
}
fn compile_path_elt(value: &Value) -> Result<CompiledPathKey> {
if value.as_str() == Some("@stack") {
return Ok(CompiledPathKey::Static(Key::Stack));
}
let obj = value
.as_object()
.ok_or_else(|| IrDriverError::InvalidIr(format!("path elt not an object: {value}")))?;
let vm_kind = obj
.get("vm")
.and_then(Value::as_str)
.ok_or_else(|| IrDriverError::InvalidIr(format!("path elt has no 'vm' key: {value}")))?;
match vm_kind {
"align" => {
let v = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
let bytes = obj.get("bytes").and_then(Value::as_u64).unwrap_or(1);
let n = json_as_u128(v)?;
let av = align_value_with_bytes(n, bytes)?;
Ok(CompiledPathKey::Static(Key::Value(checked_key(av)?)))
}
"stack" => Ok(CompiledPathKey::Static(Key::Stack)),
"ref" => {
let inner = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("path ref missing 'value'".into()))?;
let expr = compile_ref_expr(inner)?;
let plan = obj.get("type").map(compile_type_plan).transpose()?;
if let CompiledRefExpr::Literal(val) = expr {
let av = if let Some(ref p) = plan {
p.encode(&val)?
} else {
align_value_with_bytes(json_as_u128(&val)?, 1)?
};
return Ok(CompiledPathKey::Static(Key::Value(checked_key(av)?)));
}
Ok(CompiledPathKey::DynamicRef { expr, plan })
}
other => Err(IrDriverError::unimplemented(format!(
"path elt vm wrapper '{other}'"
))),
}
}
fn compile_state_value(value: &Value) -> Result<CompiledStateValue> {
let obj = value
.as_object()
.ok_or_else(|| IrDriverError::InvalidIr(format!("state-value not an object: {value}")))?;
if obj.get("vm").and_then(Value::as_str) != Some("state-value") {
return Err(IrDriverError::InvalidIr(format!(
"expected vm=state-value, got {value}"
)));
}
let kind = obj
.get("kind")
.and_then(Value::as_str)
.ok_or_else(|| IrDriverError::InvalidIr("state-value missing 'kind'".into()))?;
match kind {
"null" => Ok(CompiledStateValue::Static(checked_state_value(
&StateValue::Null,
)?)),
"cell" | "adt" => {
let inner = obj.get("value").ok_or_else(|| {
IrDriverError::InvalidIr(format!("state-value {kind} missing 'value'"))
})?;
match compile_aligned_value(inner)? {
CompiledAlignedValue::Static(av) => {
let checked = checked_cell_value(av)?;
Ok(CompiledStateValue::Static(StateValue::Cell(Sp::new(
checked,
))))
}
dynamic => Ok(CompiledStateValue::Cell(dynamic)),
}
}
"map" => {
if let Some(entries) = obj.get("entries").and_then(Value::as_array) {
if !entries.is_empty() {
return Err(IrDriverError::unimplemented(
"state-value map with non-empty entries (no contract shape uses this yet)",
));
}
}
Ok(CompiledStateValue::Static(checked_state_value(
&StateValue::Map(moonproof_ledger::storage::storage::HashMap::new()),
)?))
}
"array" => {
let values = obj.get("values").and_then(Value::as_array).ok_or_else(|| {
IrDriverError::InvalidIr("state-value array missing 'values'".into())
})?;
let mut items = Vec::with_capacity(values.len());
let mut all_static = true;
for v in values {
let compiled = compile_state_value(v)?;
if !matches!(compiled, CompiledStateValue::Static(_)) {
all_static = false;
}
items.push(compiled);
}
if all_static {
let static_items: Vec<StateValue<InMemoryDB, AlignedValueChecked>> = items
.into_iter()
.map(|c| match c {
CompiledStateValue::Static(sv) => sv,
_ => unreachable!(),
})
.collect();
Ok(CompiledStateValue::Static(StateValue::Array(
StorageArray::from(static_items),
)))
} else {
Ok(CompiledStateValue::Array(items))
}
}
"merkle-tree" => {
let depth_v = obj
.get("depth")
.ok_or_else(|| IrDriverError::InvalidIr("merkle-tree missing 'depth'".into()))?;
let depth_u128 = json_as_u128(depth_v)?;
let depth = u8::try_from(depth_u128).map_err(|_| {
IrDriverError::TypeMismatch(format!(
"merkle-tree depth out of u8 range: {depth_u128}"
))
})?;
if let Some(entries) = obj.get("entries").and_then(Value::as_array) {
if !entries.is_empty() {
return Err(IrDriverError::unimplemented(
"state-value merkle-tree with pre-populated entries",
));
}
}
let tree = StateValue::BoundedMerkleTree(
moonproof_ledger::transient_crypto::merkle_tree::MerkleTree::<(), InMemoryDB>::blank(
depth,
),
);
Ok(CompiledStateValue::Static(checked_state_value(&tree)?))
}
other => Err(IrDriverError::unimplemented(format!(
"state-value kind '{other}'"
))),
}
}
fn compile_aligned_concat(values: &[Value]) -> Result<CompiledAlignedValue> {
let mut items = Vec::with_capacity(values.len());
let mut all_static = true;
for v in values {
let c = compile_aligned_value(v)?;
if !matches!(c, CompiledAlignedValue::Static(_)) {
all_static = false;
}
items.push(c);
}
if all_static {
let avs: Vec<AlignedValue> = items
.into_iter()
.map(|c| match c {
CompiledAlignedValue::Static(av) => av,
_ => unreachable!(),
})
.collect();
Ok(CompiledAlignedValue::Static(AlignedValue::concat(
avs.iter(),
)))
} else {
Ok(CompiledAlignedValue::AlignedConcat(items))
}
}
fn compile_aligned_value(value: &Value) -> Result<CompiledAlignedValue> {
let obj = value
.as_object()
.ok_or_else(|| IrDriverError::InvalidIr(format!("aligned-value not an object: {value}")))?;
let kind = obj
.get("vm")
.and_then(Value::as_str)
.ok_or_else(|| IrDriverError::InvalidIr("aligned-value missing 'vm'".into()))?;
match kind {
"align" => {
let v = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("align missing 'value'".into()))?;
let bytes = obj.get("bytes").and_then(Value::as_u64).unwrap_or(1);
let n = json_as_u128(v)?;
Ok(CompiledAlignedValue::Static(align_value_with_bytes(
n, bytes,
)?))
}
"ref" => {
let type_obj = obj.get("type").ok_or_else(|| {
IrDriverError::InvalidIr("aligned-value ref missing 'type'".into())
})?;
let inner = obj.get("value").ok_or_else(|| {
IrDriverError::InvalidIr("aligned-value ref missing 'value'".into())
})?;
let plan = compile_type_plan(type_obj)?;
let expr = compile_ref_expr(inner)?;
if let CompiledRefExpr::Literal(val) = expr {
return Ok(CompiledAlignedValue::Static(plan.encode(&val)?));
}
Ok(CompiledAlignedValue::Ref { expr, plan })
}
"null" => {
let type_obj = obj.get("type").ok_or_else(|| {
IrDriverError::InvalidIr("aligned-value null missing 'type'".into())
})?;
let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
crate::ir::interp::decode_value_as(type_obj).map_err(|e| {
IrDriverError::InvalidIr(format!("null.type not a TypeDescriptor: {e}"))
})?;
Ok(CompiledAlignedValue::Static(encode_default(&descriptor)?))
}
"aligned-concat" => {
let values = obj.get("values").and_then(Value::as_array).ok_or_else(|| {
IrDriverError::InvalidIr("aligned-concat missing 'values' array".into())
})?;
compile_aligned_concat(values)
}
"coin-commit" => {
let coin_inner = obj
.get("coin")
.ok_or_else(|| IrDriverError::InvalidIr("coin-commit missing 'coin'".into()))?;
let recipient_inner = obj.get("recipient").ok_or_else(|| {
IrDriverError::InvalidIr("coin-commit missing 'recipient'".into())
})?;
let coin = compile_aligned_value(coin_inner)?;
let recipient = compile_aligned_value(recipient_inner)?;
match (coin, recipient) {
(CompiledAlignedValue::Static(c), CompiledAlignedValue::Static(r)) => {
Ok(CompiledAlignedValue::Static(coin_commit_aligned(&c, &r)?))
}
(coin, recipient) => Ok(CompiledAlignedValue::CoinCommit {
coin: Box::new(coin),
recipient: Box::new(recipient),
}),
}
}
"leaf-hash" => {
let inner = obj
.get("value")
.ok_or_else(|| IrDriverError::InvalidIr("leaf-hash missing 'value'".into()))?;
match compile_aligned_value(inner)? {
CompiledAlignedValue::Static(av) => {
Ok(CompiledAlignedValue::Static(leaf_hash_aligned(av)))
}
dynamic => Ok(CompiledAlignedValue::LeafHash(Box::new(dynamic))),
}
}
other => Err(IrDriverError::unimplemented(format!(
"aligned-value vm wrapper '{other}'"
))),
}
}
impl CompiledRefExpr {
fn resolve<'s>(&'s self, scope: &'s EvalScope<'_>) -> Result<Cow<'s, Value>> {
match self {
Self::Var(name) => scope.lookup_var(name),
Self::Literal(v) => Ok(Cow::Borrowed(v)),
Self::Expr(expr) => scope.resolve_expr(expr).map(Cow::Owned),
}
}
}
impl CompiledIntArg {
fn eval(&self, scope: &EvalScope<'_>) -> Result<u128> {
match self {
Self::Static(n) => Ok(*n),
Self::Ref(expr) => {
let resolved = expr.resolve(scope)?;
json_as_u128(&resolved)
}
Self::Add(left, right) => {
let l = left.eval(scope)?;
let r = right.eval(scope)?;
l.checked_add(r).ok_or_else(|| {
IrDriverError::TypeMismatch(format!("vm:add overflow: {l} + {r} exceeds u128"))
})
}
}
}
}
impl CompiledAlignedValue {
fn materialize(&self, scope: &EvalScope<'_>) -> Result<AlignedValue> {
match self {
Self::Static(av) => Ok(av.clone()),
Self::Ref { expr, plan } => {
let resolved = expr.resolve(scope)?;
plan.encode(&resolved)
}
Self::AlignedConcat(items) => {
let mut avs = Vec::with_capacity(items.len());
for item in items {
avs.push(item.materialize(scope)?);
}
Ok(AlignedValue::concat(avs.iter()))
}
Self::CoinCommit { coin, recipient } => {
let coin_av = coin.materialize(scope)?;
let recipient_av = recipient.materialize(scope)?;
coin_commit_aligned(&coin_av, &recipient_av)
}
Self::LeafHash(inner) => {
let inner_av = inner.materialize(scope)?;
Ok(leaf_hash_aligned(inner_av))
}
}
}
}
impl CompiledStateValue {
fn materialize(
&self,
scope: &EvalScope<'_>,
) -> Result<StateValue<InMemoryDB, AlignedValueChecked>> {
match self {
Self::Static(sv) => Ok(sv.clone()),
Self::Cell(cav) => {
let av = cav.materialize(scope)?;
let checked = checked_cell_value(av)?;
Ok(StateValue::Cell(Sp::new(checked)))
}
Self::Array(items) => {
let mut resolved = Vec::with_capacity(items.len());
for item in items {
resolved.push(item.materialize(scope)?);
}
Ok(StateValue::Array(StorageArray::from(resolved)))
}
}
}
}
impl CompiledPathKey {
fn materialize(&self, scope: &EvalScope<'_>) -> Result<Key> {
match self {
Self::Static(key) => Ok(key.clone()),
Self::DynamicRef { expr, plan } => {
let resolved = expr.resolve(scope)?;
let av = if let Some(p) = plan {
p.encode(&resolved)?
} else {
align_value_with_bytes(json_as_u128(&resolved)?, 1)?
};
Ok(Key::Value(checked_key(av)?))
}
}
}
}
impl CompiledOp {
pub fn materialize(&self, scope: &EvalScope<'_>) -> Result<Op<ResultModeGather, InMemoryDB>> {
match self {
Self::Static(op) => Ok(op.clone()),
Self::Push { storage, value } => Ok(Op::Push {
storage: *storage,
value: value.materialize(scope)?,
}),
Self::Idx {
cached,
push_path,
path,
} => {
let mut keys = Vec::with_capacity(path.len());
for elt in path {
keys.push(elt.materialize(scope)?);
}
Ok(Op::Idx {
cached: *cached,
push_path: *push_path,
path: StorageArray::from(keys),
})
}
Self::Ins { cached, n } => Ok(Op::Ins {
cached: *cached,
n: narrow_int("ins", "n", n.eval(scope)?)?,
}),
Self::Addi { immediate } => Ok(Op::Addi {
immediate: narrow_int("addi", "immediate", immediate.eval(scope)?)?,
}),
Self::Subi { immediate } => Ok(Op::Subi {
immediate: narrow_int("subi", "immediate", immediate.eval(scope)?)?,
}),
Self::Noop { n } => {
let n_raw = n.eval(scope).unwrap_or(0);
Ok(Op::Noop {
n: u32::try_from(n_raw).unwrap_or(0),
})
}
Self::Dup { n } => Ok(Op::Dup {
n: narrow_int("dup", "n", n.eval(scope)?)?,
}),
Self::Swap { n } => Ok(Op::Swap {
n: narrow_int("swap", "n", n.eval(scope)?)?,
}),
Self::Concat { cached, n } => Ok(Op::Concat {
cached: *cached,
n: narrow_int("concat", "n", n.eval(scope)?)?,
}),
Self::Branch { skip } => Ok(Op::Branch {
skip: narrow_int("branch", "skip", skip.eval(scope)?)?,
}),
Self::Jmp { skip } => Ok(Op::Jmp {
skip: narrow_int("jmp", "skip", skip.eval(scope)?)?,
}),
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct SlotCompiledQuery {
pub(crate) flags: QueryFlags,
pub(crate) body: SlotQueryBody,
}
#[derive(Debug, Clone)]
pub(crate) enum SlotQueryBody {
Static(Box<[Op<ResultModeGather, InMemoryDB>]>),
Dynamic(Box<[SlotCompiledOp]>),
}
#[derive(Debug, Clone)]
pub(crate) enum SlotCompiledOp {
Static(Op<ResultModeGather, InMemoryDB>),
Push {
storage: bool,
value: SlotStateValue,
},
Idx {
cached: bool,
push_path: bool,
path: Box<[SlotPathKey]>,
},
Ins {
cached: bool,
n: SlotIntArg,
},
Addi {
immediate: SlotIntArg,
},
Subi {
immediate: SlotIntArg,
},
Noop {
n: SlotIntArg,
},
Dup {
n: SlotIntArg,
},
Swap {
n: SlotIntArg,
},
Concat {
cached: bool,
n: SlotIntArg,
},
Branch {
skip: SlotIntArg,
},
Jmp {
skip: SlotIntArg,
},
}
#[derive(Debug, Clone)]
pub(crate) enum SlotStateValue {
Static(StateValue<InMemoryDB, AlignedValueChecked>),
Cell(SlotAlignedValue),
Array(Box<[SlotStateValue]>),
}
#[derive(Debug, Clone)]
pub(crate) enum SlotAlignedValue {
Static(AlignedValue),
Ref {
expr: SlotRefExpr,
plan: FabPlan,
},
AlignedConcat(Box<[SlotAlignedValue]>),
CoinCommit {
coin: Box<SlotAlignedValue>,
recipient: Box<SlotAlignedValue>,
},
LeafHash(Box<SlotAlignedValue>),
}
#[derive(Debug, Clone)]
pub(crate) enum SlotPathKey {
Static(Key),
DynamicRef {
expr: SlotRefExpr,
plan: Option<FabPlan>,
},
}
#[derive(Debug, Clone)]
pub(crate) enum SlotIntArg {
Static(u128),
Ref(SlotRefExpr),
Add(Box<SlotIntArg>, Box<SlotIntArg>),
}
#[derive(Debug, Clone)]
pub(crate) enum SlotRefExpr {
Slot(u16),
Const(VmVal),
EltRef {
base: Box<SlotRefExpr>,
field: Arc<str>,
},
NewStruct {
fields: Box<[Arc<str>]>,
args: Box<[SlotRefExpr]>,
},
NewArray(Box<[SlotRefExpr]>),
}
impl SlotCompiledQuery {
#[must_use]
pub(crate) fn from_compiled(
query: &CompiledLedgerQuery,
resolve_var: &impl Fn(&str) -> Option<u16>,
) -> Option<Self> {
let body = match &query.body {
CompiledQueryBody::Static(ops) => SlotQueryBody::Static(ops.clone().into_boxed_slice()),
CompiledQueryBody::Dynamic(ops) => {
let mut bound = Vec::with_capacity(ops.len());
for op in ops {
bound.push(bind_slot_op(op, resolve_var)?);
}
SlotQueryBody::Dynamic(bound.into_boxed_slice())
}
};
Some(Self {
flags: query.flags,
body,
})
}
pub(crate) fn materialize_dynamic(
ops: &[SlotCompiledOp],
frame: &[VmVal],
) -> Result<Vec<Op<ResultModeGather, InMemoryDB>>> {
let mut out = Vec::with_capacity(ops.len());
for op in ops {
out.push(op.materialize(frame)?);
}
Ok(out)
}
}
fn bind_slot_op(
op: &CompiledOp,
resolve_var: &impl Fn(&str) -> Option<u16>,
) -> Option<SlotCompiledOp> {
Some(match op {
CompiledOp::Static(raw) => SlotCompiledOp::Static(raw.clone()),
CompiledOp::Push { storage, value } => SlotCompiledOp::Push {
storage: *storage,
value: bind_slot_state_value(value, resolve_var)?,
},
CompiledOp::Idx {
cached,
push_path,
path,
} => {
let mut keys = Vec::with_capacity(path.len());
for k in path {
keys.push(bind_slot_path_key(k, resolve_var)?);
}
SlotCompiledOp::Idx {
cached: *cached,
push_path: *push_path,
path: keys.into_boxed_slice(),
}
}
CompiledOp::Ins { cached, n } => SlotCompiledOp::Ins {
cached: *cached,
n: bind_slot_int_arg(n, resolve_var)?,
},
CompiledOp::Addi { immediate } => SlotCompiledOp::Addi {
immediate: bind_slot_int_arg(immediate, resolve_var)?,
},
CompiledOp::Subi { immediate } => SlotCompiledOp::Subi {
immediate: bind_slot_int_arg(immediate, resolve_var)?,
},
CompiledOp::Noop { n } => SlotCompiledOp::Noop {
n: bind_slot_int_arg(n, resolve_var)?,
},
CompiledOp::Dup { n } => SlotCompiledOp::Dup {
n: bind_slot_int_arg(n, resolve_var)?,
},
CompiledOp::Swap { n } => SlotCompiledOp::Swap {
n: bind_slot_int_arg(n, resolve_var)?,
},
CompiledOp::Concat { cached, n } => SlotCompiledOp::Concat {
cached: *cached,
n: bind_slot_int_arg(n, resolve_var)?,
},
CompiledOp::Branch { skip } => SlotCompiledOp::Branch {
skip: bind_slot_int_arg(skip, resolve_var)?,
},
CompiledOp::Jmp { skip } => SlotCompiledOp::Jmp {
skip: bind_slot_int_arg(skip, resolve_var)?,
},
})
}
fn bind_slot_state_value(
sv: &CompiledStateValue,
resolve_var: &impl Fn(&str) -> Option<u16>,
) -> Option<SlotStateValue> {
Some(match sv {
CompiledStateValue::Static(s) => SlotStateValue::Static(s.clone()),
CompiledStateValue::Cell(av) => {
SlotStateValue::Cell(bind_slot_aligned_value(av, resolve_var)?)
}
CompiledStateValue::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
out.push(bind_slot_state_value(item, resolve_var)?);
}
SlotStateValue::Array(out.into_boxed_slice())
}
})
}
fn bind_slot_aligned_value(
av: &CompiledAlignedValue,
resolve_var: &impl Fn(&str) -> Option<u16>,
) -> Option<SlotAlignedValue> {
Some(match av {
CompiledAlignedValue::Static(s) => SlotAlignedValue::Static(s.clone()),
CompiledAlignedValue::Ref { expr, plan } => SlotAlignedValue::Ref {
expr: bind_slot_ref_expr(expr, resolve_var)?,
plan: plan.clone(),
},
CompiledAlignedValue::AlignedConcat(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
out.push(bind_slot_aligned_value(item, resolve_var)?);
}
SlotAlignedValue::AlignedConcat(out.into_boxed_slice())
}
CompiledAlignedValue::CoinCommit { coin, recipient } => SlotAlignedValue::CoinCommit {
coin: Box::new(bind_slot_aligned_value(coin, resolve_var)?),
recipient: Box::new(bind_slot_aligned_value(recipient, resolve_var)?),
},
CompiledAlignedValue::LeafHash(inner) => {
SlotAlignedValue::LeafHash(Box::new(bind_slot_aligned_value(inner, resolve_var)?))
}
})
}
fn bind_slot_path_key(
key: &CompiledPathKey,
resolve_var: &impl Fn(&str) -> Option<u16>,
) -> Option<SlotPathKey> {
Some(match key {
CompiledPathKey::Static(k) => SlotPathKey::Static(k.clone()),
CompiledPathKey::DynamicRef { expr, plan } => SlotPathKey::DynamicRef {
expr: bind_slot_ref_expr(expr, resolve_var)?,
plan: plan.clone(),
},
})
}
fn bind_slot_int_arg(
arg: &CompiledIntArg,
resolve_var: &impl Fn(&str) -> Option<u16>,
) -> Option<SlotIntArg> {
Some(match arg {
CompiledIntArg::Static(n) => SlotIntArg::Static(*n),
CompiledIntArg::Ref(expr) => SlotIntArg::Ref(bind_slot_ref_expr(expr, resolve_var)?),
CompiledIntArg::Add(l, r) => SlotIntArg::Add(
Box::new(bind_slot_int_arg(l, resolve_var)?),
Box::new(bind_slot_int_arg(r, resolve_var)?),
),
})
}
fn bind_slot_ref_expr(
expr: &CompiledRefExpr,
resolve_var: &impl Fn(&str) -> Option<u16>,
) -> Option<SlotRefExpr> {
match expr {
CompiledRefExpr::Var(name) => Some(SlotRefExpr::Slot(resolve_var(name)?)),
CompiledRefExpr::Literal(v) => Some(SlotRefExpr::Const(VmVal::from_runtime_value(v))),
CompiledRefExpr::Expr(e) => bind_slot_ir_expr(e, resolve_var),
}
}
fn bind_slot_ir_expr(
expr: &moonproof_runtime_ir::ir::Expression,
resolve_var: &impl Fn(&str) -> Option<u16>,
) -> Option<SlotRefExpr> {
use moonproof_runtime_ir::ir::{Expression as E, TypeDescriptor as T};
match expr {
E::Var { name } => Some(SlotRefExpr::Slot(resolve_var(name)?)),
E::Literal { value } => Some(SlotRefExpr::Const(VmVal::from_runtime_value(value))),
E::EnumRef { of_type, variant } => match of_type {
T::Enum { elements, .. } if elements.iter().any(|v| v == variant) => {
Some(SlotRefExpr::Const(VmVal::Str(Arc::from(variant.as_str()))))
}
_ => None,
},
E::Default { of_type } => {
let v = super::vm_val::default_vm_val(of_type).ok()?;
Some(SlotRefExpr::Const(v))
}
E::EltRef { value, field, .. } => Some(SlotRefExpr::EltRef {
base: Box::new(bind_slot_ir_expr(value, resolve_var)?),
field: Arc::from(field.as_str()),
}),
E::New { of_type, arguments } => {
let mut ty = of_type;
while let T::Alias { of, .. } = ty {
ty = of;
}
let mut args = Vec::with_capacity(arguments.len());
for a in arguments {
args.push(bind_slot_ir_expr(a, resolve_var)?);
}
match ty {
T::Struct { elements, .. } if elements.len() == args.len() => {
let fields: Vec<Arc<str>> = elements
.iter()
.map(|f| Arc::from(f.name.as_str()))
.collect();
Some(SlotRefExpr::NewStruct {
fields: fields.into_boxed_slice(),
args: args.into_boxed_slice(),
})
}
T::Tuple { types } if types.len() == args.len() => {
Some(SlotRefExpr::NewArray(args.into_boxed_slice()))
}
T::Vector { length, .. } if *length as usize == args.len() => {
Some(SlotRefExpr::NewArray(args.into_boxed_slice()))
}
_ => None,
}
}
_ => None,
}
}
impl SlotRefExpr {
#[inline]
fn resolve<'a>(&'a self, frame: &'a [VmVal]) -> Result<Cow<'a, VmVal>> {
match self {
Self::Slot(slot) => Ok(Cow::Borrowed(&frame[usize::from(*slot)])),
Self::Const(v) => Ok(Cow::Borrowed(v)),
Self::EltRef { base, field } => {
let v = base.resolve(frame)?;
let found = v.get_field(field, None).ok_or_else(|| {
IrDriverError::TypeMismatch(format!(
"field '{field}' not in struct {}",
v.to_runtime_value()
))
})?;
Ok(Cow::Owned(found.clone()))
}
Self::NewStruct { fields, args } => {
let mut out = Vec::with_capacity(fields.len());
for (name, arg) in fields.iter().zip(args.iter()) {
out.push((Arc::clone(name), arg.resolve(frame)?.into_owned()));
}
Ok(Cow::Owned(VmVal::Object(Arc::from(out))))
}
Self::NewArray(args) => {
let mut out = Vec::with_capacity(args.len());
for arg in args {
out.push(arg.resolve(frame)?.into_owned());
}
Ok(Cow::Owned(VmVal::Array(Arc::from(out))))
}
}
}
}
impl SlotIntArg {
fn eval(&self, frame: &[VmVal]) -> Result<u128> {
match self {
Self::Static(n) => Ok(*n),
Self::Ref(expr) => expr.resolve(frame)?.as_u128_parsed(),
Self::Add(left, right) => {
let l = left.eval(frame)?;
let r = right.eval(frame)?;
l.checked_add(r).ok_or_else(|| {
IrDriverError::TypeMismatch(format!("vm:add overflow: {l} + {r} exceeds u128"))
})
}
}
}
}
impl SlotAlignedValue {
fn materialize(&self, frame: &[VmVal]) -> Result<AlignedValue> {
match self {
Self::Static(av) => Ok(av.clone()),
Self::Ref { expr, plan } => {
let resolved = expr.resolve(frame)?;
plan.encode_vm_val(&resolved)
}
Self::AlignedConcat(items) => {
let mut avs = Vec::with_capacity(items.len());
for item in items {
avs.push(item.materialize(frame)?);
}
Ok(AlignedValue::concat(avs.iter()))
}
Self::CoinCommit { coin, recipient } => {
let coin_av = coin.materialize(frame)?;
let recipient_av = recipient.materialize(frame)?;
coin_commit_aligned(&coin_av, &recipient_av)
}
Self::LeafHash(inner) => {
let inner_av = inner.materialize(frame)?;
Ok(leaf_hash_aligned(inner_av))
}
}
}
}
impl SlotStateValue {
fn materialize(&self, frame: &[VmVal]) -> Result<StateValue<InMemoryDB, AlignedValueChecked>> {
match self {
Self::Static(sv) => Ok(sv.clone()),
Self::Cell(cav) => {
let av = cav.materialize(frame)?;
let checked = checked_cell_value(av)?;
Ok(StateValue::Cell(Sp::new(checked)))
}
Self::Array(items) => {
let mut resolved = Vec::with_capacity(items.len());
for item in items {
resolved.push(item.materialize(frame)?);
}
Ok(StateValue::Array(StorageArray::from(resolved)))
}
}
}
}
impl SlotPathKey {
fn materialize(&self, frame: &[VmVal]) -> Result<Key> {
match self {
Self::Static(key) => Ok(key.clone()),
Self::DynamicRef { expr, plan } => {
let resolved = expr.resolve(frame)?;
let av = if let Some(p) = plan {
p.encode_vm_val(&resolved)?
} else {
align_value_with_bytes(resolved.as_u128_parsed()?, 1)?
};
Ok(Key::Value(checked_key(av)?))
}
}
}
}
impl SlotCompiledOp {
fn materialize(&self, frame: &[VmVal]) -> Result<Op<ResultModeGather, InMemoryDB>> {
match self {
Self::Static(op) => Ok(op.clone()),
Self::Push { storage, value } => Ok(Op::Push {
storage: *storage,
value: value.materialize(frame)?,
}),
Self::Idx {
cached,
push_path,
path,
} => {
let mut keys = Vec::with_capacity(path.len());
for elt in path {
keys.push(elt.materialize(frame)?);
}
Ok(Op::Idx {
cached: *cached,
push_path: *push_path,
path: StorageArray::from(keys),
})
}
Self::Ins { cached, n } => Ok(Op::Ins {
cached: *cached,
n: narrow_int("ins", "n", n.eval(frame)?)?,
}),
Self::Addi { immediate } => Ok(Op::Addi {
immediate: narrow_int("addi", "immediate", immediate.eval(frame)?)?,
}),
Self::Subi { immediate } => Ok(Op::Subi {
immediate: narrow_int("subi", "immediate", immediate.eval(frame)?)?,
}),
Self::Noop { n } => {
let n_raw = n.eval(frame).unwrap_or(0);
Ok(Op::Noop {
n: u32::try_from(n_raw).unwrap_or(0),
})
}
Self::Dup { n } => Ok(Op::Dup {
n: narrow_int("dup", "n", n.eval(frame)?)?,
}),
Self::Swap { n } => Ok(Op::Swap {
n: narrow_int("swap", "n", n.eval(frame)?)?,
}),
Self::Concat { cached, n } => Ok(Op::Concat {
cached: *cached,
n: narrow_int("concat", "n", n.eval(frame)?)?,
}),
Self::Branch { skip } => Ok(Op::Branch {
skip: narrow_int("branch", "skip", skip.eval(frame)?)?,
}),
Self::Jmp { skip } => Ok(Op::Jmp {
skip: narrow_int("jmp", "skip", skip.eval(frame)?)?,
}),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use moonproof_ledger::base_crypto::fab::{
Alignment, AlignmentAtom, Value as FabValue, ValueAtom,
};
fn oversized_field() -> AlignedValue {
AlignedValue::new(
FabValue(vec![ValueAtom(vec![0xff; 32])]),
Alignment::singleton(AlignmentAtom::Field),
)
.expect("32 bytes fit a field atom's alignment")
}
#[test]
fn checked_key_accepts_a_canonical_value() {
assert!(checked_key(AlignedValue::from(7u8)).is_ok());
}
#[test]
fn checked_key_refuses_a_field_atom_above_the_modulus() {
assert!(matches!(
checked_key(oversized_field()),
Err(IrDriverError::InvalidIr(_))
));
}
#[test]
fn checked_state_value_accepts_a_canonical_cell() {
let cell = StateValue::Cell(Sp::new(AlignedValue::from(7u8)));
assert!(checked_state_value(&cell).is_ok());
}
#[test]
fn checked_state_value_refuses_a_non_canonical_cell() {
let cell = StateValue::Cell(Sp::new(oversized_field()));
assert!(matches!(
checked_state_value(&cell),
Err(IrDriverError::InvalidIr(_))
));
}
#[test]
fn analyze_ops_classifies_read_write_context_effects_and_branches() {
let key0 = Key::Value(checked_key(AlignedValue::from(0u8)).unwrap());
let read_ops = vec![
Op::Dup { n: 0 },
Op::Idx {
cached: false,
push_path: false,
path: StorageArray::from(vec![key0.clone()]),
},
Op::Popeq {
cached: false,
result: (),
},
];
assert_eq!(
analyze_ops(&read_ops),
QueryFlags {
reads_context: false,
touches_effects: false,
mutates_state: false,
}
);
let write_ops = vec![
Op::Idx {
cached: false,
push_path: true,
path: StorageArray::from(vec![key0.clone()]),
},
Op::Push {
storage: true,
value: checked_state_value(&StateValue::Cell(Sp::new(AlignedValue::from(1u8))))
.unwrap(),
},
Op::Ins {
cached: false,
n: 1,
},
];
assert_eq!(
analyze_ops(&write_ops),
QueryFlags {
reads_context: false,
touches_effects: false,
mutates_state: true,
}
);
let ctx_ops = vec![
Op::Dup { n: 2 },
Op::Idx {
cached: true,
push_path: false,
path: StorageArray::from(vec![key0]),
},
Op::Popeq {
cached: true,
result: (),
},
];
assert_eq!(
analyze_ops(&ctx_ops),
QueryFlags {
reads_context: true,
touches_effects: false,
mutates_state: false,
}
);
let eff_ops = vec![Op::Swap { n: 0 }, Op::Swap { n: 0 }];
assert!(analyze_ops(&eff_ops).touches_effects);
assert!(!analyze_ops(&eff_ops).reads_context);
let branch_ops = vec![
Op::Push {
storage: false,
value: checked_state_value(&StateValue::Cell(Sp::new(AlignedValue::from(true))))
.unwrap(),
},
Op::Branch { skip: 0 },
];
assert_eq!(analyze_ops(&branch_ops), QueryFlags::ALL);
}
}