Skip to main content

moonproof_runtime/ir/
interp.rs

1//! Statement / Expression walker — the runtime interpreter.
2//!
3//! Holds the mutable bookkeeping a circuit accumulates during
4//! execution (public transcript, witness outputs, popeq reads, the
5//! current contract state, the local variable scope) and walks the
6//! body IR producing an [`ExecuteCircuitResult`]-shaped output.
7//!
8//! Today this handles the registry-shape body — `Statement::Seq` /
9//! `Const` / `Expr`, `Expression::Var` / `Literal` / `Call` (witness
10//! only) / `AdtOp` / `EltRef`. Surfaces a clear `Unimplemented`
11//! error for anything else so callers know exactly which IR node
12//! the interpreter needs to grow next.
13
14use std::collections::HashMap;
15use std::sync::{Arc, LazyLock};
16
17use moonproof_ledger::base_crypto::cost_model::RunningCost;
18use moonproof_ledger::base_crypto::fab::AlignedValue;
19use moonproof_ledger::base_crypto::hash::HashOutput;
20use moonproof_ledger::base_crypto::time::Timestamp;
21use moonproof_ledger::coin_structure::contract::ContractAddress;
22use moonproof_ledger::onchain_runtime::context::{Effects, QueryContext};
23use moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
24use moonproof_ledger::onchain_runtime::ops::Op;
25use moonproof_ledger::onchain_runtime::result_mode::{GatherEvent, ResultModeGather};
26use moonproof_ledger::onchain_runtime::state::{ChargedState, ContractState, StateValue};
27use moonproof_ledger::onchain_runtime::vm_value::{ValueStrength, VmValue};
28use moonproof_ledger::storage::db::InMemoryDB;
29use moonproof_runtime_ir::ir::{
30    AdtOpInvocation, CircuitBody, Expression, FieldType, IntLit, MoonIr, Statement, TupleItem,
31    TypeDescriptor, VmInstr,
32};
33use moonproof_runtime_ir::RuntimeValue as Value;
34use rustc_hash::{FxBuildHasher, FxHashMap};
35
36use super::descriptor::{decode_aligned_value_full, encode_literal, FabPlan};
37use super::error::{IrDriverError, Result};
38use super::index::{IrIndex, NativeFabPlans};
39use super::vm_decode::{
40    analyze_ops, decode_op, CompiledLedgerQuery, CompiledQueryBody, EvalScope, QueryFlags,
41};
42use super::witnesses::Witnesses;
43use crate::cross_contract::CallTreeRun;
44use crate::zswap_local::{CompactZswapLocalState, CompactZswapOutput};
45
46/// Process-wide cached empty [`Effects`] to avoid allocating 9 empty storage
47/// MPTs on every circuit call.
48static EMPTY_EFFECTS: LazyLock<Effects<InMemoryDB>> = LazyLock::new(Effects::default);
49
50/// Process-wide cached VM-stack representation of an empty [`Effects`] record
51/// (`stack[1]`). Cloning this is a single `Arc` refcount increment.
52static EMPTY_EFFECTS_VM: LazyLock<VmValue<InMemoryDB>> = LazyLock::new(|| (&*EMPTY_EFFECTS).into());
53
54/// Process-wide cached empty [`ContractState`] used as a placeholder during
55/// single-session constructor execution before building the final `ContractState`.
56static EMPTY_CONTRACT_STATE: LazyLock<ContractState<InMemoryDB>> =
57    LazyLock::new(ContractState::default);
58
59/// Cheap O(1) clone of an empty [`Effects`] record.
60#[inline]
61#[must_use]
62pub(crate) fn empty_effects() -> Effects<InMemoryDB> {
63    EMPTY_EFFECTS.clone()
64}
65
66/// Cheap O(1) clone of an empty [`ContractState`].
67#[inline]
68#[must_use]
69pub(crate) fn empty_contract_state() -> ContractState<InMemoryDB> {
70    EMPTY_CONTRACT_STATE.clone()
71}
72
73#[inline]
74fn effects_is_empty(effects: &Effects<InMemoryDB>) -> bool {
75    effects.claimed_nullifiers.is_empty()
76        && effects.claimed_shielded_receives.is_empty()
77        && effects.claimed_shielded_spends.is_empty()
78        && effects.claimed_contract_calls.is_empty()
79        && effects.shielded_mints.is_empty()
80        && effects.unshielded_mints.is_empty()
81        && effects.unshielded_inputs.is_empty()
82        && effects.unshielded_outputs.is_empty()
83        && effects.claimed_unshielded_spends.is_empty()
84}
85
86/// Apply `ChargedState::update` with the exact same cost-model closures used
87/// by `QueryContext::query`, once at circuit exit when state actually changed.
88fn update_charged_state(
89    charged: &ChargedState<InMemoryDB>,
90    new_state: StateValue<InMemoryDB>,
91) -> ChargedState<InMemoryDB> {
92    let cost_model = &INITIAL_COST_MODEL;
93    let (new_charged_state, _state_cost) = charged.update(
94        new_state,
95        |writes, deletes| {
96            RunningCost::compute(
97                cost_model.gc_rcmap_constant
98                    + cost_model.gc_rcmap_coeff_keys_removed_size * deletes
99                    + cost_model.update_rcmap_constant
100                    + cost_model.update_rcmap_coeff_keys_added_size * writes
101                    + cost_model.get_writes_constant
102                    + cost_model.get_writes_coeff_keys_added_size * writes,
103            )
104        },
105        |budget| {
106            (budget.compute_time / cost_model.gc_rcmap_coeff_keys_removed_size).into_atomic_units(1)
107                as usize
108        },
109    );
110    new_charged_state
111}
112
113/// Persistent on-chain VM stack threaded across sequential `AdtOp`, `Emit`,
114/// and `claimContractCall` queries within a single circuit or constructor run.
115///
116/// Calls `moonproof_ledger::onchain_runtime::vm::run_program` directly on the
117/// 3-slot stack `[ctx_vm, effects_vm, state_vm]` without rebuilding MPTs via
118/// `QueryContext::to_vm_stack()`, decoding `Effects::try_from`, or running
119/// `ChargedState::update` between ops.
120#[derive(Debug, Clone)]
121pub struct VmSession {
122    stack: [VmValue<InMemoryDB>; 3],
123    ctx_materialized: bool,
124    effects_touched: bool,
125    state_mutated: bool,
126}
127
128impl VmSession {
129    /// Start a session directly from a raw contract `StateValue` (used by
130    /// `IrExecutable::initialize` to run `init_ops` + `constructor.body` in
131    /// one session before constructing `ContractState` once).
132    #[must_use]
133    pub(crate) fn from_state_value(initial_state: StateValue<InMemoryDB>) -> Self {
134        Self {
135            stack: [
136                VmValue::new(ValueStrength::Weak, StateValue::Null),
137                EMPTY_EFFECTS_VM.clone(),
138                VmValue::new(ValueStrength::Strong, initial_state),
139            ],
140            ctx_materialized: false,
141            effects_touched: false,
142            state_mutated: false,
143        }
144    }
145
146    /// Start a session from contract state and effects.
147    #[must_use]
148    pub(crate) fn from_state_and_effects(
149        contract_state: &ContractState<InMemoryDB>,
150        effects: &Effects<InMemoryDB>,
151    ) -> Self {
152        let effects_vm = if effects_is_empty(effects) {
153            EMPTY_EFFECTS_VM.clone()
154        } else {
155            effects.into()
156        };
157        Self {
158            stack: [
159                VmValue::new(ValueStrength::Weak, StateValue::Null),
160                effects_vm,
161                VmValue::new(ValueStrength::Strong, contract_state.data.get_ref().clone()),
162            ],
163            ctx_materialized: false,
164            effects_touched: false,
165            state_mutated: false,
166        }
167    }
168
169    /// Start a session from an [`InterpState`]'s current contract state and effects.
170    #[must_use]
171    fn from_interp_state(state: &InterpState<'_>) -> Self {
172        Self::from_state_and_effects(&state.contract_state, &state.effects)
173    }
174
175    /// Flush this session back into `contract_state.data` and `effects`.
176    pub(crate) fn sync_into(
177        self,
178        contract_state: &mut ContractState<InMemoryDB>,
179        effects: &mut Effects<InMemoryDB>,
180    ) -> Result<()> {
181        let [_ctx, effects_vm, state_vm] = self.stack;
182        if self.effects_touched {
183            *effects = Effects::try_from(effects_vm)
184                .map_err(|e| IrDriverError::VmOp(format!("decoding VM effects failed: {e:?}")))?;
185        }
186        if self.state_mutated && &state_vm.value != contract_state.data.get_ref() {
187            contract_state.data = update_charged_state(&contract_state.data, state_vm.value);
188        }
189        Ok(())
190    }
191
192    /// Lazily materialize `stack[0]` (`ctx_vm`) the first time a query reads
193    /// call context.
194    pub(crate) fn ensure_context(
195        &mut self,
196        contract_state: &ContractState<InMemoryDB>,
197        address: ContractAddress,
198        tblock: Timestamp,
199        coin_commitments: &[(moonproof_ledger::coin_structure::coin::Commitment, u64)],
200        caller: Option<ContractAddress>,
201    ) {
202        if !self.ctx_materialized {
203            let qctx = query_context(
204                contract_state,
205                address,
206                tblock,
207                coin_commitments,
208                caller,
209                &EMPTY_EFFECTS,
210            );
211            self.stack[0] = VmValue::from(&qctx);
212            self.ctx_materialized = true;
213        }
214    }
215
216    /// Execute `ops` directly on `self.stack` via `vm::run_program`, checking
217    /// the exact 3-slot stack and strong-state invariants enforced by
218    /// `QueryContext::query`.
219    pub(crate) fn run_ops(
220        &mut self,
221        ops: &[Op<ResultModeGather, InMemoryDB>],
222        flags: QueryFlags,
223        err_context: impl FnOnce() -> String,
224    ) -> Result<Vec<GatherEvent<InMemoryDB>>> {
225        let res = match moonproof_ledger::onchain_runtime::vm::run_program(
226            &self.stack,
227            ops,
228            None,
229            &INITIAL_COST_MODEL,
230        ) {
231            Ok(res) => res,
232            Err(e) => return Err(IrDriverError::VmOp(format!("{}: {e:?}", err_context()))),
233        };
234
235        let mut res_stack = res.stack;
236        if res_stack.len() != 3 {
237            return Err(IrDriverError::VmOp(format!(
238                "{}: FinalStackWrongLength (got {})",
239                err_context(),
240                res_stack.len()
241            )));
242        }
243        let new_state = res_stack.pop().expect("len == 3");
244        if new_state.strength != ValueStrength::Strong {
245            return Err(IrDriverError::VmOp(format!(
246                "{}: WeakStateReturned",
247                err_context()
248            )));
249        }
250        let new_effects = res_stack.pop().expect("len == 3");
251        let new_ctx = res_stack.pop().expect("len == 3");
252        self.stack = [new_ctx, new_effects, new_state];
253        self.effects_touched |= flags.touches_effects;
254        self.state_mutated |= flags.mutates_state;
255        Ok(res.events)
256    }
257
258    /// Consume the session and return the resulting contract `StateValue`.
259    #[must_use]
260    pub(crate) fn into_state_value(self) -> StateValue<InMemoryDB> {
261        let [_ctx, _effects, state] = self.stack;
262        state.value
263    }
264}
265
266/// Fast non-cryptographic variable map used for interpreter `locals` and
267/// `args` scopes.
268pub type VarMap = FxHashMap<String, Value>;
269
270/// Mutable state the interpreter maintains during a single circuit
271/// execution.
272pub struct InterpState<'a> {
273    pub ir: &'a MoonIr,
274    /// Optional pre-built O(1) lookup index over `ir`. Populated by
275    /// `IrExecutable`; falls back to linear scan when `None`.
276    pub index: Option<&'a IrIndex>,
277    pub contract_state: ContractState<InMemoryDB>,
278    pub contract_address: ContractAddress,
279    pub private_state: Value,
280    pub locals: VarMap,
281    pub args: VarMap,
282    pub public_transcript: Vec<Op<ResultModeGather, InMemoryDB>>,
283    pub private_transcript_outputs: Vec<AlignedValue>,
284    pub popeq_read_results: Vec<AlignedValue>,
285    pub witnesses: Arc<dyn Witnesses>,
286    /// Pre-registered coin commitments for `update-with-coin-check`
287    /// op-classes. The on-chain VM walks `context[1] (com_indices)`
288    /// to look up the coin's merkle-tree index when executing
289    /// `Cell.writeCoin` and similar ops. The wallet normally injects
290    /// these from the live chain state; for offline/test runs the
291    /// host can pre-populate them. Empty by default.
292    pub coin_commitments: Vec<(moonproof_ledger::coin_structure::coin::Commitment, u64)>,
293    /// Compact-runtime-side zswap local state — accumulates
294    /// `CompactZswapOutput`s and `QualifiedInfo` inputs as the
295    /// circuit invokes the `createZswapOutput` / `createZswapInput`
296    /// kernel witnesses. The call-tx pipeline reads this and runs
297    /// it through `zswap_state_to_offer` to attach the resulting
298    /// `Offer<ProofPreimage>` to the wrapped `Transaction`.
299    pub next_zswap_local_state: CompactZswapLocalState,
300    /// Contract events emitted by `emit` (MIP-0002), in emission order.
301    /// The on-chain VM surfaces each as a `GatherEvent::Log`; the
302    /// indexer exposes the same values through `contractEvents`.
303    pub emitted_events: Vec<EmittedEvent>,
304    /// Block time the circuit runs at, read by `blockTime*` kernel
305    /// calls through the query context.
306    pub tblock: Timestamp,
307    /// The contract that called this one, for a cross-contract callee.
308    pub caller: Option<ContractAddress>,
309    /// The call tree this circuit runs in. `None` when the host ran it
310    /// on its own, which refuses cross-contract calls.
311    pub call_tree: Option<&'a mut CallTreeRun>,
312    /// What the call has claimed and moved so far: each VM query starts
313    /// from it and leaves its additions here, as one call's queries share
314    /// one effects record on the ledger.
315    pub effects: moonproof_ledger::onchain_runtime::context::Effects<InMemoryDB>,
316    /// Persistent on-chain VM stack threaded across sequential
317    /// `AdtOp` / `Emit` / `claimContractCall` queries within this circuit
318    /// execution. Lazily constructed on the first ledger op (so pure
319    /// circuits never touch VM state) and synced back to
320    /// `contract_state.data` + `effects` via [`Self::sync_from_query_context`].
321    pub vm_session: Option<VmSession>,
322    /// Human-readable contract label for execution traces.
323    pub contract_label: String,
324    /// Currently executing circuit name for execution traces.
325    pub circuit_name: String,
326    /// Optional execution trace sink (`None` when tracing is disabled).
327    pub trace: Option<&'a mut crate::trace::ExecutionTrace>,
328    /// Trace verbosity level when `trace` is `Some`.
329    pub trace_level: crate::trace::TraceLevel,
330    /// Call nesting depth (`0` for root, `+1` per cross-contract hop).
331    pub trace_depth: usize,
332    /// Optional IR execution coverage collector (`None` when disabled).
333    pub coverage: Option<&'a mut crate::coverage::IrCoverageCollector>,
334}
335
336impl InterpState<'_> {
337    /// Flush the persistent [`VmSession`] back into `contract_state.data`
338    /// and `effects`, returning an error if effects decoding fails.
339    pub(crate) fn try_sync_from_query_context(&mut self) -> Result<()> {
340        if let Some(session) = self.vm_session.take() {
341            session.sync_into(&mut self.contract_state, &mut self.effects)?;
342        }
343        Ok(())
344    }
345
346    /// Flush the persistent [`VmSession`] back into `contract_state.data`
347    /// and `effects` after executing statements or expressions.
348    ///
349    /// Direct callers of [`run_statement`] or [`eval_expression`] that construct
350    /// [`InterpState`] manually (rather than using [`IrExecutable`](crate::IrExecutable))
351    /// must invoke this method before reading `self.contract_state` or `self.effects`
352    /// so ledger updates accumulated in `self.vm_session` are committed.
353    pub fn sync_from_query_context(&mut self) {
354        if let Err(err) = self.try_sync_from_query_context() {
355            tracing::error!("sync_from_query_context failed: {err}");
356        }
357    }
358}
359
360/// The query context VM ops run in, filled the way compact-runtime's
361/// `createInitialQueryContext` fills it: the contract's own address and
362/// token balance and the block time. The coin commitments let
363/// `update-with-coin-check` op-classes (e.g. `Cell.writeCoin`) resolve
364/// their merkle-tree index; without them the VM raises
365/// `ExpectedCell(null)` walking `context[1]`.
366pub(crate) fn query_context(
367    contract_state: &ContractState<InMemoryDB>,
368    address: ContractAddress,
369    tblock: Timestamp,
370    coin_commitments: &[(moonproof_ledger::coin_structure::coin::Commitment, u64)],
371    caller: Option<ContractAddress>,
372    effects: &moonproof_ledger::onchain_runtime::context::Effects<InMemoryDB>,
373) -> QueryContext<InMemoryDB> {
374    let mut qctx = QueryContext::new(contract_state.data.clone(), address);
375    qctx.effects = effects.clone();
376    qctx.call_context.own_address = address;
377    qctx.call_context.tblock = tblock;
378    qctx.call_context.balance = contract_state.balance.clone();
379    qctx.call_context.caller =
380        caller.map(moonproof_ledger::coin_structure::coin::PublicAddress::Contract);
381    for (commitment, mt_index) in coin_commitments {
382        qctx.call_context.com_indices =
383            qctx.call_context.com_indices.insert(*commitment, *mt_index);
384    }
385    qctx
386}
387
388/// One `emit` occurrence: the tag and version the contract declared,
389/// plus the state value the VM logged.
390#[derive(Debug, Clone)]
391pub struct EmittedEvent {
392    /// The contract whose circuit emitted the event.
393    pub contract_address: ContractAddress,
394    pub version: u32,
395    pub tag: u32,
396    pub value: moonproof_ledger::onchain_runtime::state::StateValue<InMemoryDB>,
397}
398
399/// Walk a Statement tree, threading mutable interpreter state. Returns
400/// the last-expression value (the circuit's implicit return), or
401/// `Value::Null` if no expression contributed a value.
402pub fn run_statement(state: &mut InterpState<'_>, stmt: &Statement) -> Result<Value> {
403    match stmt {
404        Statement::Seq { items } => {
405            let mut last = Value::Null;
406            for item in items {
407                last = run_statement(state, item)?;
408            }
409            Ok(last)
410        }
411        Statement::Const { binding, value } => {
412            let evaluated = eval_expression(state, value)?;
413            state.locals.insert(binding.name.clone(), evaluated);
414            Ok(Value::Null)
415        }
416        Statement::ConstDestructure { bindings } => {
417            // Compact `const`-without-value: forward-declare locals so
418            // a subsequent `Expression::Assign` to the same name can
419            // bind them. Mirrors Compact source like `let t: Uint<128>;`
420            // where `t` is filled in by an `assign` later in the same
421            // block.
422            for binding in bindings {
423                state.locals.insert(binding.name.clone(), Value::Null);
424            }
425            Ok(Value::Null)
426        }
427        Statement::If { cond, then, r#else } => {
428            let cond_v = eval_expression(state, cond)?;
429            let cond_b = cond_v.as_bool().ok_or_else(|| {
430                IrDriverError::TypeMismatch(format!("if cond not bool: {cond_v}"))
431            })?;
432            if let Some(cov) = state.coverage.as_deref_mut() {
433                cov.record_stmt_if(stmt, cond_b);
434            }
435            if cond_b {
436                run_statement(state, then)
437            } else if let Some(else_b) = r#else {
438                run_statement(state, else_b)
439            } else {
440                Ok(Value::Null)
441            }
442        }
443        Statement::Expr { value } => eval_expression(state, value),
444        Statement::Unimplemented => Err(IrDriverError::unimplemented(
445            "Statement::Unimplemented sentinel from IR",
446        )),
447        Statement::Noop => Ok(Value::Null),
448    }
449}
450
451/// Evaluate an expression, possibly with side effects on
452/// `InterpState` (witness calls update `private_transcript_outputs`;
453/// adt-op invocations append to `public_transcript` and update
454/// `contract_state`).
455pub fn eval_expression(state: &mut InterpState<'_>, expr: &Expression) -> Result<Value> {
456    match expr {
457        Expression::Var { name } => eval_var(state, name),
458        Expression::Literal { value } => Ok(value.clone()),
459        Expression::Default { of_type } => default_value_for_descriptor(of_type),
460        Expression::Call {
461            function,
462            function_uniq,
463            arguments,
464        } => eval_call(state, function, *function_uniq, arguments),
465        Expression::AdtOp(invocation) => eval_adt_op_tracked(state, expr, invocation),
466        Expression::Tuple { items } | Expression::Vector { items } => eval_items(state, items),
467        Expression::EltRef { .. }
468        | Expression::TupleSlice { .. }
469        | Expression::VectorSlice { .. }
470        | Expression::BytesSlice { .. }
471        | Expression::TupleRef { .. }
472        | Expression::VectorRef { .. }
473        | Expression::BytesRef { .. } => eval_access(state, expr),
474        Expression::Fold {
475            length,
476            function,
477            initial,
478            arguments,
479        } => eval_fold(state, length, function, initial, arguments),
480        Expression::Map {
481            length,
482            function,
483            arguments,
484        } => eval_map(state, length, function, arguments),
485        Expression::Seq { items } => eval_seq(state, items),
486        Expression::If { cond, then, r#else } => eval_if(state, expr, cond, then, r#else),
487        Expression::Not { value } => eval_not(state, value),
488        Expression::And { left, right } => eval_and(state, left, right),
489        Expression::Or { left, right } => eval_or(state, left, right),
490        Expression::Eq {
491            left,
492            right,
493            of_type,
494        } => eval_equality(state, of_type.as_ref(), left, right).map(Value::Bool),
495        Expression::Neq {
496            left,
497            right,
498            of_type,
499        } => eval_equality(state, of_type.as_ref(), left, right).map(|eq| Value::Bool(!eq)),
500        Expression::Assert { cond, message } => eval_assert(state, expr, cond, message),
501        Expression::New { of_type, arguments } => eval_new(state, of_type, arguments),
502        Expression::SafeCast { .. }
503        | Expression::Cast { .. }
504        | Expression::DowncastUnsigned { .. }
505        | Expression::CastFromBytes { .. }
506        | Expression::FieldToBytes { .. }
507        | Expression::CastToField { .. }
508        | Expression::CastFromField { .. }
509        | Expression::VectorToBytes { .. }
510        | Expression::BytesToVector { .. }
511        | Expression::CastFromEnum { .. }
512        | Expression::CastToEnum { .. } => eval_conversion(state, expr),
513        // Contract event emission (MIP-0002). The payload is evaluated
514        // for its effects and bound length; the recorded event itself
515        // is produced by replaying `vm_ops` against the ledger, the
516        // same path `public-ledger` operations take.
517        Expression::Emit {
518            payload,
519            payload_length,
520            vm_ops,
521            event_version,
522            event_tag,
523        } => eval_emit(
524            state,
525            expr,
526            payload,
527            *payload_length,
528            vm_ops,
529            *event_version,
530            *event_tag,
531        ),
532        Expression::Assign { name, value } => eval_assign(state, name, value),
533        Expression::Binop {
534            op,
535            of_type,
536            left,
537            right,
538            ..
539        } => {
540            let l = eval_expression(state, left)?;
541            let r = eval_expression(state, right)?;
542            eval_binop(op, of_type.as_ref(), &l, &r)
543        }
544        Expression::EnumRef { of_type, variant } => eval_enum_ref(of_type, variant),
545        Expression::ContractCall {
546            circuit,
547            address,
548            address_type,
549            arguments,
550        } => eval_contract_call(state, circuit, address, address_type, arguments),
551        Expression::Unimplemented => Err(IrDriverError::unimplemented(format!(
552            "Expression variant: {expr:?}"
553        ))),
554    }
555}
556
557/// The indexing and slicing expressions.
558fn eval_access(state: &mut InterpState<'_>, expr: &Expression) -> Result<Value> {
559    match expr {
560        Expression::EltRef { value, field, .. } => eval_elt_ref(state, value, field),
561        Expression::TupleSlice {
562            value,
563            start,
564            length,
565            ..
566        } => eval_tuple_slice(state, value, start, length),
567        Expression::VectorSlice {
568            value,
569            start,
570            length,
571            ..
572        } => eval_vector_slice(state, value, start, length),
573        Expression::BytesSlice {
574            value,
575            start,
576            length,
577            ..
578        } => eval_bytes_slice(state, value, start, length),
579        Expression::TupleRef { value, index } => eval_tuple_ref(state, value, index),
580        Expression::VectorRef { value, index, .. } => eval_vector_ref(state, value, index),
581        Expression::BytesRef { value, index, .. } => eval_bytes_ref(state, value, index),
582        other => Err(IrDriverError::unimplemented(format!(
583            "Expression variant: {other:?}"
584        ))),
585    }
586}
587
588/// The casts and representation changes between value shapes.
589fn eval_conversion(state: &mut InterpState<'_>, expr: &Expression) -> Result<Value> {
590    match expr {
591        Expression::SafeCast { value, .. } | Expression::Cast { value, .. } => {
592            // Casts only matter at the AlignedValue boundary —
593            // descriptors carry the alignment widths. The JSON-typed
594            // value is invariant under Compact's static casts.
595            eval_expression(state, value)
596        }
597        Expression::DowncastUnsigned { value, to_bits, .. } => {
598            eval_downcast_unsigned(state, value, to_bits)
599        }
600        Expression::CastFromBytes { to, length, value } => {
601            eval_cast_from_bytes(state, to, *length, value)
602        }
603        Expression::FieldToBytes {
604            length,
605            field_type,
606            value,
607        } => eval_field_to_bytes(state, *length, *field_type, value),
608        // Move a value into a field, carried as the canonical 32-byte LE
609        // form the field encoders expect.
610        Expression::CastToField {
611            field_type, value, ..
612        } => {
613            let v = eval_expression(state, value)?;
614            let n = super::curve::value_as_u256(&v, "cast-to-field operand")?;
615            let n = super::curve::cast_to_field(*field_type, n)?;
616            Ok(Value::Bytes(n.to_le_bytes().to_vec()))
617        }
618        // Narrow a field element to a `Uint` bounded by `maxval`.
619        // Mirrors print-typescript.ss, which lowers this to the same
620        // bound check `downcast-unsigned` performs.
621        Expression::CastFromField { maxval, value, .. } => {
622            eval_cast_from_field(state, maxval, value)
623        }
624        Expression::VectorToBytes { length, value } => eval_vector_to_bytes(state, *length, value),
625        Expression::BytesToVector { length, value } => eval_bytes_to_vector(state, *length, value),
626        Expression::CastFromEnum {
627            from: from_desc,
628            to,
629            value,
630        } => eval_cast_from_enum(state, from_desc, to, value),
631        Expression::CastToEnum { to, value, .. } => eval_cast_to_enum(state, to, value),
632        other => Err(IrDriverError::unimplemented(format!(
633            "Expression variant: {other:?}"
634        ))),
635    }
636}
637
638fn eval_seq(state: &mut InterpState<'_>, items: &[Expression]) -> Result<Value> {
639    let mut last = Value::Null;
640    for item in items {
641        last = eval_expression(state, item)?;
642    }
643    Ok(last)
644}
645
646fn value_as_bool(v: &Value) -> Option<bool> {
647    match v {
648        Value::Bool(b) => Some(*b),
649        Value::Int(0) => Some(false),
650        Value::Int(1) => Some(true),
651        _ => None,
652    }
653}
654
655fn eval_not(state: &mut InterpState<'_>, value: &Expression) -> Result<Value> {
656    let v = eval_expression(state, value)?;
657    let b = value_as_bool(&v)
658        .ok_or_else(|| IrDriverError::TypeMismatch(format!("not on non-bool: {v}")))?;
659    Ok(Value::Bool(!b))
660}
661
662fn eval_equality(
663    state: &mut InterpState<'_>,
664    of_type: Option<&TypeDescriptor>,
665    left: &Expression,
666    right: &Expression,
667) -> Result<bool> {
668    let l = eval_expression(state, left)?;
669    let r = eval_expression(state, right)?;
670    values_equal_typed(of_type, &l, &r)
671}
672
673fn eval_var(state: &InterpState<'_>, name: &str) -> Result<Value> {
674    // First check args (circuit inputs), then locals
675    // (Const-bound values).
676    if let Some(v) = state.args.get(name) {
677        return Ok(v.clone());
678    }
679    state
680        .locals
681        .get(name)
682        .cloned()
683        .ok_or_else(|| IrDriverError::UnboundVariable(name.to_owned()))
684}
685
686fn eval_elt_ref(state: &mut InterpState<'_>, value: &Expression, field: &str) -> Result<Value> {
687    let v = eval_expression(state, value)?;
688    let obj = v
689        .as_object()
690        .ok_or_else(|| IrDriverError::TypeMismatch(format!("elt-ref on non-object: {v}")))?;
691    obj.get(field)
692        .cloned()
693        .ok_or_else(|| IrDriverError::TypeMismatch(format!("field '{field}' not in struct {v}")))
694}
695
696fn eval_items(state: &mut InterpState<'_>, items: &[TupleItem]) -> Result<Value> {
697    // Tuple and Vector use the same JSON shape — both produce
698    // an array of items. The IR distinguishes them only at the
699    // type level (Tuple is a tuple of mixed types, Vector is a
700    // homogeneous fixed-length array). Runtime semantics are
701    // identical.
702    let mut resolved: Vec<Value> = Vec::with_capacity(items.len());
703    for item in items {
704        match item.kind.as_str() {
705            "single" => resolved.push(eval_expression(state, &item.value)?),
706            "spread" => {
707                // `[...rest, x]` — the inner value is itself an
708                // array; flatten its elements into the parent
709                // sequence.
710                let inner = eval_expression(state, &item.value)?;
711                let arr = inner.as_array().cloned().ok_or_else(|| {
712                    IrDriverError::TypeMismatch(format!("spread item not array: {inner}"))
713                })?;
714                resolved.extend(arr);
715            }
716            other => {
717                return Err(IrDriverError::unimplemented(format!(
718                    "TupleItem kind '{other}'"
719                )));
720            }
721        }
722    }
723    Ok(Value::Array(resolved))
724}
725
726fn eval_tuple_slice(
727    state: &mut InterpState<'_>,
728    value: &Expression,
729    start: &IntLit,
730    length: &IntLit,
731) -> Result<Value> {
732    // Compact's `slice<N>(vec, k)` lowers to TupleSlice when
733    // `k` is a literal constant: take `length` consecutive
734    // elements starting at `start`.
735    let v = eval_expression(state, value)?;
736    let arr = v
737        .as_array()
738        .ok_or_else(|| IrDriverError::TypeMismatch(format!("tuple-slice on non-array: {v}")))?;
739    let start_u = start
740        .as_u32()
741        .ok_or_else(|| IrDriverError::InvalidIr(format!("tuple-slice start out of u32: {start}")))?
742        as usize;
743    let length_u = length.as_u32().ok_or_else(|| {
744        IrDriverError::InvalidIr(format!("tuple-slice length out of u32: {length}"))
745    })? as usize;
746    if start_u
747        .checked_add(length_u)
748        .is_none_or(|end| end > arr.len())
749    {
750        return Err(IrDriverError::TypeMismatch(format!(
751            "tuple-slice [{start_u}..{}] out of bounds (input len={})",
752            start_u.saturating_add(length_u),
753            arr.len()
754        )));
755    }
756    Ok(Value::Array(arr[start_u..start_u + length_u].to_vec()))
757}
758
759fn eval_vector_slice(
760    state: &mut InterpState<'_>,
761    value: &Expression,
762    start: &Expression,
763    length: &IntLit,
764) -> Result<Value> {
765    // Like TupleSlice but `start` is a runtime Expression.
766    let v = eval_expression(state, value)?;
767    let arr = v
768        .as_array()
769        .ok_or_else(|| IrDriverError::TypeMismatch(format!("vector-slice on non-array: {v}")))?;
770    let start_v = eval_expression(state, start)?;
771    let start_u = super::descriptor::json_as_u128(&start_v)? as usize;
772    let length_u = length.as_u32().ok_or_else(|| {
773        IrDriverError::InvalidIr(format!("vector-slice length out of u32: {length}"))
774    })? as usize;
775    if start_u
776        .checked_add(length_u)
777        .is_none_or(|end| end > arr.len())
778    {
779        return Err(IrDriverError::TypeMismatch(format!(
780            "vector-slice [{start_u}..{}] out of bounds (input len={})",
781            start_u.saturating_add(length_u),
782            arr.len()
783        )));
784    }
785    Ok(Value::Array(arr[start_u..start_u + length_u].to_vec()))
786}
787
788fn eval_bytes_slice(
789    state: &mut InterpState<'_>,
790    value: &Expression,
791    start: &Expression,
792    length: &IntLit,
793) -> Result<Value> {
794    // Slice a byte buffer. Returns `length` bytes starting at
795    // byte index `start`.
796    let v = eval_expression(state, value)?;
797    let bytes = v.as_bytes().ok_or_else(|| {
798        IrDriverError::TypeMismatch(format!("bytes-slice on non-bytes value: {v}"))
799    })?;
800    let start_v = eval_expression(state, start)?;
801    let start_u = super::descriptor::json_as_u128(&start_v)? as usize;
802    let length_u = length.as_u32().ok_or_else(|| {
803        IrDriverError::InvalidIr(format!("bytes-slice length out of u32: {length}"))
804    })? as usize;
805    if start_u
806        .checked_add(length_u)
807        .is_none_or(|end| end > bytes.len())
808    {
809        return Err(IrDriverError::TypeMismatch(format!(
810            "bytes-slice [{start_u}..{}] out of bounds (input len={})",
811            start_u.saturating_add(length_u),
812            bytes.len()
813        )));
814    }
815    Ok(Value::Bytes(bytes[start_u..start_u + length_u].to_vec()))
816}
817
818fn eval_tuple_ref(
819    state: &mut InterpState<'_>,
820    value: &Expression,
821    index: &IntLit,
822) -> Result<Value> {
823    let v = eval_expression(state, value)?;
824    let arr = v
825        .as_array()
826        .ok_or_else(|| IrDriverError::TypeMismatch(format!("tuple-ref on non-array: {v}")))?;
827    let idx = index
828        .as_u32()
829        .ok_or_else(|| IrDriverError::InvalidIr(format!("tuple-ref index out of u32: {index}")))?
830        as usize;
831    arr.get(idx).cloned().ok_or_else(|| {
832        IrDriverError::TypeMismatch(format!(
833            "tuple-ref index {idx} out of bounds (len={})",
834            arr.len()
835        ))
836    })
837}
838
839fn eval_vector_ref(
840    state: &mut InterpState<'_>,
841    value: &Expression,
842    index: &Expression,
843) -> Result<Value> {
844    // Like TupleRef but `index` is itself an Expression
845    // (computed at runtime). Same indexing semantics.
846    let v = eval_expression(state, value)?;
847    let arr = v
848        .as_array()
849        .ok_or_else(|| IrDriverError::TypeMismatch(format!("vector-ref on non-array: {v}")))?;
850    let idx_v = eval_expression(state, index)?;
851    let idx = super::descriptor::json_as_u128(&idx_v)? as usize;
852    arr.get(idx).cloned().ok_or_else(|| {
853        IrDriverError::TypeMismatch(format!(
854            "vector-ref index {idx} out of bounds (len={})",
855            arr.len()
856        ))
857    })
858}
859
860fn eval_if(
861    state: &mut InterpState<'_>,
862    expr: &Expression,
863    cond: &Expression,
864    then: &Expression,
865    r#else: &Expression,
866) -> Result<Value> {
867    let c = eval_expression(state, cond)?;
868    let cb = value_as_bool(&c)
869        .ok_or_else(|| IrDriverError::TypeMismatch(format!("if cond not bool: {c}")))?;
870    if let Some(cov) = state.coverage.as_deref_mut() {
871        cov.record_expr_if(expr, cb);
872    }
873    if cb {
874        eval_expression(state, then)
875    } else {
876        eval_expression(state, r#else)
877    }
878}
879
880fn eval_and(state: &mut InterpState<'_>, left: &Expression, right: &Expression) -> Result<Value> {
881    let l = eval_expression(state, left)?
882        .as_bool()
883        .ok_or_else(|| IrDriverError::TypeMismatch("and lhs not bool".into()))?;
884    if !l {
885        return Ok(Value::Bool(false));
886    }
887    let r = eval_expression(state, right)?
888        .as_bool()
889        .ok_or_else(|| IrDriverError::TypeMismatch("and rhs not bool".into()))?;
890    Ok(Value::Bool(r))
891}
892
893fn eval_or(state: &mut InterpState<'_>, left: &Expression, right: &Expression) -> Result<Value> {
894    let l = eval_expression(state, left)?
895        .as_bool()
896        .ok_or_else(|| IrDriverError::TypeMismatch("or lhs not bool".into()))?;
897    if l {
898        return Ok(Value::Bool(true));
899    }
900    let r = eval_expression(state, right)?
901        .as_bool()
902        .ok_or_else(|| IrDriverError::TypeMismatch("or rhs not bool".into()))?;
903    Ok(Value::Bool(r))
904}
905
906fn eval_assert(
907    state: &mut InterpState<'_>,
908    expr: &Expression,
909    cond: &Expression,
910    message: &str,
911) -> Result<Value> {
912    let c = eval_expression(state, cond)?;
913    let cb = value_as_bool(&c)
914        .ok_or_else(|| IrDriverError::TypeMismatch(format!("assert cond not bool: {c}")))?;
915    if let Some(cov) = state.coverage.as_deref_mut() {
916        cov.record_assert(expr, cb);
917    }
918    if !cb {
919        if let Some(trace) = state.trace.as_deref_mut() {
920            trace.push(crate::trace::TraceEvent::AssertFailed {
921                contract: state.contract_label.clone(),
922                circuit: state.circuit_name.clone(),
923                message: message.to_owned(),
924                depth: state.trace_depth,
925            });
926        }
927        return Err(IrDriverError::AssertionFailed(message.to_owned()));
928    }
929    // The assert returns a unit (empty tuple). Use null to
930    // surface "no value" — every consumer ignores asserts'
931    // return values.
932    Ok(Value::Null)
933}
934
935fn eval_downcast_unsigned(
936    state: &mut InterpState<'_>,
937    value: &Expression,
938    to_bits: &IntLit,
939) -> Result<Value> {
940    // Verify the runtime value fits within the target inclusive upper bound.
941    // Note: despite the historical IR field name `to-bits`, both `compactc`
942    // and `compact-lift` emit the inclusive `maxval` (e.g. `65535` for
943    // `Uint<16>`, `4294967295` for `Uint<32>`, `18446744073709551615` for
944    // `Uint<64>`, or arbitrary `M` for `Uint<0..M>`).
945    let v = eval_expression(state, value)?;
946    let n = super::curve::value_as_u256(&v, "downcast-unsigned operand")?;
947    let max = to_bits.as_u256().ok_or_else(|| {
948        IrDriverError::InvalidIr(format!("downcast-unsigned bound is negative: {to_bits}"))
949    })?;
950    if n > max {
951        return Err(IrDriverError::TypeMismatch(format!(
952            "downcast to max {max} overflows: {n}"
953        )));
954    }
955    Ok(v)
956}
957
958fn eval_field_to_bytes(
959    state: &mut InterpState<'_>,
960    length: u32,
961    field_type: Option<FieldType>,
962    value: &Expression,
963) -> Result<Value> {
964    // Compact's `field->bytes`: take a field element, write it
965    // little-endian as N bytes, error if it exceeds N. Mirrors
966    // `compact-runtime/dist/casts.js::convertFieldToBytes`.
967    //
968    // `value_as_u256` covers every shape a field value arrives
969    // in — the canonical 32-byte LE form, a small integer, and
970    // the decimal string arithmetic promotes to past `u128`.
971    // The secp fields exceed `u128` routinely, so the width has
972    // to be 256-bit here regardless of `field_type`.
973    let v = eval_expression(state, value)?;
974    let n = length as usize;
975    let what = field_type.map_or("field->bytes", |_| "field->bytes operand");
976    let bytes = super::curve::value_as_u256(&v, what)?
977        .to_le_bytes()
978        .to_vec();
979    // Verify the value fits in N bytes (any non-zero high bytes are an overflow).
980    for (i, &byte) in bytes.iter().enumerate() {
981        if i >= n && byte != 0 {
982            return Err(IrDriverError::VmOp(format!(
983                "field->bytes: value 0x{} does not fit in {n} bytes",
984                hex::encode(&bytes)
985            )));
986        }
987    }
988    let mut out = vec![0u8; n];
989    let copy_len = bytes.len().min(n);
990    out[..copy_len].copy_from_slice(&bytes[..copy_len]);
991    Ok(Value::Bytes(out))
992}
993
994fn eval_cast_from_field(
995    state: &mut InterpState<'_>,
996    maxval: &IntLit,
997    value: &Expression,
998) -> Result<Value> {
999    let v = eval_expression(state, value)?;
1000    let n = super::curve::value_as_u256(&v, "cast-from-field operand")?;
1001    let max = maxval.as_u128().ok_or_else(|| {
1002        IrDriverError::TypeMismatch(format!("cast-from-field maxval out of u128: {maxval}"))
1003    })?;
1004    if n > ethnum::U256::from(max) {
1005        return Err(IrDriverError::VmOp(format!(
1006            "cast from Field or Uint value to smaller Uint value failed: \
1007             {n} is greater than {max}"
1008        )));
1009    }
1010    let small = u128::from_le_bytes(
1011        n.to_le_bytes()[..16]
1012            .try_into()
1013            .map_err(|_| IrDriverError::TypeMismatch("cast-from-field result slice".to_owned()))?,
1014    );
1015    Ok(uint_value(small))
1016}
1017
1018fn eval_adt_op_tracked(
1019    state: &mut InterpState<'_>,
1020    expr: &Expression,
1021    invocation: &AdtOpInvocation,
1022) -> Result<Value> {
1023    let val = execute_adt_op(state, invocation)?;
1024    if let Some(cov) = state.coverage.as_deref_mut() {
1025        cov.record_adt_op(expr);
1026    }
1027    Ok(val)
1028}
1029
1030fn eval_emit(
1031    state: &mut InterpState<'_>,
1032    expr: &Expression,
1033    payload: &Expression,
1034    payload_length: u32,
1035    vm_ops: &[VmInstr],
1036    event_version: u32,
1037    event_tag: u32,
1038) -> Result<Value> {
1039    let payload_value = eval_expression(state, payload)?;
1040    let encoded = super::curve::value_as_u256(&payload_value, "emit payload")
1041        .map(|n| n.to_le_bytes().to_vec())
1042        .or_else(|_| {
1043            payload_value.as_bytes().map(<[u8]>::to_vec).ok_or_else(|| {
1044                IrDriverError::TypeMismatch(format!(
1045                    "emit payload is neither bytes nor numeric: {payload_value}"
1046                ))
1047            })
1048        })?;
1049    let n = payload_length as usize;
1050    if encoded.len() < n {
1051        return Err(IrDriverError::TypeMismatch(format!(
1052            "emit payload is {} bytes, declared {n}",
1053            encoded.len()
1054        )));
1055    }
1056    let events = run_vm_ops(state, vm_ops).map_err(|e| {
1057        IrDriverError::VmOp(format!(
1058            "emit (version {event_version}, tag {event_tag}) vm-ops failed: {e}"
1059        ))
1060    })?;
1061    for ev in events {
1062        if let GatherEvent::Log(item) = ev {
1063            // Ledger 9 wraps the logged state in a
1064            // `VersionedLogItem`; the facade projects out the
1065            // state value both generations agree on.
1066            state.emitted_events.push(EmittedEvent {
1067                contract_address: state.contract_address,
1068                version: event_version,
1069                tag: event_tag,
1070                value: moonproof_ledger::log_item_state(&item).clone(),
1071            });
1072            if let Some(trace) = state.trace.as_deref_mut() {
1073                trace.push(crate::trace::TraceEvent::EmitEvent {
1074                    contract: state.contract_label.clone(),
1075                    version: event_version,
1076                    tag: event_tag,
1077                    depth: state.trace_depth,
1078                });
1079            }
1080        }
1081    }
1082    if let Some(cov) = state.coverage.as_deref_mut() {
1083        cov.record_emit(expr);
1084    }
1085    // `emit` is a statement in Compact — its value is unit.
1086    Ok(Value::Array(Vec::new()))
1087}
1088
1089fn eval_vector_to_bytes(
1090    state: &mut InterpState<'_>,
1091    length: u32,
1092    value: &Expression,
1093) -> Result<Value> {
1094    // Compact's `vector->bytes` packs `Vector<N, Uint<8>>`
1095    // elements into a single `Bytes<N>` byte buffer.
1096    let v = eval_expression(state, value)?;
1097    let arr = v.as_array().ok_or_else(|| {
1098        IrDriverError::TypeMismatch(format!("vector->bytes input not array: {v}"))
1099    })?;
1100    let n = length as usize;
1101    if arr.len() != n {
1102        return Err(IrDriverError::TypeMismatch(format!(
1103            "vector->bytes expected {n} elements, got {}",
1104            arr.len()
1105        )));
1106    }
1107    let mut out = Vec::with_capacity(n);
1108    for elt in arr {
1109        let byte = elt
1110            .as_u64()
1111            .and_then(|n| u8::try_from(n).ok())
1112            .ok_or_else(|| {
1113                IrDriverError::TypeMismatch(format!("vector->bytes element not u8: {elt}"))
1114            })?;
1115        out.push(byte);
1116    }
1117    Ok(Value::Bytes(out))
1118}
1119
1120fn eval_bytes_to_vector(
1121    state: &mut InterpState<'_>,
1122    length: u32,
1123    value: &Expression,
1124) -> Result<Value> {
1125    // Inverse of VectorToBytes: split a Bytes<N> buffer into
1126    // N u8 elements.
1127    let v = eval_expression(state, value)?;
1128    let bytes = v.as_bytes().ok_or_else(|| {
1129        IrDriverError::TypeMismatch(format!("bytes->vector input not bytes: {v}"))
1130    })?;
1131    let n = length as usize;
1132    if bytes.len() != n {
1133        return Err(IrDriverError::TypeMismatch(format!(
1134            "bytes->vector expected {n} bytes, got {}",
1135            bytes.len()
1136        )));
1137    }
1138    Ok(Value::Array(
1139        bytes.iter().map(|&b| Value::Int(i128::from(b))).collect(),
1140    ))
1141}
1142
1143fn eval_cast_from_enum(
1144    state: &mut InterpState<'_>,
1145    from_desc: &TypeDescriptor,
1146    to: &TypeDescriptor,
1147    value: &Expression,
1148) -> Result<Value> {
1149    // `(e as Uint<N>)` — convert an enum variant to its
1150    // numeric tag. The enum descriptor's `elements` order is
1151    // canonical: variant `i` maps to numeric `i`. The IR's
1152    // JSON shape for an enum variant is `Value::String(name)`;
1153    // resolve it back to the index by walking the source
1154    // enum's element list.
1155    let v = eval_expression(state, value)?;
1156    // The enum's element list is read from the IR-driver's typed
1157    // `from` field (`from_desc` below), not re-derived from the
1158    // inner `value` expression.
1159    let variant = v.as_str().ok_or_else(|| {
1160        IrDriverError::TypeMismatch(format!("cast-from-enum input not a string: {v}"))
1161    })?;
1162    // Look up the variant in the enclosing IR's enum
1163    // declarations. The IR caries the source enum on the
1164    // expression's `from` field, but our typed mirror only
1165    // exposes the descriptor's `elements` list directly.
1166    let elements = match from_desc {
1167        TypeDescriptor::Enum { elements, .. } => elements,
1168        other => {
1169            return Err(IrDriverError::TypeMismatch(format!(
1170                "cast-from-enum 'from' descriptor not an Enum: {other:?}"
1171            )));
1172        }
1173    };
1174    let idx = elements.iter().position(|e| e == variant).ok_or_else(|| {
1175        IrDriverError::TypeMismatch(format!(
1176            "cast-from-enum: variant '{variant}' not in enum {elements:?}"
1177        ))
1178    })?;
1179    // Bound-check against the target Uint's max value.
1180    if let TypeDescriptor::Uint { maxval, .. } = to {
1181        if let Some(max) = maxval.as_u128() {
1182            if (idx as u128) > max {
1183                return Err(IrDriverError::TypeMismatch(format!(
1184                    "cast-from-enum: variant index {idx} exceeds Uint maxval {max}"
1185                )));
1186            }
1187        }
1188    }
1189    Ok(Value::Int(i128::from(idx as u64)))
1190}
1191
1192fn eval_cast_to_enum(
1193    state: &mut InterpState<'_>,
1194    to: &TypeDescriptor,
1195    value: &Expression,
1196) -> Result<Value> {
1197    // `(u as MyEnum)` — convert a numeric tag back to the
1198    // matching enum variant. The Compact runtime emits a
1199    // bounds check at the source level; we mirror that here.
1200    let v = eval_expression(state, value)?;
1201    let idx = super::descriptor::json_as_u128(&v)? as usize;
1202    let elements = match to {
1203        TypeDescriptor::Enum { elements, .. } => elements,
1204        other => {
1205            return Err(IrDriverError::TypeMismatch(format!(
1206                "cast-to-enum 'to' descriptor not an Enum: {other:?}"
1207            )));
1208        }
1209    };
1210    let variant = elements.get(idx).ok_or_else(|| {
1211        IrDriverError::TypeMismatch(format!(
1212            "cast-to-enum: tag {idx} out of range for enum (variants={})",
1213            elements.len()
1214        ))
1215    })?;
1216    Ok(Value::String(variant.clone()))
1217}
1218
1219fn eval_bytes_ref(
1220    state: &mut InterpState<'_>,
1221    value: &Expression,
1222    index: &Expression,
1223) -> Result<Value> {
1224    // Indexed read into a Bytes<N> — returns a single Uint<8>.
1225    let v = eval_expression(state, value)?;
1226    let bytes = v
1227        .as_bytes()
1228        .ok_or_else(|| IrDriverError::TypeMismatch(format!("bytes-ref input not bytes: {v}")))?;
1229    let idx_v = eval_expression(state, index)?;
1230    let idx = super::descriptor::json_as_u128(&idx_v)? as usize;
1231    let byte = *bytes.get(idx).ok_or_else(|| {
1232        IrDriverError::TypeMismatch(format!(
1233            "bytes-ref index {idx} out of bounds (len={})",
1234            bytes.len()
1235        ))
1236    })?;
1237    Ok(Value::Int(i128::from(byte)))
1238}
1239
1240fn eval_assign(state: &mut InterpState<'_>, name: &str, value: &Expression) -> Result<Value> {
1241    // Compact `name = expr` — re-bind the local. Used inside
1242    // `Expression::Seq` to fold computation into a previously
1243    // forward-declared `Statement::ConstDestructure` binding,
1244    // or to mutate a regular local. The expression's value is
1245    // the assigned value, so e.g. `(assign t = x; assert (>= t
1246    // y); t - y)` works.
1247    let v = eval_expression(state, value)?;
1248    state.locals.insert(name.to_owned(), v.clone());
1249    Ok(v)
1250}
1251
1252fn eval_enum_ref(of_type: &TypeDescriptor, variant: &str) -> Result<Value> {
1253    // Variant strings are produced as JSON strings; the type
1254    // descriptor is carried so encoders can re-resolve to a
1255    // u8 atom on the wire.
1256    match of_type {
1257        TypeDescriptor::Enum { elements, name } => {
1258            if !elements.iter().any(|v| v == variant) {
1259                return Err(IrDriverError::TypeMismatch(format!(
1260                    "enum {name} has no variant '{variant}' (variants: {elements:?})"
1261                )));
1262            }
1263            Ok(Value::String(variant.to_owned()))
1264        }
1265        other => Err(IrDriverError::TypeMismatch(format!(
1266            "enum-ref descriptor not an Enum: {other:?}"
1267        ))),
1268    }
1269}
1270
1271/// Evaluate `Expression::CastFromBytes` for any target type that the
1272/// JS runtime's `casts.js` supports: `Field`, `Uint<bits>`, and
1273/// `Bytes<L>` (no-op).
1274///
1275/// Bytes are read **little-endian** per
1276/// `compact-runtime/dist/casts.js::convertBytesTo*`. The input
1277/// expression's evaluated JSON form must be a hex-encoded byte string
1278/// of exactly `length` bytes.
1279fn eval_cast_from_bytes(
1280    state: &mut InterpState<'_>,
1281    to: &TypeDescriptor,
1282    length: u32,
1283    value: &Expression,
1284) -> Result<Value> {
1285    let v = eval_expression(state, value)?;
1286    let bytes: Vec<u8> = v
1287        .as_bytes()
1288        .ok_or_else(|| {
1289            IrDriverError::TypeMismatch(format!("cast-from-bytes input not bytes: {v}"))
1290        })?
1291        .to_vec();
1292    let length_u = length as usize;
1293    if bytes.len() != length_u {
1294        return Err(IrDriverError::TypeMismatch(format!(
1295            "cast-from-bytes Bytes<{length_u}> received {} bytes",
1296            bytes.len()
1297        )));
1298    }
1299    match to {
1300        TypeDescriptor::Field => {
1301            // Zero-pad to 32 bytes (Fr's LE repr length); validate.
1302            let mut buf = bytes;
1303            buf.resize(32, 0);
1304            if moonproof_ledger::transient_crypto::curve::Fr::from_le_bytes(&buf).is_none() {
1305                return Err(IrDriverError::TypeMismatch(format!(
1306                    "cast-from-bytes: value 0x{} exceeds Fr modulus",
1307                    hex::encode(&buf)
1308                )));
1309            }
1310            Ok(Value::Bytes(buf))
1311        }
1312        TypeDescriptor::Uint { maxval, .. } => {
1313            // Per `convertBytesToUint`: read LE, verify ≤ maxval.
1314            let max = maxval.as_u128().ok_or_else(|| {
1315                IrDriverError::TypeMismatch(format!(
1316                    "cast-from-bytes Uint maxval out of u128: {maxval}"
1317                ))
1318            })?;
1319            // Build the integer value LE.
1320            if bytes.len() > 16 {
1321                return Err(IrDriverError::unimplemented(format!(
1322                    "cast-from-bytes Bytes<{}> -> Uint exceeds u128 (would need bignum)",
1323                    bytes.len()
1324                )));
1325            }
1326            let mut buf = [0u8; 16];
1327            buf[..bytes.len()].copy_from_slice(&bytes);
1328            let n = u128::from_le_bytes(buf);
1329            if n > max {
1330                return Err(IrDriverError::TypeMismatch(format!(
1331                    "cast-from-bytes: value {n} exceeds Uint maxval {max}"
1332                )));
1333            }
1334            Ok(uint_value(n))
1335        }
1336        TypeDescriptor::Bytes { length: target_len } => {
1337            // Bytes<N> -> Bytes<M> is a width re-tag (N must equal M
1338            // since the source descriptor enforces exact length). We
1339            // already validated the input length above.
1340            if *target_len != length {
1341                return Err(IrDriverError::TypeMismatch(format!(
1342                    "cast-from-bytes Bytes<{length}> -> Bytes<{target_len}> width mismatch"
1343                )));
1344            }
1345            Ok(v)
1346        }
1347        TypeDescriptor::Alias { of, .. } => eval_cast_from_bytes(state, of, length, value),
1348        TypeDescriptor::Secp256k1Point
1349        | TypeDescriptor::Secp256r1Point
1350        | TypeDescriptor::Curve25519Point => {
1351            use moonproof_ledger::foreign_curve::{self as fc, ForeignCurve};
1352            let curve = match to {
1353                TypeDescriptor::Secp256k1Point => ForeignCurve::Secp256k1,
1354                TypeDescriptor::Secp256r1Point => ForeignCurve::Secp256r1,
1355                _ => ForeignCurve::Curve25519,
1356            };
1357            let pt = fc::from_bytes(curve, &bytes)
1358                .map_err(|e| IrDriverError::VmOp(format!("cast-from-bytes to {to:?}: {e}")))?;
1359            Ok(super::curve::affine_to_value(curve, &pt))
1360        }
1361        // `convertBytesToField`: a byte vector of any length, read
1362        // little-endian and reduced modulo the field. Only `Field`
1363        // itself refuses an out-of-range value, above.
1364        other => {
1365            let modulus = FieldType::of_descriptor(other)
1366                .and_then(super::curve::modulus_of)
1367                .ok_or_else(|| {
1368                    IrDriverError::unimplemented(format!("cast-from-bytes target type {other:?}"))
1369                })?;
1370            let m = num_bigint::BigUint::from_bytes_le(&modulus.to_le_bytes());
1371            let mut reduced = (num_bigint::BigUint::from_bytes_le(&bytes) % m).to_bytes_le();
1372            reduced.resize(32, 0);
1373            Ok(Value::Bytes(reduced))
1374        }
1375    }
1376}
1377
1378/// Evaluate a `Expression::Binop`. Compact's binops cover seven ops:
1379/// `+`, `-`, `*` (arithmetic), and `<`, `<=`, `>`, `>=` (comparison).
1380/// Equality is `Expression::Eq` / `Expression::Neq`, not a binop.
1381///
1382/// Both operands must be u128-shaped (the IR's `IntLit` / Uint
1383/// descriptor surface). Arithmetic uses `checked_*` so an overflow
1384/// surfaces as a `VmOp` error — matching Compact's semantics where
1385/// `Uint<N>` overflow is a runtime failure (the JS path's
1386/// `_descriptor_N` checks bounds at `toValue`).
1387/// Compare two runtime values for equality. When the IR carries the
1388/// shared static type (`of_type`), encode both sides through that
1389/// descriptor first so a Field returned from `Map.lookup` (decoded as
1390/// 32-byte LE bytes) compares equal to a Field literal expressed as
1391/// `SafeCast(Int(n))`. Without typed normalization the structural
1392/// `RuntimeValue` `PartialEq` treats `Bytes(...)` and `Int(_)` as
1393/// distinct even when they encode the same Field element.
1394fn value_to_fr_fast(value: &Value) -> Option<moonproof_ledger::transient_crypto::curve::Fr> {
1395    use moonproof_ledger::transient_crypto::curve::Fr;
1396    if let Some(b) = value.as_bytes() {
1397        Fr::from_le_bytes(b)
1398    } else if let Some(n) = value.as_u128() {
1399        Some(Fr::from(n))
1400    } else if let Some(s) = value.as_str() {
1401        s.parse::<u128>().ok().map(Fr::from)
1402    } else {
1403        None
1404    }
1405}
1406
1407fn values_equal_typed(
1408    of_type: Option<&TypeDescriptor>,
1409    left: &Value,
1410    right: &Value,
1411) -> Result<bool> {
1412    let Some(mut ty) = of_type else {
1413        return Ok(left == right);
1414    };
1415    while let TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } = ty {
1416        ty = of;
1417    }
1418    match ty {
1419        TypeDescriptor::Boolean => {
1420            if let (Value::Bool(a), Value::Bool(b)) = (left, right) {
1421                return Ok(a == b);
1422            }
1423        }
1424        TypeDescriptor::Uint { maxval, .. } => {
1425            if let Some(max) = maxval.as_u128() {
1426                if let (Ok(l), Ok(r)) = (
1427                    super::descriptor::json_as_u128(left),
1428                    super::descriptor::json_as_u128(right),
1429                ) {
1430                    if l <= max && r <= max {
1431                        return Ok(l == r);
1432                    }
1433                }
1434            }
1435        }
1436        TypeDescriptor::Counter => {
1437            if let (Ok(l), Ok(r)) = (
1438                super::descriptor::json_as_u128(left),
1439                super::descriptor::json_as_u128(right),
1440            ) {
1441                if l <= u128::from(u64::MAX) && r <= u128::from(u64::MAX) {
1442                    return Ok(l == r);
1443                }
1444            }
1445        }
1446        TypeDescriptor::Bytes { length } => {
1447            let expected = *length as usize;
1448            if let (Value::Bytes(a), Value::Bytes(b)) = (left, right) {
1449                if a.len() == expected && b.len() == expected {
1450                    return Ok(a == b);
1451                }
1452            }
1453        }
1454        TypeDescriptor::Field => {
1455            if let (Value::Int(a), Value::Int(b)) = (left, right) {
1456                if *a >= 0 && *b >= 0 {
1457                    return Ok(a == b);
1458                }
1459            }
1460            if let (Some(lf), Some(rf)) = (value_to_fr_fast(left), value_to_fr_fast(right)) {
1461                return Ok(lf == rf);
1462            }
1463        }
1464        TypeDescriptor::Enum { elements, .. } => {
1465            if let (Value::String(a), Value::String(b)) = (left, right) {
1466                if a == b {
1467                    if let Some(idx) = elements.iter().position(|v| v == a) {
1468                        if u8::try_from(idx).is_ok() {
1469                            return Ok(true);
1470                        }
1471                    }
1472                } else if let (Some(ia), Some(ib)) = (
1473                    elements.iter().position(|v| v == a),
1474                    elements.iter().position(|v| v == b),
1475                ) {
1476                    if u8::try_from(ia).is_ok() && u8::try_from(ib).is_ok() {
1477                        return Ok(ia == ib);
1478                    }
1479                }
1480            }
1481        }
1482        _ => {}
1483    }
1484    let l_av = super::descriptor::encode_literal(ty, left)?;
1485    let r_av = super::descriptor::encode_literal(ty, right)?;
1486    Ok(l_av == r_av)
1487}
1488
1489/// Arithmetic in a field is modular, never a checked overflow —
1490/// `built-ins.ts` implements `+`, `-` and `*` as `addField` / `subField`
1491/// / `mulField` and their secp counterparts, each reducing by the
1492/// field's modulus. Only `Uint<N>` treats overflow as a failure.
1493fn eval_field_binop(field_type: FieldType, op: &str, left: &Value, right: &Value) -> Result<Value> {
1494    let l = super::curve::value_as_u256(left, "field binop lhs")?;
1495    let r = super::curve::value_as_u256(right, "field binop rhs")?;
1496
1497    match super::curve::modulus_of(field_type) {
1498        // The native field reduces through `Fr` itself, so no modulus
1499        // is restated here.
1500        None => {
1501            use moonproof_ledger::transient_crypto::curve::Fr;
1502            let to_fr = |n: ethnum::U256, side: &str| -> Result<Fr> {
1503                Fr::from_le_bytes(&n.to_le_bytes()).ok_or_else(|| {
1504                    IrDriverError::TypeMismatch(format!("Field binop {side} out of range: {n}"))
1505                })
1506            };
1507            let lf = to_fr(l, "lhs")?;
1508            let rf = to_fr(r, "rhs")?;
1509            let out = match op {
1510                "+" => lf + rf,
1511                "-" => lf - rf,
1512                "*" => lf * rf,
1513                other => {
1514                    return Err(IrDriverError::unimplemented(format!(
1515                        "Field binop '{other}' (expected +, - or *)"
1516                    )))
1517                }
1518            };
1519            Ok(Value::Bytes(out.as_le_bytes()))
1520        }
1521        Some(modulus) => {
1522            let out = super::curve::modular_binop(modulus, op, l, r)?;
1523            Ok(Value::Bytes(out.to_le_bytes().to_vec()))
1524        }
1525    }
1526}
1527
1528/// JSON safe-integer range — a number up to `u64`, a decimal string above.
1529fn uint_value(n: u128) -> Value {
1530    match u64::try_from(n) {
1531        Ok(n) => Value::Int(i128::from(n)),
1532        Err(_) => Value::String(n.to_string()),
1533    }
1534}
1535
1536fn eval_binop(
1537    op: &str,
1538    of_type: Option<&TypeDescriptor>,
1539    left: &Value,
1540    right: &Value,
1541) -> Result<Value> {
1542    // Since 0.33 the arithmetic ops carry their operand type. When it
1543    // names a field, the operation is modular in that field.
1544    if let Some(t) = of_type {
1545        if let Some(field) = FieldType::of_descriptor(t) {
1546            return eval_field_binop(field, op, left, right);
1547        }
1548    }
1549    let l = super::descriptor::json_as_u128(left).map_err(|e| {
1550        IrDriverError::TypeMismatch(format!("binop '{op}' lhs not u128: {left} ({e})"))
1551    })?;
1552    let r = super::descriptor::json_as_u128(right).map_err(|e| {
1553        IrDriverError::TypeMismatch(format!("binop '{op}' rhs not u128: {right} ({e})"))
1554    })?;
1555    let arith = |out: Option<u128>, sym: &str| -> Result<Value> {
1556        let v = out
1557            .ok_or_else(|| IrDriverError::VmOp(format!("binop '{sym}' overflow: {l} {sym} {r}")))?;
1558        Ok(uint_value(v))
1559    };
1560    match op {
1561        "+" => arith(l.checked_add(r), "+"),
1562        "-" => arith(l.checked_sub(r), "-"),
1563        "*" => arith(l.checked_mul(r), "*"),
1564        "<" => Ok(Value::Bool(l < r)),
1565        "<=" => Ok(Value::Bool(l <= r)),
1566        ">" => Ok(Value::Bool(l > r)),
1567        ">=" => Ok(Value::Bool(l >= r)),
1568        other => Err(IrDriverError::unimplemented(format!(
1569            "Binop op '{other}' (expected one of +, -, *, <, <=, >, >=)"
1570        ))),
1571    }
1572}
1573
1574/// Build a JSON-shape default value for any `TypeDescriptor`.
1575/// Mirrors `encode_default` in the descriptor module — primitives
1576/// produce zero, structs/tuples produce nested defaults, enums pick
1577/// the first variant.
1578fn default_value_for_descriptor(descriptor: &TypeDescriptor) -> Result<Value> {
1579    match descriptor {
1580        TypeDescriptor::Boolean => Ok(Value::Bool(false)),
1581        TypeDescriptor::Uint { .. } | TypeDescriptor::Counter => Ok(Value::Int(0)),
1582        TypeDescriptor::Bytes { length } => Ok(Value::Bytes(vec![0u8; *length as usize])),
1583        TypeDescriptor::Field => Ok(Value::Bytes(vec![0u8; 32])),
1584        TypeDescriptor::Alias { of, .. } | TypeDescriptor::Cell { of } => {
1585            default_value_for_descriptor(of)
1586        }
1587        TypeDescriptor::Struct { elements, .. } => {
1588            let mut obj = std::collections::BTreeMap::<String, Value>::new();
1589            for f in elements {
1590                obj.insert(f.name.clone(), default_value_for_descriptor(&f.field_type)?);
1591            }
1592            Ok(Value::Object(obj))
1593        }
1594        TypeDescriptor::Tuple { types } => {
1595            let mut arr = Vec::with_capacity(types.len());
1596            for t in types {
1597                arr.push(default_value_for_descriptor(t)?);
1598            }
1599            Ok(Value::Array(arr))
1600        }
1601        TypeDescriptor::Vector { elt_type, length } => {
1602            let mut arr = Vec::with_capacity(*length as usize);
1603            for _ in 0..*length {
1604                arr.push(default_value_for_descriptor(elt_type)?);
1605            }
1606            Ok(Value::Array(arr))
1607        }
1608        TypeDescriptor::Enum { elements, .. } => {
1609            // First variant is the default. (Compact convention —
1610            // matches what `_descriptor_N.alignment().toBytes(default)`
1611            // produces in the JS emit.)
1612            elements
1613                .first()
1614                .map(|s| Value::String(s.clone()))
1615                .ok_or_else(|| IrDriverError::InvalidIr("enum descriptor has no variants".into()))
1616        }
1617        TypeDescriptor::Opaque { ts_type } => match ts_type.as_str() {
1618            "string" => Ok(Value::String(String::new())),
1619            "Uint8Array" => Ok(Value::Bytes(Vec::new())),
1620            other => Err(IrDriverError::unimplemented(format!(
1621                "default_value for Opaque<{other}>"
1622            ))),
1623        },
1624        // Curve fields and points: the decoded wire default, so the
1625        // value is whatever `encode_default` puts on the wire (zero, and
1626        // each curve's identity point).
1627        TypeDescriptor::JubjubScalar
1628        | TypeDescriptor::Secp256k1Base
1629        | TypeDescriptor::Secp256k1Scalar
1630        | TypeDescriptor::Secp256r1Base
1631        | TypeDescriptor::Secp256r1Scalar
1632        | TypeDescriptor::Curve25519Base
1633        | TypeDescriptor::Curve25519Scalar
1634        | TypeDescriptor::JubjubPoint
1635        | TypeDescriptor::Secp256k1Point
1636        | TypeDescriptor::Secp256r1Point
1637        | TypeDescriptor::Curve25519Point => {
1638            let av = super::descriptor::encode_default(descriptor)?;
1639            super::descriptor::decode_aligned_value(descriptor, &av.value.0, &mut 0)
1640        }
1641        other => Err(IrDriverError::unimplemented(format!(
1642            "default_value for descriptor {other:?}"
1643        ))),
1644    }
1645}
1646
1647/// Evaluate `Expression::New` — construct a struct/tuple/vector
1648/// from positional arguments. Compact's `new` operator carries a
1649/// descriptor + a list of arg expressions whose order matches the
1650/// type's field order.
1651fn eval_new(
1652    state: &mut InterpState<'_>,
1653    of_type: &TypeDescriptor,
1654    arguments: &[Expression],
1655) -> Result<Value> {
1656    let arg_values = arguments
1657        .iter()
1658        .map(|e| eval_expression(state, e))
1659        .collect::<Result<Vec<Value>>>()?;
1660    construct(of_type, arg_values)
1661}
1662
1663/// The value `new T(args)` builds from already-evaluated arguments: a
1664/// struct is an object keyed by field name, a tuple or vector an array.
1665pub(crate) fn construct(of_type: &TypeDescriptor, arg_values: Vec<Value>) -> Result<Value> {
1666    match of_type {
1667        TypeDescriptor::Struct { elements, name } => {
1668            if arg_values.len() != elements.len() {
1669                return Err(IrDriverError::ArgCount {
1670                    context: format!("new {name}"),
1671                    expected: elements.len(),
1672                    got: arg_values.len(),
1673                });
1674            }
1675            let mut obj = std::collections::BTreeMap::<String, Value>::new();
1676            for (field, v) in elements.iter().zip(arg_values) {
1677                obj.insert(field.name.clone(), v);
1678            }
1679            Ok(Value::Object(obj))
1680        }
1681        TypeDescriptor::Tuple { types } => {
1682            if arg_values.len() != types.len() {
1683                return Err(IrDriverError::ArgCount {
1684                    context: "new tuple".into(),
1685                    expected: types.len(),
1686                    got: arg_values.len(),
1687                });
1688            }
1689            Ok(Value::Array(arg_values))
1690        }
1691        TypeDescriptor::Vector { length, .. } => {
1692            if arg_values.len() != *length as usize {
1693                return Err(IrDriverError::ArgCount {
1694                    context: "new vector".into(),
1695                    expected: *length as usize,
1696                    got: arg_values.len(),
1697                });
1698            }
1699            Ok(Value::Array(arg_values))
1700        }
1701        TypeDescriptor::Alias { of, .. } => construct(of, arg_values),
1702        other => Err(IrDriverError::unimplemented(format!(
1703            "Expression::New for descriptor {other:?}"
1704        ))),
1705    }
1706}
1707
1708/// Pre-parsed function target for [`eval_fold`] / [`eval_map`].
1709///
1710/// Decoded **once** before the loop begins so multi-iteration folds (such
1711/// as depth-8 Merkle path roots) never re-deserialize the lambda AST or
1712/// clone a `CircuitBody` per iteration.
1713enum PreparedFunction<'ir> {
1714    Fref(&'ir CircuitBody),
1715    Lambda {
1716        arg_names: Vec<&'ir str>,
1717        body: Box<Statement>,
1718    },
1719}
1720
1721fn prepare_function<'ir>(
1722    ir: &'ir MoonIr,
1723    index: Option<&IrIndex>,
1724    function: &'ir Value,
1725) -> Result<PreparedFunction<'ir>> {
1726    let obj = function
1727        .as_object()
1728        .ok_or_else(|| IrDriverError::InvalidIr(format!("function not an object: {function}")))?;
1729    let kind = obj
1730        .get("kind")
1731        .and_then(Value::as_str)
1732        .ok_or_else(|| IrDriverError::InvalidIr(format!("function missing 'kind': {function}")))?;
1733    match kind {
1734        "fref" => {
1735            let name = obj
1736                .get("name")
1737                .and_then(Value::as_str)
1738                .ok_or_else(|| IrDriverError::InvalidIr("fref function missing 'name'".into()))?;
1739            let callee = index
1740                .and_then(|idx| idx.first_circuit(ir, name))
1741                .or_else(|| ir.circuits.iter().find(|c| c.name == name))
1742                .ok_or_else(|| {
1743                    IrDriverError::unimplemented(format!("fref '{name}' not found in circuits[]"))
1744                })?;
1745            Ok(PreparedFunction::Fref(callee))
1746        }
1747        "lambda" => {
1748            let arg_defs = obj
1749                .get("arguments")
1750                .and_then(Value::as_array)
1751                .ok_or_else(|| IrDriverError::InvalidIr("lambda missing 'arguments'".into()))?;
1752            let mut arg_names = Vec::with_capacity(arg_defs.len());
1753            for def in arg_defs {
1754                let name = def
1755                    .get("name")
1756                    .and_then(Value::as_str)
1757                    .ok_or_else(|| IrDriverError::InvalidIr("lambda arg missing 'name'".into()))?;
1758                arg_names.push(name);
1759            }
1760            let body_v = obj
1761                .get("body")
1762                .ok_or_else(|| IrDriverError::InvalidIr("lambda missing 'body'".into()))?;
1763            let body: Statement = decode_value_as::<Statement>(body_v)
1764                .map_err(|e| IrDriverError::InvalidIr(format!("lambda body deserialize: {e}")))?;
1765            Ok(PreparedFunction::Lambda {
1766                arg_names,
1767                body: Box::new(body),
1768            })
1769        }
1770        other => Err(IrDriverError::unimplemented(format!(
1771            "function kind '{other}'"
1772        ))),
1773    }
1774}
1775
1776/// Evaluate `Expression::Fold`: reduce a parallel zip of input vectors
1777/// using the supplied function with the running accumulator.
1778///
1779/// Semantics (matches Compact's `for (const v of vec) { ... }` lowering):
1780/// 1. Evaluate `initial.value` → accumulator.
1781/// 2. Evaluate each `arguments[k].value` → input array of length `length`.
1782/// 3. For each `i` in `0..length`: invoke `function(acc, arr1[i], ..., argN[i])`,
1783///    take the result as the new accumulator.
1784/// 4. Return the final accumulator.
1785fn eval_fold(
1786    state: &mut InterpState<'_>,
1787    length: &moonproof_runtime_ir::ir::IntLit,
1788    function: &Value,
1789    initial: &Value,
1790    arguments: &[Value],
1791) -> Result<Value> {
1792    let len = length
1793        .as_u32()
1794        .ok_or_else(|| IrDriverError::InvalidIr(format!("fold length not u32: {length}")))?
1795        as usize;
1796    let init_obj = initial
1797        .as_object()
1798        .ok_or_else(|| IrDriverError::InvalidIr(format!("fold.initial not object: {initial}")))?;
1799    let init_value_expr = init_obj
1800        .get("value")
1801        .ok_or_else(|| IrDriverError::InvalidIr("fold.initial missing 'value'".into()))?;
1802    let init_expr: Expression = decode_value_as::<Expression>(init_value_expr)
1803        .map_err(|e| IrDriverError::InvalidIr(format!("fold.initial.value deserialize: {e}")))?;
1804    let mut acc = eval_expression(state, &init_expr)?;
1805    let arg_arrays = eval_map_arguments(state, arguments)?;
1806    if len == 0 {
1807        return Ok(acc);
1808    }
1809    let prepared = prepare_function(state.ir, state.index, function)?;
1810    match prepared {
1811        PreparedFunction::Fref(callee) => {
1812            let mut call_args: Vec<Value> = Vec::with_capacity(1 + arg_arrays.len());
1813            for i in 0..len {
1814                call_args.clear();
1815                call_args.push(acc);
1816                for arr in &arg_arrays {
1817                    let elt = arr.get(i).cloned().ok_or_else(|| {
1818                        IrDriverError::TypeMismatch(format!(
1819                            "fold input array shorter than length {len} at index {i}"
1820                        ))
1821                    })?;
1822                    call_args.push(elt);
1823                }
1824                acc = eval_circuit_call(state, callee, &call_args)?;
1825            }
1826            Ok(acc)
1827        }
1828        PreparedFunction::Lambda { arg_names, body } => {
1829            let expected_arity = 1 + arg_arrays.len();
1830            if arg_names.len() != expected_arity {
1831                return Err(IrDriverError::ArgCount {
1832                    context: "lambda invocation".into(),
1833                    expected: arg_names.len(),
1834                    got: expected_arity,
1835                });
1836            }
1837            let saved_args = std::mem::replace(
1838                &mut state.args,
1839                VarMap::with_capacity_and_hasher(expected_arity, FxBuildHasher),
1840            );
1841            let saved_locals = std::mem::take(&mut state.locals);
1842            let mut run_res: Result<()> = Ok(());
1843            for i in 0..len {
1844                state.args.clear();
1845                state.locals.clear();
1846                state.args.insert(
1847                    arg_names[0].to_owned(),
1848                    std::mem::replace(&mut acc, Value::Null),
1849                );
1850                for (name, arr) in arg_names[1..].iter().zip(&arg_arrays) {
1851                    let Some(elt) = arr.get(i) else {
1852                        run_res = Err(IrDriverError::TypeMismatch(format!(
1853                            "fold input array shorter than length {len} at index {i}"
1854                        )));
1855                        acc = Value::Null;
1856                        break;
1857                    };
1858                    state.args.insert((*name).to_owned(), elt.clone());
1859                }
1860                if run_res.is_err() {
1861                    break;
1862                }
1863                match run_statement(state, &body) {
1864                    Ok(v) => acc = v,
1865                    Err(e) => {
1866                        run_res = Err(e);
1867                        acc = Value::Null;
1868                        break;
1869                    }
1870                }
1871            }
1872            state.args = saved_args;
1873            state.locals = saved_locals;
1874            run_res.map(|()| acc)
1875        }
1876    }
1877}
1878
1879/// Evaluate `Expression::Map`: zip-apply the function over input
1880/// vectors, collecting results into a fresh array.
1881fn eval_map(
1882    state: &mut InterpState<'_>,
1883    length: &moonproof_runtime_ir::ir::IntLit,
1884    function: &Value,
1885    arguments: &[Value],
1886) -> Result<Value> {
1887    let len = length
1888        .as_u32()
1889        .ok_or_else(|| IrDriverError::InvalidIr(format!("map length not u32: {length}")))?
1890        as usize;
1891    let arg_arrays = eval_map_arguments(state, arguments)?;
1892    let mut out: Vec<Value> = Vec::with_capacity(len);
1893    if len == 0 {
1894        return Ok(Value::Array(out));
1895    }
1896    let prepared = prepare_function(state.ir, state.index, function)?;
1897    match prepared {
1898        PreparedFunction::Fref(callee) => {
1899            let mut call_args: Vec<Value> = Vec::with_capacity(arg_arrays.len());
1900            for i in 0..len {
1901                call_args.clear();
1902                for arr in &arg_arrays {
1903                    let elt = arr.get(i).cloned().ok_or_else(|| {
1904                        IrDriverError::TypeMismatch(format!(
1905                            "map input array shorter than length {len} at index {i}"
1906                        ))
1907                    })?;
1908                    call_args.push(elt);
1909                }
1910                out.push(eval_circuit_call(state, callee, &call_args)?);
1911            }
1912            Ok(Value::Array(out))
1913        }
1914        PreparedFunction::Lambda { arg_names, body } => {
1915            let expected_arity = arg_arrays.len();
1916            if arg_names.len() != expected_arity {
1917                return Err(IrDriverError::ArgCount {
1918                    context: "lambda invocation".into(),
1919                    expected: arg_names.len(),
1920                    got: expected_arity,
1921                });
1922            }
1923            let saved_args = std::mem::replace(
1924                &mut state.args,
1925                VarMap::with_capacity_and_hasher(expected_arity, FxBuildHasher),
1926            );
1927            let saved_locals = std::mem::take(&mut state.locals);
1928            let mut run_res: Result<()> = Ok(());
1929            for i in 0..len {
1930                state.args.clear();
1931                state.locals.clear();
1932                for (name, arr) in arg_names.iter().zip(&arg_arrays) {
1933                    let Some(elt) = arr.get(i) else {
1934                        run_res = Err(IrDriverError::TypeMismatch(format!(
1935                            "map input array shorter than length {len} at index {i}"
1936                        )));
1937                        break;
1938                    };
1939                    state.args.insert((*name).to_owned(), elt.clone());
1940                }
1941                if run_res.is_err() {
1942                    break;
1943                }
1944                match run_statement(state, &body) {
1945                    Ok(v) => out.push(v),
1946                    Err(e) => {
1947                        run_res = Err(e);
1948                        break;
1949                    }
1950                }
1951            }
1952            state.args = saved_args;
1953            state.locals = saved_locals;
1954            run_res.map(|()| Value::Array(out))
1955        }
1956    }
1957}
1958
1959/// Deserialize a `RuntimeValue` (typically holding a nested IR-fragment
1960/// as `Object`/`Array`/`Bytes`) into any typed `serde::Deserialize`
1961/// target, straight off the in-memory tree.
1962///
1963/// Byte-string fidelity is preserved without a CBOR detour: the
1964/// [`from_runtime_value`](moonproof_runtime_ir::from_runtime_value)
1965/// deserializer drives `Bytes` through `visit_bytes`, so a
1966/// `RuntimeValue::Bytes` reaches the target as bytes (not the
1967/// `hex::encode` string the JSON bridge would force). This replaced a
1968/// `ciborium` serialize+parse round-trip that ran on every vm-op `ref`
1969/// decode, lambda-body decode, and fold/map argument.
1970pub(crate) fn decode_value_as<T: serde::de::DeserializeOwned>(v: &Value) -> Result<T> {
1971    moonproof_runtime_ir::from_runtime_value(v)
1972        .map_err(|e| IrDriverError::InvalidIr(format!("RuntimeValue → typed decode: {e}")))
1973}
1974
1975/// Helper for [`eval_fold`] / [`eval_map`]: evaluate each
1976/// `MapArgument`'s `value` Expression to an array. Each `MapArgument`
1977/// JSON has `{value: <expr>, type: <descriptor>, cast-to: <descriptor>}`;
1978/// today we evaluate only `value` (the cast-to descriptor is
1979/// type-system metadata that doesn't change runtime semantics in our
1980/// JSON-typed interpretation).
1981fn eval_map_arguments(state: &mut InterpState<'_>, arguments: &[Value]) -> Result<Vec<Vec<Value>>> {
1982    let mut arrs: Vec<Vec<Value>> = Vec::with_capacity(arguments.len());
1983    for arg in arguments {
1984        let obj = arg.as_object().ok_or_else(|| {
1985            IrDriverError::InvalidIr(format!("map/fold argument not object: {arg}"))
1986        })?;
1987        let value_v = obj
1988            .get("value")
1989            .ok_or_else(|| IrDriverError::InvalidIr("map/fold argument missing 'value'".into()))?;
1990        let value_expr: Expression = decode_value_as::<Expression>(value_v)
1991            .map_err(|e| IrDriverError::InvalidIr(format!("map/fold argument deserialize: {e}")))?;
1992        let v = eval_expression(state, &value_expr)?;
1993        let arr = match v {
1994            Value::Array(a) => a,
1995            Value::Bytes(b) => b
1996                .into_iter()
1997                .map(|byte| Value::Int(i128::from(byte)))
1998                .collect(),
1999            other => {
2000                return Err(IrDriverError::TypeMismatch(format!(
2001                    "map/fold argument value not array: {other}"
2002                )));
2003            }
2004        };
2005        arrs.push(arr);
2006    }
2007    Ok(arrs)
2008}
2009
2010/// Evaluate a Call expression. Routes to:
2011///
2012/// 1. Contract `witnesses[]` entries — the host callback,
2013///    appending the observed value to the private transcript and
2014///    rotating private state.
2015/// 2. `natives[]` with `class=witness` — also routed through the
2016///    host callback (e.g. `ownPublicKey`); the IR places these in
2017///    `natives` rather than `witnesses` because they're host-side
2018///    builtins, not contract-defined witnesses, but the binding
2019///    mechanism is identical.
2020/// 3. `natives[]` with `class=circuit` — pure host functions
2021///    (`persistentHash`, `transientHash`, etc.). Implemented
2022///    directly in [`eval_native_circuit`].
2023/// 4. Entries in `circuits[]` — non-exported helpers like
2024///    `left()`, `assertOnlyOwner()`. Recursively walks the body
2025///    with a fresh local scope; effects on contract state and
2026///    private state propagate to the caller.
2027fn eval_call(
2028    state: &mut InterpState<'_>,
2029    function: &str,
2030    function_uniq: Option<u64>,
2031    arguments: &[Expression],
2032) -> Result<Value> {
2033    let arg_values: Result<Vec<Value>> = arguments
2034        .iter()
2035        .map(|e| eval_expression(state, e))
2036        .collect();
2037    let arg_values = arg_values?;
2038
2039    // Contract witness — appears in `witnesses[]`. Witnesses trait
2040    // takes RuntimeValue end-to-end; no JSON intermediate. The
2041    // `Value::Array` wrapper is built only on the witness paths that
2042    // actually pass it to the host callback — circuit-helper and
2043    // native-circuit calls (the common case) skip the clone.
2044    let witness_entry = if let Some(idx) = state.index.filter(|idx| idx.matches_ir(state.ir)) {
2045        idx.witness_with_plan(state.ir, function)
2046    } else {
2047        state
2048            .ir
2049            .witnesses
2050            .iter()
2051            .find(|w| w.name == function)
2052            .map(|w| (w, None))
2053    };
2054    if let Some((witness_def, result_plan)) = witness_entry {
2055        let args_json = Value::Array(arg_values.clone());
2056        let result = state
2057            .witnesses
2058            .invoke(function, &args_json, &state.private_state)?;
2059        if state.trace_level.includes_details() {
2060            if let Some(trace) = state.trace.as_deref_mut() {
2061                trace.push(crate::trace::TraceEvent::WitnessCall {
2062                    contract: state.contract_label.clone(),
2063                    circuit: state.circuit_name.clone(),
2064                    witness: function.to_owned(),
2065                    args: args_json,
2066                    observed: result.observed.clone(),
2067                    depth: state.trace_depth,
2068                });
2069            }
2070        }
2071        let observed_av =
2072            encode_with_plan(result_plan, &witness_def.result_type, &result.observed)?;
2073        state.private_transcript_outputs.push(observed_av);
2074        state.private_state = result.next_private_state;
2075        bridge_zswap_kernel_witness(state, function, &witness_def.arguments, &arg_values)?;
2076        return Ok(result.observed);
2077    }
2078
2079    if let Some(native_def) =
2080        select_native(state.ir, state.index, function, function_uniq, &arg_values)?
2081    {
2082        return eval_native_call(state, function, native_def, &arg_values);
2083    }
2084    if let Some(circuit) = select_circuit(
2085        state.ir,
2086        state.index,
2087        function,
2088        function_uniq,
2089        arg_values.len(),
2090    )? {
2091        return eval_circuit_call(state, circuit, &arg_values);
2092    }
2093
2094    Err(IrDriverError::unimplemented(format!(
2095        "Call to unknown function '{function}' (not in witnesses, natives, or circuits)"
2096    )))
2097}
2098
2099/// The `natives[]` entry a call names, if any.
2100///
2101/// Compactc emits one `natives[]` entry per generic instantiation
2102/// of the same source-level native (e.g. `persistentCommit<Bytes<13>>`
2103/// and `persistentCommit<RoundPreimage>` both register as
2104/// `name: "persistentCommit"`). Since the IR's `Expression::Call`
2105/// carries only the source name, we resolve the right
2106/// instantiation by structural argument match: try each candidate
2107/// and pick the first one whose declared `arg_type`s successfully
2108/// encode the runtime values via `encode_literal`. This matches
2109/// what the JS path does with separate monomorphized helpers
2110/// (e.g. `_persistentCommit_0` / `_persistentCommit_1`).
2111fn select_native<'ir>(
2112    ir: &'ir MoonIr,
2113    index: Option<&IrIndex>,
2114    function: &str,
2115    function_uniq: Option<u64>,
2116    arg_values: &[Value],
2117) -> Result<Option<&'ir moonproof_runtime_ir::ir::Native>> {
2118    if let Some(idx) = index.filter(|idx| idx.matches_ir(ir)) {
2119        if let Some(uniq) = function_uniq {
2120            if let Some(def) = idx.native_by_uniq(ir, uniq) {
2121                if def.name == function {
2122                    return Ok(Some(def));
2123                }
2124            }
2125        }
2126        let Some(indices) = idx.native_indices_by_name(ir, function) else {
2127            return Ok(None);
2128        };
2129        if indices.len() == 1 {
2130            return Ok(Some(&ir.natives[indices[0]]));
2131        }
2132        return indices
2133            .iter()
2134            .map(|&i| &ir.natives[i])
2135            .find(|cand| {
2136                cand.arguments.len() == arg_values.len()
2137                    && cand
2138                        .arguments
2139                        .iter()
2140                        .zip(arg_values.iter())
2141                        .all(|(arg_def, v)| encode_literal(&arg_def.arg_type, v).is_ok())
2142            })
2143            .map(Some)
2144            .ok_or_else(|| {
2145                IrDriverError::TypeMismatch(format!(
2146                    "no native '{function}' matches {} runtime arg(s); \
2147                     {} candidates rejected on encode",
2148                    arg_values.len(),
2149                    indices.len()
2150                ))
2151            });
2152    }
2153
2154    let native_candidates: Vec<&moonproof_runtime_ir::ir::Native> =
2155        ir.natives.iter().filter(|n| n.name == function).collect();
2156    if native_candidates.is_empty() {
2157        return Ok(None);
2158    }
2159    let by_uniq = function_uniq.and_then(|uniq| {
2160        native_candidates
2161            .iter()
2162            .copied()
2163            .find(|n| n.internal_uniq == Some(uniq))
2164    });
2165    let native_def = if let Some(def) = by_uniq {
2166        def
2167    } else if native_candidates.len() == 1 {
2168        native_candidates[0]
2169    } else {
2170        // Multiple monomorphized entries — pick the one whose
2171        // argument descriptors match the runtime values.
2172        native_candidates
2173            .iter()
2174            .copied()
2175            .find(|cand| {
2176                cand.arguments.len() == arg_values.len()
2177                    && cand
2178                        .arguments
2179                        .iter()
2180                        .zip(arg_values.iter())
2181                        .all(|(arg_def, v)| encode_literal(&arg_def.arg_type, v).is_ok())
2182            })
2183            .ok_or_else(|| {
2184                IrDriverError::TypeMismatch(format!(
2185                    "no native '{function}' matches {} runtime arg(s); \
2186                     {} candidates rejected on encode",
2187                    arg_values.len(),
2188                    native_candidates.len()
2189                ))
2190            })?
2191    };
2192    Ok(Some(native_def))
2193}
2194
2195#[inline]
2196fn encode_with_plan(
2197    plan: Option<&FabPlan>,
2198    descriptor: &TypeDescriptor,
2199    value: &Value,
2200) -> Result<AlignedValue> {
2201    if let Some(plan) = plan {
2202        plan.encode(value)
2203    } else {
2204        encode_literal(descriptor, value)
2205    }
2206}
2207
2208/// Dispatch a call to a native by its canonical intrinsic name and class.
2209fn eval_native_call(
2210    state: &mut InterpState<'_>,
2211    function: &str,
2212    native_def: &moonproof_runtime_ir::ir::Native,
2213    arg_values: &[Value],
2214) -> Result<Value> {
2215    let resolved = native_def.resolve_intrinsic();
2216    let intrinsic = if resolved.is_empty() {
2217        moonproof_runtime_ir::canonical_intrinsic_name(function)
2218    } else {
2219        moonproof_runtime_ir::canonical_intrinsic_name(resolved)
2220    };
2221    let plans = state
2222        .index
2223        .and_then(|idx| idx.native_plans(state.ir, native_def));
2224    let result_plan = plans.and_then(|p| p.result.as_ref());
2225
2226    // Check runtime-provided witness intrinsics first (regardless of whether
2227    // the frontend tagged them as `class: "witness"` or a semantic class such
2228    // as `"context"` / `"zswap"`).
2229    //
2230    // `ownPublicKey` reads the caller's coin public key from the call context,
2231    // as compact-runtime's does; the contract's witnesses have no say in it.
2232    if intrinsic == "ownPublicKey" {
2233        let mut key = std::collections::BTreeMap::new();
2234        key.insert(
2235            "bytes".to_owned(),
2236            Value::Bytes(state.next_zswap_local_state.coin_public_key.0.to_vec()),
2237        );
2238        let observed = Value::Object(key);
2239        let observed_av = encode_with_plan(result_plan, &native_def.result_type, &observed)?;
2240        state.private_transcript_outputs.push(observed_av);
2241        return Ok(observed);
2242    }
2243    // Kernel witnesses (`createZswapOutput` / `createZswapInput`) are
2244    // runtime-side primitives: they observe `[]` (empty tuple), the host
2245    // side-effect is recorded by `bridge_zswap_kernel_witness`, and the
2246    // user's Witnesses backend has nothing to contribute.
2247    if matches!(intrinsic, "createZswapOutput" | "createZswapInput") {
2248        let observed = Value::Array(Vec::new());
2249        let observed_av = encode_with_plan(result_plan, &native_def.result_type, &observed)?;
2250        state.private_transcript_outputs.push(observed_av);
2251        bridge_zswap_kernel_witness(state, intrinsic, &native_def.arguments, arg_values)?;
2252        return Ok(observed);
2253    }
2254
2255    match native_def.class.as_str() {
2256        "witness" => {
2257            let args_json = Value::Array(arg_values.to_vec());
2258            let result = state
2259                .witnesses
2260                .invoke(function, &args_json, &state.private_state)?;
2261            let observed_av =
2262                encode_with_plan(result_plan, &native_def.result_type, &result.observed)?;
2263            state.private_transcript_outputs.push(observed_av);
2264            state.private_state = result.next_private_state;
2265            bridge_zswap_kernel_witness(state, function, &native_def.arguments, arg_values)?;
2266            Ok(result.observed)
2267        }
2268        "circuit" | "hash" | "commit" | "crypto" | "curve" | "pure" => eval_native_circuit(
2269            intrinsic,
2270            arg_values,
2271            &native_def.arguments,
2272            plans,
2273            &native_def.result_type,
2274        ),
2275        other => Err(IrDriverError::unimplemented(format!(
2276            "native class '{other}' for '{function}'"
2277        ))),
2278    }
2279}
2280
2281/// The non-exported circuit helper a call names, if any.
2282///
2283/// Compactc emits one `circuits[]` entry per generic instantiation
2284/// of the same source-level circuit (e.g. `none<Opaque<string>>`,
2285/// `none<ShieldedCoinInfo>`, `none<ZswapCoinPublicKey>` all share
2286/// `name: "none"`). The patched fork emits `internal-uniq` on each
2287/// definition and `function-uniq` on each call site so consumers
2288/// can disambiguate. When `function_uniq` is present, prefer the
2289/// candidate whose `internal_uniq` matches; otherwise fall back to
2290/// the first match by name (older fixtures without uniq).
2291fn select_circuit<'ir>(
2292    ir: &'ir MoonIr,
2293    index: Option<&IrIndex>,
2294    function: &str,
2295    function_uniq: Option<u64>,
2296    arity: usize,
2297) -> Result<Option<&'ir CircuitBody>> {
2298    if let Some(idx) = index.filter(|idx| idx.matches_ir(ir)) {
2299        if let Some(uniq) = function_uniq {
2300            if let Some(c) = idx.circuit_by_uniq(ir, uniq) {
2301                if c.name == function {
2302                    return Ok(Some(c));
2303                }
2304            }
2305            let Some(indices) = idx.circuit_indices_by_name(ir, function) else {
2306                return Ok(None);
2307            };
2308            return Err(IrDriverError::TypeMismatch(format!(
2309                "no circuit '{function}' with uniq {uniq} \
2310                 (got {} candidates with uniqs {:?})",
2311                indices.len(),
2312                indices
2313                    .iter()
2314                    .map(|&i| ir.circuits[i].internal_uniq)
2315                    .collect::<Vec<_>>()
2316            )));
2317        }
2318        let Some(indices) = idx.circuit_indices_by_name(ir, function) else {
2319            return Ok(None);
2320        };
2321        if indices.len() == 1 {
2322            return Ok(Some(&ir.circuits[indices[0]]));
2323        }
2324        let mut by_arity = indices
2325            .iter()
2326            .map(|&i| &ir.circuits[i])
2327            .filter(|c| c.arguments.len() == arity);
2328        let chosen = if let (Some(only), None) = (by_arity.next(), by_arity.next()) {
2329            only
2330        } else {
2331            &ir.circuits[indices[0]]
2332        };
2333        return Ok(Some(chosen));
2334    }
2335
2336    let circuit_candidates: Vec<&CircuitBody> =
2337        ir.circuits.iter().filter(|c| c.name == function).collect();
2338    if circuit_candidates.is_empty() {
2339        return Ok(None);
2340    }
2341    let circuit = if let Some(uniq) = function_uniq {
2342        circuit_candidates
2343            .iter()
2344            .copied()
2345            .find(|c| c.internal_uniq == Some(uniq))
2346            .ok_or_else(|| {
2347                IrDriverError::TypeMismatch(format!(
2348                    "no circuit '{function}' with uniq {uniq} \
2349                     (got {} candidates with uniqs {:?})",
2350                    circuit_candidates.len(),
2351                    circuit_candidates
2352                        .iter()
2353                        .map(|c| c.internal_uniq)
2354                        .collect::<Vec<_>>()
2355                ))
2356            })?
2357    } else {
2358        // No call-site uniq (e.g. a lifted IR whose producer
2359        // doesn't thread `function-uniq`). For an overloaded
2360        // name, prefer the unique candidate whose arity matches
2361        // this call; fall back to the first by name when arity
2362        // doesn't pin exactly one (single candidate, or
2363        // same-arity overloads).
2364        let mut by_arity = circuit_candidates
2365            .iter()
2366            .copied()
2367            .filter(|c| c.arguments.len() == arity);
2368        if let (Some(only), None) = (by_arity.next(), by_arity.next()) {
2369            only
2370        } else {
2371            circuit_candidates[0]
2372        }
2373    };
2374    Ok(Some(circuit))
2375}
2376
2377/// Recursively run another circuit's body. The callee shares the
2378/// caller's contract state, address, and witnesses (so its ADT-ops
2379/// affect the caller's state and its witness calls rotate the
2380/// caller's private state) but gets a fresh `locals` map and a
2381/// fresh `args` map seeded from this call's arguments.
2382fn eval_circuit_call(
2383    caller: &mut InterpState<'_>,
2384    circuit: &CircuitBody,
2385    arg_values: &[Value],
2386) -> Result<Value> {
2387    if arg_values.len() != circuit.arguments.len() {
2388        return Err(IrDriverError::ArgCount {
2389            context: format!("circuit call '{}'", circuit.name),
2390            expected: circuit.arguments.len(),
2391            got: arg_values.len(),
2392        });
2393    }
2394    let mut callee_args = VarMap::with_capacity_and_hasher(circuit.arguments.len(), FxBuildHasher);
2395    for (def, v) in circuit.arguments.iter().zip(arg_values.iter()) {
2396        callee_args.insert(def.name.clone(), v.clone());
2397    }
2398    // Swap only `args` and `locals` in place: every other field
2399    // (`contract_state`, `private_state`, transcripts, `effects`,
2400    // `witnesses`, `coin_commitments`, `call_tree`) is shared
2401    // mutably with the helper call and needs zero cloning.
2402    if let Some(cov) = caller.coverage.as_deref_mut() {
2403        cov.record_circuit(circuit);
2404    }
2405    let saved_args = std::mem::replace(&mut caller.args, callee_args);
2406    let saved_locals = std::mem::take(&mut caller.locals);
2407    let result = run_statement(caller, &circuit.body);
2408    caller.args = saved_args;
2409    caller.locals = saved_locals;
2410    result
2411}
2412
2413/// A call to a circuit of another contract, made as compact-runtime's
2414/// `crossContractCall` makes it: the callee runs against its own state
2415/// with no witnesses, then the caller takes the callee's result and a
2416/// fresh commitment randomness as private transcript outputs and claims
2417/// the call.
2418fn eval_contract_call(
2419    state: &mut InterpState<'_>,
2420    circuit: &str,
2421    address: &Expression,
2422    address_type: &TypeDescriptor,
2423    arguments: &[Expression],
2424) -> Result<Value> {
2425    let address_value = eval_expression(state, address)?;
2426    let arg_values = arguments
2427        .iter()
2428        .map(|e| eval_expression(state, e))
2429        .collect::<Result<Vec<_>>>()?;
2430    eval_contract_call_values(state, circuit, &address_value, address_type, arg_values)
2431}
2432
2433pub(crate) fn eval_contract_call_values(
2434    state: &mut InterpState<'_>,
2435    circuit: &str,
2436    address_value: &Value,
2437    address_type: &TypeDescriptor,
2438    arg_values: Vec<Value>,
2439) -> Result<Value> {
2440    let callee_address = contract_address_of(address_value)?;
2441    let own_address = state.contract_address;
2442    let (interface, declared) = declared_contract_type(address_type)?;
2443    let describe = || {
2444        format!(
2445            "call from {} to '{circuit}' at {} through contract type '{interface}'",
2446            crate::state::contract_address_to_hex(&own_address),
2447            crate::state::contract_address_to_hex(&callee_address),
2448        )
2449    };
2450    check_contract_call(declared, circuit, callee_address, &describe)?;
2451    let Some(run) = state.call_tree.as_deref_mut() else {
2452        return Err(IrDriverError::CrossContract(format!(
2453            "{}: the circuit was run on its own; run it with \
2454             IrExecutable::execute_call_tree so its callees can be resolved",
2455            describe()
2456        )));
2457    };
2458    if run.active.contains(&callee_address) {
2459        return Err(IrDriverError::CrossContract(format!(
2460            "{}: the callee is already executing on the call stack, and re-entrant \
2461             cross-contract calls are not supported",
2462            describe()
2463        )));
2464    }
2465    let Some(callee) = run.callees.get(&callee_address).cloned() else {
2466        run.required = Some(callee_address);
2467        return Err(IrDriverError::CrossContract(format!(
2468            "{}: the callee is not bound yet",
2469            describe()
2470        )));
2471    };
2472    let callee_index = run.callee_indices.get(&callee_address).cloned();
2473    crate::cross_contract::check_conformance(declared, &callee.ir, &describe)?;
2474    crate::cross_contract::check_implementation(&callee, circuit, &describe)?;
2475    let body = find_exported_callee_circuit(&callee.ir, callee_index.as_deref(), circuit)?;
2476    let trace_args = state
2477        .trace
2478        .as_ref()
2479        .map(|_| Value::Array(arg_values.clone()));
2480    let args = bind_callee_args(body, arg_values, &describe)?;
2481
2482    let callee_label = state.trace.as_ref().map_or_else(String::new, |_| {
2483        format!(
2484            "{interface}@{}",
2485            crate::trace::short_address(&callee_address)
2486        )
2487    });
2488    let callee_depth = state.trace_depth + 1;
2489    let trace_level = state.trace_level;
2490    record_cross_contract_enter(
2491        state.trace.as_deref_mut(),
2492        &state.contract_label,
2493        &callee_label,
2494        circuit,
2495        trace_args,
2496        state.trace_depth,
2497    );
2498    let (result, finished) = execute_callee_frame(
2499        run,
2500        &callee,
2501        callee_index.as_deref(),
2502        body,
2503        callee_address,
2504        own_address,
2505        args,
2506        state.next_zswap_local_state.coin_public_key,
2507        std::mem::take(&mut state.emitted_events),
2508        state.tblock,
2509        callee_label,
2510        circuit,
2511        state.trace.as_deref_mut(),
2512        trace_level,
2513        callee_depth,
2514        &describe,
2515    )?;
2516    state.emitted_events = finished.emitted_events;
2517    state.private_transcript_outputs.push(finished.output);
2518    state
2519        .private_transcript_outputs
2520        .push(AlignedValue::from(finished.rand));
2521    run_ops(
2522        state,
2523        claim_contract_call_ops(callee_address, circuit, finished.comm)?,
2524    )
2525    .map_err(|e| IrDriverError::CrossContract(format!("{}: claiming the call: {e}", describe())))?;
2526    Ok(result)
2527}
2528
2529fn find_exported_callee_circuit<'ir>(
2530    ir: &'ir MoonIr,
2531    index: Option<&IrIndex>,
2532    circuit: &str,
2533) -> Result<&'ir CircuitBody> {
2534    index
2535        .and_then(|idx| idx.exported_circuit(ir, circuit))
2536        .or_else(|| ir.circuits.iter().find(|c| c.exported && c.name == circuit))
2537        .ok_or_else(|| IrDriverError::UnknownCircuit(circuit.to_owned()))
2538}
2539
2540#[allow(clippy::too_many_arguments)]
2541fn execute_callee_frame(
2542    run: &mut CallTreeRun,
2543    callee: &crate::cross_contract::CalleeContract,
2544    callee_index: Option<&IrIndex>,
2545    body: &CircuitBody,
2546    callee_address: ContractAddress,
2547    own_address: ContractAddress,
2548    args: VarMap,
2549    coin_public_key: crate::types::CoinPublicKey,
2550    emitted_events: Vec<EmittedEvent>,
2551    tblock: Timestamp,
2552    callee_label: String,
2553    circuit: &str,
2554    trace: Option<&mut crate::trace::ExecutionTrace>,
2555    trace_level: crate::trace::TraceLevel,
2556    callee_depth: usize,
2557    describe: &dyn Fn() -> String,
2558) -> Result<(Value, FinishedCall)> {
2559    // A second call to the same callee sees what the first left behind.
2560    let initial_contract_state = run
2561        .states
2562        .get(&callee_address)
2563        .cloned()
2564        .unwrap_or_else(|| callee.state.clone());
2565    let zswap = run
2566        .zswap
2567        .remove(&callee_address)
2568        .unwrap_or_else(|| CompactZswapLocalState::empty(coin_public_key));
2569    run.active.push(callee_address);
2570    let effects = empty_effects();
2571    let tracing_active = trace.is_some();
2572    let circuit_label = if tracing_active {
2573        circuit.to_owned()
2574    } else {
2575        String::new()
2576    };
2577    let transcript_cap =
2578        callee_index.map_or(0, |idx| idx.estimated_transcript_ops(&callee.ir, body));
2579    let mut callee_state = InterpState {
2580        ir: &callee.ir,
2581        index: callee_index,
2582        contract_state: initial_contract_state.clone(),
2583        contract_address: callee_address,
2584        private_state: Value::Null,
2585        locals: VarMap::default(),
2586        args,
2587        public_transcript: Vec::with_capacity(transcript_cap),
2588        private_transcript_outputs: Vec::new(),
2589        popeq_read_results: Vec::new(),
2590        witnesses: Arc::new(crate::cross_contract::CalleeWitnesses {
2591            callee: callee_address,
2592        }),
2593        coin_commitments: Vec::new(),
2594        next_zswap_local_state: zswap,
2595        emitted_events,
2596        tblock,
2597        caller: Some(own_address),
2598        call_tree: Some(run),
2599        effects,
2600        vm_session: None,
2601        contract_label: callee_label,
2602        circuit_name: circuit_label,
2603        trace,
2604        trace_level,
2605        trace_depth: callee_depth,
2606        coverage: None,
2607    };
2608    let run_result = run_statement(&mut callee_state, &body.body);
2609    // Always pop this callee from `run.active` before propagating any error so
2610    // the active call stack stays balanced even when `execute_callee_frame` fails.
2611    if let Some(active_run) = callee_state.call_tree.as_deref_mut() {
2612        active_run.active.pop();
2613    }
2614    let result = run_result?;
2615    callee_state.try_sync_from_query_context()?;
2616    if let Some(t) = callee_state.trace.as_deref_mut() {
2617        t.push(crate::trace::TraceEvent::CircuitExit {
2618            contract: std::mem::take(&mut callee_state.contract_label),
2619            circuit: std::mem::take(&mut callee_state.circuit_name),
2620            result: result.clone(),
2621            depth: callee_depth,
2622        });
2623    }
2624    let finished = finish_callee_run(
2625        callee_state,
2626        body,
2627        &result,
2628        own_address,
2629        initial_contract_state,
2630        describe,
2631    )?;
2632    Ok((result, finished))
2633}
2634
2635fn record_cross_contract_enter(
2636    trace: Option<&mut crate::trace::ExecutionTrace>,
2637    caller: &str,
2638    target: &str,
2639    circuit: &str,
2640    args: Option<Value>,
2641    caller_depth: usize,
2642) {
2643    if let (Some(trace), Some(traced_args)) = (trace, args) {
2644        trace.push(crate::trace::TraceEvent::CrossContractCall {
2645            caller: caller.to_owned(),
2646            callee: target.to_owned(),
2647            circuit: circuit.to_owned(),
2648            args: traced_args.clone(),
2649            depth: caller_depth,
2650        });
2651        trace.push(crate::trace::TraceEvent::CircuitEnter {
2652            contract: target.to_owned(),
2653            circuit: circuit.to_owned(),
2654            args: traced_args,
2655            depth: caller_depth + 1,
2656        });
2657    }
2658}
2659
2660/// The interface name and declared circuits of a contract type, seen
2661/// through any aliases.
2662fn declared_contract_type(
2663    address_type: &TypeDescriptor,
2664) -> Result<(&str, &[moonproof_runtime_ir::ir::ContractCircuitSig])> {
2665    let mut declared_type = address_type;
2666    while let TypeDescriptor::Alias { of, .. } = declared_type {
2667        declared_type = of;
2668    }
2669    let TypeDescriptor::Contract {
2670        name: interface,
2671        circuits: declared,
2672    } = declared_type
2673    else {
2674        return Err(IrDriverError::InvalidIr(format!(
2675            "contract-call through a value of type {address_type:?}"
2676        )));
2677    };
2678    Ok((interface, declared))
2679}
2680
2681fn check_contract_call(
2682    declared: &[moonproof_runtime_ir::ir::ContractCircuitSig],
2683    circuit: &str,
2684    callee_address: ContractAddress,
2685    describe: &dyn Fn() -> String,
2686) -> Result<()> {
2687    if moonproof_ledger::ERA != moonproof_ledger::LedgerEra::V9 {
2688        return Err(IrDriverError::CrossContract(format!(
2689            "{}: cross-contract calls need ledger 9; this build targets {}",
2690            describe(),
2691            moonproof_ledger::ERA.as_str()
2692        )));
2693    }
2694    if !declared.iter().any(|c| c.name == circuit) {
2695        return Err(IrDriverError::InvalidIr(format!(
2696            "{}: the contract type declares no such circuit",
2697            describe()
2698        )));
2699    }
2700    if callee_address == ContractAddress::default() {
2701        return Err(IrDriverError::CrossContract(format!(
2702            "{}: the callee is the default contract address",
2703            describe()
2704        )));
2705    }
2706    Ok(())
2707}
2708
2709fn bind_callee_args(
2710    body: &CircuitBody,
2711    arg_values: Vec<Value>,
2712    describe: &dyn Fn() -> String,
2713) -> Result<VarMap> {
2714    let got = arg_values.len();
2715    let mut args = VarMap::with_capacity_and_hasher(body.arguments.len(), FxBuildHasher);
2716    for (a, v) in body.arguments.iter().zip(arg_values) {
2717        args.insert(a.name.clone(), v);
2718    }
2719    if args.len() != body.arguments.len() {
2720        return Err(IrDriverError::ArgCount {
2721            context: describe(),
2722            expected: body.arguments.len(),
2723            got,
2724        });
2725    }
2726    Ok(args)
2727}
2728
2729/// What the caller takes from a finished callee run.
2730struct FinishedCall {
2731    output: AlignedValue,
2732    rand: moonproof_ledger::transient_crypto::curve::Fr,
2733    comm: moonproof_ledger::transient_crypto::curve::Fr,
2734    emitted_events: Vec<EmittedEvent>,
2735}
2736
2737/// Record a finished callee run on its call tree: the callee's final
2738/// state and zswap outputs, and the call itself with its commitment.
2739fn finish_callee_run(
2740    mut callee_state: InterpState<'_>,
2741    body: &CircuitBody,
2742    result: &Value,
2743    caller_address: ContractAddress,
2744    initial_contract_state: ContractState<InMemoryDB>,
2745    describe: &dyn Fn() -> String,
2746) -> Result<FinishedCall> {
2747    callee_state.sync_from_query_context();
2748    let input = encode_input_with_index(
2749        callee_state.ir,
2750        callee_state.index,
2751        body,
2752        &callee_state.args,
2753    )?;
2754    let output = encode_output_with_index(callee_state.ir, callee_state.index, body, result)?;
2755    let InterpState {
2756        contract_state: next_contract_state,
2757        contract_address,
2758        public_transcript,
2759        popeq_read_results,
2760        private_transcript_outputs,
2761        next_zswap_local_state,
2762        emitted_events,
2763        call_tree,
2764        effects: callee_effects,
2765        ..
2766    } = callee_state;
2767    let run = call_tree.ok_or_else(|| {
2768        IrDriverError::CrossContract(format!("{}: the call tree was lost", describe()))
2769    })?;
2770    let rand: moonproof_ledger::transient_crypto::curve::Fr = rand::Rng::r#gen(&mut run.rng);
2771    run.states
2772        .insert(contract_address, next_contract_state.clone());
2773    run.zswap
2774        .insert(contract_address, next_zswap_local_state.clone());
2775    let comm = moonproof_ledger::onchain_runtime::communication_commitment(
2776        input.clone(),
2777        output.clone(),
2778        rand,
2779    );
2780    run.calls.push(crate::cross_contract::CalleeCall {
2781        contract_address,
2782        caller: caller_address,
2783        circuit_id: body.name.clone(),
2784        initial_contract_state,
2785        next_contract_state,
2786        input,
2787        output: output.clone(),
2788        public_transcript,
2789        popeq_read_results,
2790        private_transcript_outputs,
2791        zswap_local_state: next_zswap_local_state,
2792        communication_commitment_rand: rand,
2793        effects: callee_effects,
2794    });
2795    Ok(FinishedCall {
2796        output,
2797        rand,
2798        comm,
2799        emitted_events,
2800    })
2801}
2802
2803/// The address a value of a contract type holds.
2804fn contract_address_of(value: &Value) -> Result<ContractAddress> {
2805    let bytes = value
2806        .as_object()
2807        .and_then(|obj| obj.get("bytes"))
2808        .and_then(Value::as_bytes)
2809        .ok_or_else(|| {
2810            IrDriverError::TypeMismatch(format!("contract value is not a ContractAddress: {value}"))
2811        })?;
2812    let bytes: [u8; 32] = bytes.try_into().map_err(|_| {
2813        IrDriverError::TypeMismatch(format!(
2814            "contract address has {} bytes, not 32",
2815            bytes.len()
2816        ))
2817    })?;
2818    Ok(ContractAddress(HashOutput(bytes)))
2819}
2820
2821/// `kernel.claimContractCall(address, entryPointHash, commitment)`, as
2822/// compactc emits it and compact-runtime's `kernelClaimContractCall`
2823/// spells it by hand: insert `(seq, address, ep_hash, comm)` into the
2824/// claimed-calls set, `seq` being the set's size.
2825fn claim_contract_call_ops(
2826    callee: ContractAddress,
2827    circuit: &str,
2828    comm: moonproof_ledger::transient_crypto::curve::Fr,
2829) -> Result<Vec<Op<ResultModeGather, InMemoryDB>>> {
2830    use moonproof_ledger::onchain_runtime::ops::Key;
2831    use moonproof_ledger::onchain_runtime::state::{EntryPointBuf, StateValue};
2832    use moonproof_ledger::storage::arena::Sp;
2833    use moonproof_ledger::storage::storage::Array as StorageArray;
2834
2835    let bytes32 = TypeDescriptor::Bytes { length: 32 };
2836    let entry_point: EntryPointBuf = circuit.as_bytes().into();
2837    let address = encode_literal(&bytes32, &Value::Bytes(callee.0 .0.to_vec()))?;
2838    let ep_hash = encode_literal(&bytes32, &Value::Bytes(entry_point.ep_hash().0.to_vec()))?;
2839    let claim = AlignedValue::concat([&address, &ep_hash, &AlignedValue::from(comm)]);
2840    let claimed_contract_calls = super::vm_decode::checked_key(AlignedValue::from(3u8))?;
2841    Ok(vec![
2842        Op::Swap { n: 0 },
2843        Op::Idx {
2844            cached: true,
2845            push_path: true,
2846            path: StorageArray::from(vec![Key::Value(claimed_contract_calls)]),
2847        },
2848        Op::Dup { n: 0 },
2849        Op::Size,
2850        Op::Push {
2851            storage: false,
2852            value: super::vm_decode::checked_state_value(&StateValue::Cell(Sp::new(claim)))?,
2853        },
2854        Op::Concat {
2855            cached: true,
2856            n: 160,
2857        },
2858        Op::Push {
2859            storage: false,
2860            value: super::vm_decode::checked_state_value(&StateValue::Null)?,
2861        },
2862        Op::Ins { cached: true, n: 2 },
2863        Op::Swap { n: 0 },
2864    ])
2865}
2866
2867/// Implement the host-side natives Compact contracts call directly.
2868/// These are pure functions (no side effects, no host capability
2869/// needed) that the IR would otherwise require a sidecar to compute.
2870///
2871/// **persistentHash**: matches the WASM-exposed
2872/// `persistentHash(alignment, value)` from
2873/// `onchain-runtime-wasm/src/primitives.rs`: encode the input via
2874/// its declared descriptor into an `AlignedValue`, then run
2875/// `ValueReprAlignedValue::binary_repr` through a
2876/// `PersistentHashWriter` (which is SHA-256 underneath).
2877#[inline]
2878fn encode_native_arg(
2879    plans: Option<&NativeFabPlans>,
2880    arg_defs: &[moonproof_runtime_ir::ir::Argument],
2881    arg_values: &[Value],
2882    idx: usize,
2883) -> Result<AlignedValue> {
2884    let plan = plans.and_then(|p| p.args.get(idx)).and_then(Option::as_ref);
2885    encode_with_plan(plan, &arg_defs[idx].arg_type, &arg_values[idx])
2886}
2887
2888pub(crate) fn eval_native_circuit(
2889    function: &str,
2890    arg_values: &[Value],
2891    arg_defs: &[moonproof_runtime_ir::ir::Argument],
2892    plans: Option<&NativeFabPlans>,
2893    _result_type: &TypeDescriptor,
2894) -> Result<Value> {
2895    match function {
2896        "persistentHash" => native_persistent_hash(arg_values, arg_defs, plans),
2897        // `transientHash(value) -> Field` — Poseidon hash of the
2898        // value's `field_vec()` representation. Mirrors
2899        // `transient-crypto/src/hash.rs:76`.
2900        "transientHash" => native_transient_hash(arg_values, arg_defs, plans),
2901        // `transientCommit(value, opening) -> Field` — commits to a
2902        // value with a Field opening via Poseidon. Mirrors
2903        // `transient-crypto/src/hash.rs:84`: prepend `opening` to the
2904        // value's field-repr, then `transient_hash`.
2905        "transientCommit" => native_transient_commit(arg_values, arg_defs, plans),
2906        // `degradeToTransient(persistent) -> Field` — extracts the
2907        // 2nd field-element of a 32-byte `HashOutput`'s `field_vec`
2908        // representation. Mirrors `transient-crypto/src/hash.rs:71`.
2909        "degradeToTransient" => native_degrade_to_transient(arg_values, arg_defs, plans),
2910        // `upgradeFromTransient(transient) -> Bytes<32>` — converts a
2911        // Field to a 32-byte HashOutput by taking its LE byte repr.
2912        // Mirrors `transient-crypto/src/hash.rs:64`.
2913        "upgradeFromTransient" => native_upgrade_from_transient(arg_values, arg_defs),
2914        // `persistentCommit(value, opening) -> Bytes<32>` mirrors the
2915        // canonical Rust impl at
2916        // `midnight-ledger/base-crypto/src/hash.rs:98`: write the
2917        // opening hash, then the value's binary_repr, into a SHA-256
2918        // PersistentHashWriter. Used by Compact's `_tokenType_0`
2919        // helper to derive a per-contract token color.
2920        "persistentCommit" => native_persistent_commit(arg_values, arg_defs, plans),
2921        // `coinCommitment(coin: ShieldedCoinInfo, recipient: Either<...>) -> Bytes<32>`
2922        // — direct-call form of the `coin-commit` VM wrapper. Same
2923        // logic as the wrapper: build the typed CoinInfo + Recipient
2924        // and call `info.commitment(&recipient)`. Mirrors
2925        // `onchain-runtime-wasm/src/primitives.rs:135`'s
2926        // `runtimeCoinCommitment` and the closed `coin-commit` VM
2927        // wrapper at `vm_decode.rs::coin-commit`.
2928        "coinCommitment" => native_coin_commitment(arg_values, arg_defs, plans),
2929        // `tokenType(domain_sep: Bytes<32>, contractAddress: ContractAddress) -> Bytes<32>`
2930        // — derive the per-contract custom token type. Mirrors
2931        // `ContractAddress::custom_shielded_token_type(domain_sep)` —
2932        // a SHA-256 commit over `b"midnight:custom-token-type[v1]"
2933        // + domain_sep + contract_address.0`.
2934        "tokenType" => native_token_type(arg_values, arg_defs, plans),
2935        // ---------------------------- JubJub primitives ----------------------------
2936        //
2937        // `JubjubPoint` is `Opaque<'JubjubPoint'>` at source but is laid out as two
2938        // Field atoms at the AlignedValue layer (see upstream
2939        // `runtime/src/compact-types.ts::CompactTypeJubjubPoint`). The RuntimeValue
2940        // representation mirrors the TS struct: `Object { x: Bytes, y: Bytes }`,
2941        // each value a 32-byte little-endian Fr.
2942        "jubjubPointX" => native_jubjub_point_x(arg_values),
2943        "jubjubPointY" => native_jubjub_point_y(arg_values),
2944        "constructJubjubPoint" => native_construct_jubjub_point(arg_values),
2945        "ecAdd" => native_ec_add(arg_values),
2946        "ecMul" => native_ec_mul(arg_values),
2947        "ecMulGenerator" => native_ec_mul_generator(arg_values),
2948        "hashToCurve" => native_hash_to_curve(arg_values, arg_defs, plans),
2949        // compact-runtime's host function is `reduceModJubjubOrder`;
2950        // IR lifted from emitted JS names it by its Compact name.
2951        "jubjubScalarFromNative" | "reduceModJubjubOrder" => {
2952            native_reduce_mod_jubjub_order(arg_values)
2953        }
2954        "keccak256" | "sha512" => native_digest(function, arg_values, arg_defs, plans),
2955        // Jubjub is a twisted Edwards curve, so `-(x, y) = (-x, y)`.
2956        // compact-runtime negates the coordinate without checking the
2957        // point, and so does this.
2958        "ecNeg" => native_ec_neg(arg_values),
2959        "ed25519Verify" => native_ed25519_verify(arg_values, arg_defs, plans),
2960        "secp256r1EcdsaVerify" => native_ecdsa_verify(
2961            "secp256r1EcdsaVerify",
2962            moonproof_ledger::foreign_curve::ForeignCurve::Secp256r1,
2963            arg_values,
2964            arg_defs,
2965        ),
2966        "secp256k1EcdsaVerify" => native_ecdsa_verify(
2967            "secp256k1EcdsaVerify",
2968            moonproof_ledger::foreign_curve::ForeignCurve::Secp256k1,
2969            arg_values,
2970            arg_defs,
2971        ),
2972        other => {
2973            if let Some((field_type, op)) = foreign_field_native(other) {
2974                return eval_foreign_field_native(other, field_type, op, arg_values);
2975            }
2976            if let Some((curve, op)) = foreign_curve_native(other) {
2977                return eval_foreign_curve_native(other, curve, op, arg_values);
2978            }
2979            Err(IrDriverError::unimplemented(format!(
2980                "native circuit '{other}'"
2981            )))
2982        }
2983    }
2984}
2985
2986fn native_persistent_hash(
2987    arg_values: &[Value],
2988    arg_defs: &[moonproof_runtime_ir::ir::Argument],
2989    plans: Option<&NativeFabPlans>,
2990) -> Result<Value> {
2991    use moonproof_ledger::base_crypto::hash::PersistentHashWriter;
2992    use moonproof_ledger::base_crypto::repr::BinaryHashRepr;
2993    use moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue;
2994    if arg_values.len() != 1 || arg_defs.len() != 1 {
2995        return Err(IrDriverError::ArgCount {
2996            context: "persistentHash".into(),
2997            expected: 1,
2998            got: arg_values.len(),
2999        });
3000    }
3001    let av = encode_native_arg(plans, arg_defs, arg_values, 0)?;
3002    // Replicate the WASM impl: feed `binary_repr` of the
3003    // (value, alignment) pair into a SHA-256 sink.
3004    let mut hasher = PersistentHashWriter::default();
3005    ValueReprAlignedValue(av).binary_repr(&mut hasher);
3006    let HashOutput(bytes) = hasher.finalize();
3007    Ok(Value::Bytes(bytes.to_vec()))
3008}
3009
3010fn native_transient_hash(
3011    arg_values: &[Value],
3012    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3013    plans: Option<&NativeFabPlans>,
3014) -> Result<Value> {
3015    use moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue;
3016    use moonproof_ledger::transient_crypto::repr::FieldRepr;
3017    if arg_values.len() != 1 || arg_defs.len() != 1 {
3018        return Err(IrDriverError::ArgCount {
3019            context: "transientHash".into(),
3020            expected: 1,
3021            got: arg_values.len(),
3022        });
3023    }
3024    let av = encode_native_arg(plans, arg_defs, arg_values, 0)?;
3025    let repr = ValueReprAlignedValue(av).field_vec();
3026    let fr = moonproof_ledger::transient_crypto::hash::transient_hash(&repr);
3027    Ok(Value::Bytes(fr.as_le_bytes().clone()))
3028}
3029
3030fn native_transient_commit(
3031    arg_values: &[Value],
3032    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3033    plans: Option<&NativeFabPlans>,
3034) -> Result<Value> {
3035    use moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue;
3036    use moonproof_ledger::transient_crypto::repr::FieldRepr;
3037    if arg_values.len() != 2 || arg_defs.len() != 2 {
3038        return Err(IrDriverError::ArgCount {
3039            context: "transientCommit".into(),
3040            expected: 2,
3041            got: arg_values.len(),
3042        });
3043    }
3044    let value_av = encode_native_arg(plans, arg_defs, arg_values, 0)?;
3045    let opening_av = encode_native_arg(plans, arg_defs, arg_values, 1)?;
3046    // The opening AlignedValue is a Field — decode back to Fr.
3047    let opening_atom = opening_av.value.0.first().ok_or_else(|| {
3048        IrDriverError::TypeMismatch("transientCommit opening AlignedValue empty".into())
3049    })?;
3050    let mut opening_buf = opening_atom.0.clone();
3051    opening_buf.resize(32, 0);
3052    let opening_fr = moonproof_ledger::transient_crypto::curve::Fr::from_le_bytes(&opening_buf)
3053        .ok_or_else(|| {
3054            IrDriverError::TypeMismatch("transientCommit opening not a valid Fr".into())
3055        })?;
3056    let mut preimage = vec![opening_fr];
3057    ValueReprAlignedValue(value_av).field_repr(&mut preimage);
3058    let fr = moonproof_ledger::transient_crypto::hash::transient_hash(&preimage);
3059    Ok(Value::Bytes(fr.as_le_bytes().clone()))
3060}
3061
3062fn native_degrade_to_transient(
3063    arg_values: &[Value],
3064    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3065    plans: Option<&NativeFabPlans>,
3066) -> Result<Value> {
3067    if arg_values.len() != 1 || arg_defs.len() != 1 {
3068        return Err(IrDriverError::ArgCount {
3069            context: "degradeToTransient".into(),
3070            expected: 1,
3071            got: arg_values.len(),
3072        });
3073    }
3074    // Input is `Bytes<32>`. Decode to HashOutput.
3075    let av = encode_native_arg(plans, arg_defs, arg_values, 0)?;
3076    let atom = av.value.0.first().ok_or_else(|| {
3077        IrDriverError::TypeMismatch("degradeToTransient input AlignedValue empty".into())
3078    })?;
3079    let mut buf = atom.0.clone();
3080    buf.resize(32, 0);
3081    let mut arr = [0u8; 32];
3082    arr.copy_from_slice(&buf);
3083    let fr = moonproof_ledger::transient_crypto::hash::degrade_to_transient(HashOutput(arr));
3084    Ok(Value::Bytes(fr.as_le_bytes().clone()))
3085}
3086
3087fn native_upgrade_from_transient(
3088    arg_values: &[Value],
3089    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3090) -> Result<Value> {
3091    if arg_values.len() != 1 || arg_defs.len() != 1 {
3092        return Err(IrDriverError::ArgCount {
3093            context: "upgradeFromTransient".into(),
3094            expected: 1,
3095            got: arg_values.len(),
3096        });
3097    }
3098    let bytes = arg_values[0].as_bytes().ok_or_else(|| {
3099        IrDriverError::TypeMismatch(format!(
3100            "upgradeFromTransient input not bytes: {}",
3101            arg_values[0]
3102        ))
3103    })?;
3104    let fr =
3105        moonproof_ledger::transient_crypto::curve::Fr::from_le_bytes(bytes).ok_or_else(|| {
3106            IrDriverError::TypeMismatch("upgradeFromTransient: input not a valid Fr".into())
3107        })?;
3108    let HashOutput(out) = moonproof_ledger::transient_crypto::hash::upgrade_from_transient(fr);
3109    Ok(Value::Bytes(out.to_vec()))
3110}
3111
3112fn native_persistent_commit(
3113    arg_values: &[Value],
3114    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3115    plans: Option<&NativeFabPlans>,
3116) -> Result<Value> {
3117    use moonproof_ledger::base_crypto::hash::persistent_commit;
3118    use moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue;
3119    if arg_values.len() != 2 || arg_defs.len() != 2 {
3120        return Err(IrDriverError::ArgCount {
3121            context: "persistentCommit".into(),
3122            expected: 2,
3123            got: arg_values.len(),
3124        });
3125    }
3126    let value_av = encode_native_arg(plans, arg_defs, arg_values, 0)?;
3127    let opening_av = encode_native_arg(plans, arg_defs, arg_values, 1)?;
3128    // Decode the opening AlignedValue back to a 32-byte
3129    // HashOutput. The IR's `rand` arg is `Bytes<32>`.
3130    let opening_bytes = opening_av
3131        .value
3132        .0
3133        .first()
3134        .ok_or_else(|| {
3135            IrDriverError::TypeMismatch("persistentCommit opening AlignedValue is empty".into())
3136        })?
3137        .0
3138        .clone();
3139    if opening_bytes.len() > 32 {
3140        return Err(IrDriverError::TypeMismatch(format!(
3141            "persistentCommit opening must be ≤32 bytes, got {}",
3142            opening_bytes.len()
3143        )));
3144    }
3145    let mut opening_arr = [0u8; 32];
3146    opening_arr[..opening_bytes.len()].copy_from_slice(&opening_bytes);
3147    let HashOutput(bytes) =
3148        persistent_commit(&ValueReprAlignedValue(value_av), HashOutput(opening_arr));
3149    Ok(Value::Bytes(bytes.to_vec()))
3150}
3151
3152fn native_coin_commitment(
3153    arg_values: &[Value],
3154    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3155    plans: Option<&NativeFabPlans>,
3156) -> Result<Value> {
3157    if arg_values.len() != 2 || arg_defs.len() != 2 {
3158        return Err(IrDriverError::ArgCount {
3159            context: "coinCommitment".into(),
3160            expected: 2,
3161            got: arg_values.len(),
3162        });
3163    }
3164    let coin_av = encode_native_arg(plans, arg_defs, arg_values, 0)?;
3165    let recipient_av = encode_native_arg(plans, arg_defs, arg_values, 1)?;
3166    let coin: moonproof_ledger::coin_structure::coin::Info =
3167        moonproof_ledger::coin_structure::coin::Info::try_from(&**AsRef::<
3168            moonproof_ledger::base_crypto::fab::Value,
3169        >::as_ref(&coin_av))
3170        .map_err(|e| {
3171            IrDriverError::TypeMismatch(format!("coinCommitment coin → CoinInfo: {e:?}"))
3172        })?;
3173    let recipient: moonproof_ledger::coin_structure::transfer::Recipient =
3174        moonproof_ledger::coin_structure::transfer::Recipient::try_from(&**AsRef::<
3175            moonproof_ledger::base_crypto::fab::Value,
3176        >::as_ref(
3177            &recipient_av
3178        ))
3179        .map_err(|e| {
3180            IrDriverError::TypeMismatch(format!("coinCommitment recipient → Recipient: {e:?}"))
3181        })?;
3182    let HashOutput(bytes) = coin.commitment(&recipient).0;
3183    Ok(Value::Bytes(bytes.to_vec()))
3184}
3185
3186fn native_token_type(
3187    arg_values: &[Value],
3188    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3189    plans: Option<&NativeFabPlans>,
3190) -> Result<Value> {
3191    if arg_values.len() != 2 || arg_defs.len() != 2 {
3192        return Err(IrDriverError::ArgCount {
3193            context: "tokenType".into(),
3194            expected: 2,
3195            got: arg_values.len(),
3196        });
3197    }
3198    // domain_sep: Bytes<32>
3199    let domain_av = encode_native_arg(plans, arg_defs, arg_values, 0)?;
3200    let domain_atom = domain_av.value.0.first().ok_or_else(|| {
3201        IrDriverError::TypeMismatch("tokenType domain_sep AlignedValue empty".into())
3202    })?;
3203    let mut domain_buf = domain_atom.0.clone();
3204    domain_buf.resize(32, 0);
3205    let mut domain_arr = [0u8; 32];
3206    domain_arr.copy_from_slice(&domain_buf);
3207    // contractAddress: Struct ContractAddress { bytes: Bytes<32> }
3208    let addr_av = encode_native_arg(plans, arg_defs, arg_values, 1)?;
3209    let addr_atom = addr_av.value.0.first().ok_or_else(|| {
3210        IrDriverError::TypeMismatch("tokenType contractAddress AlignedValue empty".into())
3211    })?;
3212    let mut addr_buf = addr_atom.0.clone();
3213    addr_buf.resize(32, 0);
3214    let mut addr_arr = [0u8; 32];
3215    addr_arr.copy_from_slice(&addr_buf);
3216    let addr = moonproof_ledger::coin_structure::contract::ContractAddress(HashOutput(addr_arr));
3217    let moonproof_ledger::coin_structure::coin::ShieldedTokenType(HashOutput(bytes)) =
3218        addr.custom_shielded_token_type(HashOutput(domain_arr));
3219    Ok(Value::Bytes(bytes.to_vec()))
3220}
3221
3222fn native_jubjub_point_x(arg_values: &[Value]) -> Result<Value> {
3223    if arg_values.len() != 1 {
3224        return Err(IrDriverError::ArgCount {
3225            context: "jubjubPointX".into(),
3226            expected: 1,
3227            got: arg_values.len(),
3228        });
3229    }
3230    let p = decode_jubjub_point(&arg_values[0])?;
3231    let x = p
3232        .x()
3233        .unwrap_or_else(|| moonproof_ledger::transient_crypto::curve::Fr::from(0u64));
3234    Ok(encode_fr_value(&x))
3235}
3236
3237fn native_jubjub_point_y(arg_values: &[Value]) -> Result<Value> {
3238    if arg_values.len() != 1 {
3239        return Err(IrDriverError::ArgCount {
3240            context: "jubjubPointY".into(),
3241            expected: 1,
3242            got: arg_values.len(),
3243        });
3244    }
3245    let p = decode_jubjub_point(&arg_values[0])?;
3246    let y = p
3247        .y()
3248        .unwrap_or_else(|| moonproof_ledger::transient_crypto::curve::Fr::from(0u64));
3249    Ok(encode_fr_value(&y))
3250}
3251
3252fn native_construct_jubjub_point(arg_values: &[Value]) -> Result<Value> {
3253    if arg_values.len() != 2 {
3254        return Err(IrDriverError::ArgCount {
3255            context: "constructJubjubPoint".into(),
3256            expected: 2,
3257            got: arg_values.len(),
3258        });
3259    }
3260    let x = decode_fr_value("constructJubjubPoint.x", &arg_values[0])?;
3261    let y = decode_fr_value("constructJubjubPoint.y", &arg_values[1])?;
3262    let p = moonproof_ledger::transient_crypto::curve::EmbeddedGroupAffine::new(x, y).ok_or_else(
3263        || {
3264            IrDriverError::TypeMismatch(
3265                "constructJubjubPoint: (x, y) is not on the embedded curve".into(),
3266            )
3267        },
3268    )?;
3269    Ok(encode_jubjub_point(&p))
3270}
3271
3272fn native_ec_add(arg_values: &[Value]) -> Result<Value> {
3273    if arg_values.len() != 2 {
3274        return Err(IrDriverError::ArgCount {
3275            context: "ecAdd".into(),
3276            expected: 2,
3277            got: arg_values.len(),
3278        });
3279    }
3280    let p = decode_jubjub_point(&arg_values[0])?;
3281    let q = decode_jubjub_point(&arg_values[1])?;
3282    Ok(encode_jubjub_point(&(p + q)))
3283}
3284
3285fn native_ec_mul(arg_values: &[Value]) -> Result<Value> {
3286    if arg_values.len() != 2 {
3287        return Err(IrDriverError::ArgCount {
3288            context: "ecMul".into(),
3289            expected: 2,
3290            got: arg_values.len(),
3291        });
3292    }
3293    let p = decode_jubjub_point(&arg_values[0])?;
3294    let s = decode_fr_value("ecMul.scalar", &arg_values[1])?;
3295    // `Mul<Fr>` is implemented on EmbeddedGroupAffine — reduces `s`
3296    // modulo the embedded scalar field order internally.
3297    Ok(encode_jubjub_point(&(p * s)))
3298}
3299
3300fn native_ec_mul_generator(arg_values: &[Value]) -> Result<Value> {
3301    if arg_values.len() != 1 {
3302        return Err(IrDriverError::ArgCount {
3303            context: "ecMulGenerator".into(),
3304            expected: 1,
3305            got: arg_values.len(),
3306        });
3307    }
3308    let s = decode_fr_value("ecMulGenerator.scalar", &arg_values[0])?;
3309    let g = moonproof_ledger::transient_crypto::curve::EmbeddedGroupAffine::generator();
3310    Ok(encode_jubjub_point(&(g * s)))
3311}
3312
3313fn native_hash_to_curve(
3314    arg_values: &[Value],
3315    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3316    plans: Option<&NativeFabPlans>,
3317) -> Result<Value> {
3318    use moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue;
3319    if arg_values.len() != 1 || arg_defs.len() != 1 {
3320        return Err(IrDriverError::ArgCount {
3321            context: "hashToCurve".into(),
3322            expected: 1,
3323            got: arg_values.len(),
3324        });
3325    }
3326    let av = encode_native_arg(plans, arg_defs, arg_values, 0)?;
3327    let p = moonproof_ledger::transient_crypto::hash::hash_to_curve(&ValueReprAlignedValue(av));
3328    Ok(encode_jubjub_point(&p))
3329}
3330
3331fn native_reduce_mod_jubjub_order(arg_values: &[Value]) -> Result<Value> {
3332    // Reduce a base-field element (Fr) modulo the embedded scalar field
3333    // order. Mirrors upstream `runtime/src/built-ins.ts::reduceModJubjubOrder`
3334    // — `EmbeddedFr::from_le_bytes_wide` performs the modular reduction;
3335    // we then widen the result back to Fr so downstream arithmetic in the
3336    // base field continues to work.
3337    if arg_values.len() != 1 {
3338        return Err(IrDriverError::ArgCount {
3339            context: "jubjubScalarFromNative".into(),
3340            expected: 1,
3341            got: arg_values.len(),
3342        });
3343    }
3344    let fr = decode_fr_value("jubjubScalarFromNative.x", &arg_values[0])?;
3345    let efr = moonproof_ledger::transient_crypto::curve::EmbeddedFr::from_le_bytes_wide(
3346        &fr.as_le_bytes(),
3347    )
3348    .ok_or_else(|| {
3349        IrDriverError::TypeMismatch(
3350            "jubjubScalarFromNative: input did not reduce to embedded scalar".into(),
3351        )
3352    })?;
3353    let reduced = moonproof_ledger::transient_crypto::curve::Fr::from_le_bytes(&efr.as_le_bytes())
3354        .ok_or_else(|| {
3355            IrDriverError::TypeMismatch(
3356                "jubjubScalarFromNative: reduced scalar does not fit in Fr".into(),
3357            )
3358        })?;
3359    Ok(encode_fr_value(&reduced))
3360}
3361
3362fn native_digest(
3363    function: &str,
3364    arg_values: &[Value],
3365    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3366    plans: Option<&NativeFabPlans>,
3367) -> Result<Value> {
3368    if arg_values.len() != 1 || arg_defs.len() != 1 {
3369        return Err(IrDriverError::ArgCount {
3370            context: function.into(),
3371            expected: 1,
3372            got: arg_values.len(),
3373        });
3374    }
3375    let av = encode_native_arg(plans, arg_defs, arg_values, 0)?;
3376    let bytes = super::curve::binary_repr(&av)?;
3377    Ok(Value::Bytes(if function == "keccak256" {
3378        use sha3::Digest;
3379        sha3::Keccak256::digest(&bytes).to_vec()
3380    } else {
3381        use sha2::Digest;
3382        sha2::Sha512::digest(&bytes).to_vec()
3383    }))
3384}
3385
3386fn native_ec_neg(arg_values: &[Value]) -> Result<Value> {
3387    if arg_values.len() != 1 {
3388        return Err(IrDriverError::ArgCount {
3389            context: "ecNeg".into(),
3390            expected: 1,
3391            got: arg_values.len(),
3392        });
3393    }
3394    let obj = arg_values[0].as_object().ok_or_else(|| {
3395        IrDriverError::TypeMismatch(format!(
3396            "expected object {{ x, y }} for JubjubPoint, got {}",
3397            arg_values[0]
3398        ))
3399    })?;
3400    let coordinate = |name: &str| {
3401        obj.get(name).ok_or_else(|| {
3402            IrDriverError::TypeMismatch(format!("JubjubPoint missing field '{name}'"))
3403        })
3404    };
3405    let x = decode_fr_value("ecNeg.x", coordinate("x")?)?;
3406    let y = decode_fr_value("ecNeg.y", coordinate("y")?)?;
3407    let mut out = std::collections::BTreeMap::new();
3408    out.insert("x".to_owned(), encode_fr_value(&-x));
3409    out.insert("y".to_owned(), encode_fr_value(&y));
3410    Ok(Value::Object(out))
3411}
3412
3413/// `<curve><Base|Scalar><Neg|Inv>`, compact-runtime's per-field
3414/// negation and inversion.
3415fn foreign_field_native(host: &str) -> Option<(FieldType, &'static str)> {
3416    let fields = [
3417        ("secp256k1Base", FieldType::Secp256k1Base),
3418        ("secp256k1Scalar", FieldType::Secp256k1Scalar),
3419        ("secp256r1Base", FieldType::Secp256r1Base),
3420        ("secp256r1Scalar", FieldType::Secp256r1Scalar),
3421        ("curve25519Base", FieldType::Curve25519Base),
3422        ("curve25519Scalar", FieldType::Curve25519Scalar),
3423    ];
3424    fields
3425        .iter()
3426        .find_map(|(prefix, field_type)| match host.strip_prefix(prefix)? {
3427            "Neg" => Some((*field_type, "Neg")),
3428            "Inv" => Some((*field_type, "Inv")),
3429            _ => None,
3430        })
3431}
3432
3433fn eval_foreign_field_native(
3434    host: &str,
3435    field_type: FieldType,
3436    op: &str,
3437    arg_values: &[Value],
3438) -> Result<Value> {
3439    let [x] = arg_values else {
3440        return Err(IrDriverError::ArgCount {
3441            context: host.into(),
3442            expected: 1,
3443            got: arg_values.len(),
3444        });
3445    };
3446    let x = super::curve::value_as_u256(x, host)?;
3447    let out = if op == "Neg" {
3448        super::curve::field_neg(field_type, x)?
3449    } else {
3450        super::curve::field_inv(field_type, x)?
3451    };
3452    Ok(Value::Bytes(out.to_le_bytes().to_vec()))
3453}
3454
3455/// `<curve>{PointX,PointY,Add,Mul,MulGenerator}`, compact-runtime's
3456/// per-curve point natives.
3457fn foreign_curve_native(
3458    host: &str,
3459) -> Option<(moonproof_ledger::foreign_curve::ForeignCurve, &str)> {
3460    use moonproof_ledger::foreign_curve::ForeignCurve;
3461    let curves = [
3462        ("secp256k1", ForeignCurve::Secp256k1),
3463        ("secp256r1", ForeignCurve::Secp256r1),
3464        ("curve25519", ForeignCurve::Curve25519),
3465    ];
3466    curves.iter().find_map(|(prefix, curve)| {
3467        let op = host.strip_prefix(prefix)?;
3468        matches!(op, "PointX" | "PointY" | "Add" | "Mul" | "MulGenerator").then_some((*curve, op))
3469    })
3470}
3471
3472fn eval_foreign_curve_native(
3473    host: &str,
3474    curve: moonproof_ledger::foreign_curve::ForeignCurve,
3475    op: &str,
3476    arg_values: &[Value],
3477) -> Result<Value> {
3478    use super::curve::{affine_to_value, point_to_affine, value_as_u256};
3479    use moonproof_ledger::foreign_curve as fc;
3480
3481    let expected = match op {
3482        "Add" | "Mul" => 2,
3483        _ => 1,
3484    };
3485    if arg_values.len() != expected {
3486        return Err(IrDriverError::ArgCount {
3487            context: host.into(),
3488            expected,
3489            got: arg_values.len(),
3490        });
3491    }
3492    let curve_err = |e: fc::ForeignCurveError| IrDriverError::VmOp(format!("{host}: {e}"));
3493    let scalar = |v: &Value| value_as_u256(v, host).map(ethnum::U256::to_le_bytes);
3494    let point = match op {
3495        "PointX" | "PointY" => {
3496            let p = point_to_affine(curve, &arg_values[0], host)?;
3497            let Some((x, y)) = p else {
3498                return Err(IrDriverError::VmOp(format!(
3499                    "cannot extract the {} of the {curve:?} identity point",
3500                    if op == "PointX" {
3501                        "x-coordinate"
3502                    } else {
3503                        "y-coordinate"
3504                    }
3505                )));
3506            };
3507            return Ok(Value::Bytes(if op == "PointX" { x } else { y }.to_vec()));
3508        }
3509        "Add" => fc::add(
3510            curve,
3511            &point_to_affine(curve, &arg_values[0], host)?,
3512            &point_to_affine(curve, &arg_values[1], host)?,
3513        )
3514        .map_err(curve_err)?,
3515        "Mul" => fc::mul(
3516            curve,
3517            &point_to_affine(curve, &arg_values[0], host)?,
3518            &scalar(&arg_values[1])?,
3519        )
3520        .map_err(curve_err)?,
3521        _ => fc::mul_generator(curve, &scalar(&arg_values[0])?).map_err(curve_err)?,
3522    };
3523    Ok(affine_to_value(curve, &point))
3524}
3525
3526fn unwrap_alias_descriptor(mut td: &TypeDescriptor) -> &TypeDescriptor {
3527    while let TypeDescriptor::Alias { of, .. } = td {
3528        td = of;
3529    }
3530    td
3531}
3532
3533fn exact_bytes32(value: &Value, what: &str) -> Result<[u8; 32]> {
3534    let bytes = value.as_bytes().ok_or_else(|| {
3535        IrDriverError::TypeMismatch(format!("{what} expects Bytes<32>, got {value}"))
3536    })?;
3537    bytes.try_into().map_err(|_| {
3538        IrDriverError::TypeMismatch(format!(
3539            "{what} expects exactly 32 bytes, got {}",
3540            bytes.len()
3541        ))
3542    })
3543}
3544
3545/// Standard Ed25519 verification `ed25519Verify(msg, sig, pk) -> Boolean`:
3546/// verifies `[s]B == R + [SHA512(R || A || msg) mod L]A` and rejects
3547/// non-canonical scalars (`s >= L`) or invalid compressed point encodings.
3548fn native_ed25519_verify(
3549    arg_values: &[Value],
3550    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3551    plans: Option<&NativeFabPlans>,
3552) -> Result<Value> {
3553    use ethnum::U256;
3554    use moonproof_ledger::foreign_curve::{self as fc, AffinePoint, ForeignCurve};
3555    use sha2::Digest;
3556
3557    if arg_values.len() != 3 || arg_defs.len() != 3 {
3558        return Err(IrDriverError::ArgCount {
3559            context: "ed25519Verify".into(),
3560            expected: 3,
3561            got: arg_values.len(),
3562        });
3563    }
3564
3565    let msg_av = encode_native_arg(plans, arg_defs, arg_values, 0)?;
3566    let msg_bytes = super::curve::binary_repr(&msg_av)?;
3567
3568    let (r_pt, s_u256): (AffinePoint, U256) = if let Some(b) = arg_values[1].as_bytes() {
3569        if b.len() != 64 {
3570            return Err(IrDriverError::TypeMismatch(format!(
3571                "ed25519Verify.sig expects Bytes<64>, got {} bytes",
3572                b.len()
3573            )));
3574        }
3575        let Ok(r_pt) = fc::from_bytes(ForeignCurve::Curve25519, &b[..32]) else {
3576            return Ok(Value::Bool(false));
3577        };
3578        let s_bytes: [u8; 32] = b[32..64]
3579            .try_into()
3580            .map_err(|_| IrDriverError::TypeMismatch("ed25519Verify.sig.s slice len".into()))?;
3581        (r_pt, U256::from_le_bytes(s_bytes))
3582    } else if let Some(obj) = arg_values[1].as_object() {
3583        let r_val = obj.get("r").ok_or_else(|| {
3584            IrDriverError::TypeMismatch("ed25519Verify.sig missing field 'r'".into())
3585        })?;
3586        let s_val = obj.get("s").ok_or_else(|| {
3587            IrDriverError::TypeMismatch("ed25519Verify.sig missing field 's'".into())
3588        })?;
3589        if r_val.as_object().is_some() {
3590            let r_pt = super::curve::point_to_affine(
3591                ForeignCurve::Curve25519,
3592                r_val,
3593                "ed25519Verify.sig.r",
3594            )?;
3595            let s_u256 = super::curve::value_as_u256(s_val, "ed25519Verify.sig.s")?;
3596            (r_pt, s_u256)
3597        } else {
3598            let r_bytes = exact_bytes32(r_val, "ed25519Verify.sig.r")?;
3599            let s_bytes = exact_bytes32(s_val, "ed25519Verify.sig.s")?;
3600            let Ok(r_pt) = fc::from_bytes(ForeignCurve::Curve25519, &r_bytes) else {
3601                return Ok(Value::Bool(false));
3602            };
3603            (r_pt, U256::from_le_bytes(s_bytes))
3604        }
3605    } else {
3606        return Err(IrDriverError::TypeMismatch(format!(
3607            "ed25519Verify.sig expects Bytes<64> or struct {{ r, s }}, got {}",
3608            arg_values[1]
3609        )));
3610    };
3611
3612    if s_u256 >= super::curve::CURVE25519_SCALAR_MODULUS {
3613        return Ok(Value::Bool(false));
3614    }
3615
3616    let a_pt: AffinePoint = if arg_values[2].as_object().is_some() {
3617        super::curve::point_to_affine(ForeignCurve::Curve25519, &arg_values[2], "ed25519Verify.pk")?
3618    } else {
3619        let pk_bytes = exact_bytes32(&arg_values[2], "ed25519Verify.pk")?;
3620        let Ok(a_pt) = fc::from_bytes(ForeignCurve::Curve25519, &pk_bytes) else {
3621            return Ok(Value::Bool(false));
3622        };
3623        a_pt
3624    };
3625
3626    let curve_err = |e: fc::ForeignCurveError| IrDriverError::VmOp(format!("ed25519Verify: {e}"));
3627    let r_enc = fc::to_bytes(ForeignCurve::Curve25519, &r_pt).map_err(curve_err)?;
3628    let a_enc = fc::to_bytes(ForeignCurve::Curve25519, &a_pt).map_err(curve_err)?;
3629
3630    let mut hasher = sha2::Sha512::new();
3631    hasher.update(&r_enc);
3632    hasher.update(&a_enc);
3633    hasher.update(&msg_bytes);
3634    let digest: [u8; 64] = hasher.finalize().into();
3635
3636    let l =
3637        num_bigint::BigUint::from_bytes_le(&super::curve::CURVE25519_SCALAR_MODULUS.to_le_bytes());
3638    let mut k_le = (num_bigint::BigUint::from_bytes_le(&digest) % &l).to_bytes_le();
3639    k_le.resize(32, 0);
3640    let k_bytes: [u8; 32] = k_le.try_into().map_err(|_| {
3641        IrDriverError::VmOp("ed25519Verify: reduced challenge exceeded 32 bytes".into())
3642    })?;
3643
3644    let lhs =
3645        fc::mul_generator(ForeignCurve::Curve25519, &s_u256.to_le_bytes()).map_err(curve_err)?;
3646    let ka = fc::mul(ForeignCurve::Curve25519, &a_pt, &k_bytes).map_err(curve_err)?;
3647    let rhs = fc::add(ForeignCurve::Curve25519, &r_pt, &ka).map_err(curve_err)?;
3648
3649    Ok(Value::Bool(lhs == rhs))
3650}
3651
3652fn decode_ecdsa_sig(
3653    host: &str,
3654    sig_val: &Value,
3655    sig_ty: &TypeDescriptor,
3656    scalar_desc: &TypeDescriptor,
3657) -> Result<(ethnum::U256, ethnum::U256)> {
3658    use ethnum::U256;
3659
3660    if let Some(bytes) = sig_val.as_bytes() {
3661        if bytes.len() != 64 {
3662            return Err(IrDriverError::TypeMismatch(format!(
3663                "{host}.sig expects Bytes<64>, got {} bytes",
3664                bytes.len()
3665            )));
3666        }
3667        let r_be: [u8; 32] = bytes[..32]
3668            .try_into()
3669            .map_err(|_| IrDriverError::TypeMismatch(format!("{host}.sig.r slice len")))?;
3670        let s_be: [u8; 32] = bytes[32..64]
3671            .try_into()
3672            .map_err(|_| IrDriverError::TypeMismatch(format!("{host}.sig.s slice len")))?;
3673        return Ok((U256::from_be_bytes(r_be), U256::from_be_bytes(s_be)));
3674    }
3675
3676    let obj = sig_val.as_object().ok_or_else(|| {
3677        IrDriverError::TypeMismatch(format!(
3678            "{host}.sig expects Bytes<64> or struct {{ r, s }}, got {sig_val}"
3679        ))
3680    })?;
3681    let r_val = obj
3682        .get("r")
3683        .ok_or_else(|| IrDriverError::TypeMismatch(format!("{host}.sig missing field 'r'")))?;
3684    let s_val = obj
3685        .get("s")
3686        .ok_or_else(|| IrDriverError::TypeMismatch(format!("{host}.sig missing field 's'")))?;
3687    let is_scalar_struct = matches!(
3688        unwrap_alias_descriptor(sig_ty),
3689        TypeDescriptor::Struct { elements, .. }
3690            if elements.len() == 2
3691                && unwrap_alias_descriptor(&elements[0].field_type) == scalar_desc
3692                && unwrap_alias_descriptor(&elements[1].field_type) == scalar_desc
3693    );
3694    if is_scalar_struct {
3695        Ok((
3696            super::curve::value_as_u256(r_val, &format!("{host}.sig.r"))?,
3697            super::curve::value_as_u256(s_val, &format!("{host}.sig.s"))?,
3698        ))
3699    } else {
3700        let r_be = exact_bytes32(r_val, &format!("{host}.sig.r"))?;
3701        let s_be = exact_bytes32(s_val, &format!("{host}.sig.s"))?;
3702        Ok((U256::from_be_bytes(r_be), U256::from_be_bytes(s_be)))
3703    }
3704}
3705
3706/// ECDSA verification over secp256r1 (P-256) or secp256k1:
3707/// `verify(msg_hash: Bytes<32>, sig, pk) -> Boolean`.
3708/// Matches ZKIR lowering semantics: big-endian 32-byte `msg_hash` reduced
3709/// mod `n`, canonical non-zero `0 < r, s < n`, identity rejection on `pk`
3710/// and `u1*G + u2*pk`, and `(u1*G + u2*pk).x mod n == r`.
3711fn native_ecdsa_verify(
3712    host: &str,
3713    curve: moonproof_ledger::foreign_curve::ForeignCurve,
3714    arg_values: &[Value],
3715    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3716) -> Result<Value> {
3717    use ethnum::U256;
3718    use moonproof_ledger::foreign_curve::{self as fc, AffinePoint, ForeignCurve};
3719
3720    if arg_values.len() != 3 || arg_defs.len() != 3 {
3721        return Err(IrDriverError::ArgCount {
3722            context: host.into(),
3723            expected: 3,
3724            got: arg_values.len(),
3725        });
3726    }
3727
3728    let (scalar_field, scalar_desc, modulus) = match curve {
3729        ForeignCurve::Secp256r1 => (
3730            FieldType::Secp256r1Scalar,
3731            TypeDescriptor::Secp256r1Scalar,
3732            super::curve::SECP256R1_SCALAR_MODULUS,
3733        ),
3734        ForeignCurve::Secp256k1 => (
3735            FieldType::Secp256k1Scalar,
3736            TypeDescriptor::Secp256k1Scalar,
3737            super::curve::SECP256K1_SCALAR_MODULUS,
3738        ),
3739        ForeignCurve::Curve25519 => {
3740            return Err(IrDriverError::TypeMismatch(format!(
3741                "{host}: ECDSA is only defined on Weierstrass curves"
3742            )));
3743        }
3744    };
3745
3746    let h_be = exact_bytes32(&arg_values[0], &format!("{host}.msg_hash"))?;
3747    let msg_scalar = U256::from_be_bytes(h_be) % modulus;
3748
3749    let (sig_r, sig_s) =
3750        decode_ecdsa_sig(host, &arg_values[1], &arg_defs[1].arg_type, &scalar_desc)?;
3751    if sig_r == U256::ZERO || sig_s == U256::ZERO || sig_r >= modulus || sig_s >= modulus {
3752        return Ok(Value::Bool(false));
3753    }
3754
3755    let pk_pt: AffinePoint = if arg_values[2].as_object().is_some() {
3756        super::curve::point_to_affine(curve, &arg_values[2], &format!("{host}.pk"))?
3757    } else if let Some(bytes) = arg_values[2].as_bytes() {
3758        let Ok(pt) = fc::from_bytes(curve, bytes) else {
3759            return Ok(Value::Bool(false));
3760        };
3761        pt
3762    } else {
3763        return Err(IrDriverError::TypeMismatch(format!(
3764            "{host}.pk expects curve point or compressed bytes, got {}",
3765            arg_values[2]
3766        )));
3767    };
3768
3769    if pk_pt.is_none() {
3770        return Ok(Value::Bool(false));
3771    }
3772
3773    let curve_err = |e: fc::ForeignCurveError| IrDriverError::VmOp(format!("{host}: {e}"));
3774    let s_inv = super::curve::field_inv(scalar_field, sig_s)?;
3775    let u1 = super::curve::modular_binop(modulus, "*", msg_scalar, s_inv)?;
3776    let u2 = super::curve::modular_binop(modulus, "*", sig_r, s_inv)?;
3777
3778    let p1 = fc::mul_generator(curve, &u1.to_le_bytes()).map_err(curve_err)?;
3779    let p2 = fc::mul(curve, &pk_pt, &u2.to_le_bytes()).map_err(curve_err)?;
3780    let pt = fc::add(curve, &p1, &p2).map_err(curve_err)?;
3781
3782    let Some((x_le, _y_le)) = pt else {
3783        return Ok(Value::Bool(false));
3784    };
3785    let x_mod_n = U256::from_le_bytes(x_le) % modulus;
3786    Ok(Value::Bool(x_mod_n == sig_r))
3787}
3788
3789/// Decode a `RuntimeValue::Bytes` (or numeric form) into a base-field `Fr`.
3790/// Accepts 32-byte LE, smaller buffers (zero-padded right), and integer forms
3791/// matching `encode_field`'s tolerated inputs.
3792fn decode_fr_value(
3793    context: &str,
3794    value: &Value,
3795) -> Result<moonproof_ledger::transient_crypto::curve::Fr> {
3796    if let Some(b) = value.as_bytes() {
3797        let mut buf = b.to_vec();
3798        if buf.len() < 32 {
3799            buf.resize(32, 0);
3800        }
3801        moonproof_ledger::transient_crypto::curve::Fr::from_le_bytes(&buf).ok_or_else(|| {
3802            IrDriverError::TypeMismatch(format!("{context}: {} bytes does not fit in Fr", b.len()))
3803        })
3804    } else if let Some(n) = value.as_u128() {
3805        Ok(moonproof_ledger::transient_crypto::curve::Fr::from(n))
3806    } else if let Some(s) = value.as_str() {
3807        let n: u128 = s.parse().map_err(|e| {
3808            IrDriverError::TypeMismatch(format!(
3809                "{context}: decimal-string parse failed: '{s}' ({e})"
3810            ))
3811        })?;
3812        Ok(moonproof_ledger::transient_crypto::curve::Fr::from(n))
3813    } else {
3814        Err(IrDriverError::TypeMismatch(format!(
3815            "{context}: expected Field (bytes / int / decimal-string), got {value}"
3816        )))
3817    }
3818}
3819
3820/// Encode a base-field `Fr` into a `RuntimeValue::Bytes` (32-byte LE).
3821fn encode_fr_value(fr: &moonproof_ledger::transient_crypto::curve::Fr) -> Value {
3822    Value::Bytes(fr.as_le_bytes())
3823}
3824
3825/// Decode `Object { x: Bytes, y: Bytes }` into an `EmbeddedGroupAffine`.
3826/// Mirrors the layout produced by `CompactTypeJubjubPoint.fromValue` upstream.
3827fn decode_jubjub_point(
3828    value: &Value,
3829) -> Result<moonproof_ledger::transient_crypto::curve::EmbeddedGroupAffine> {
3830    let obj = value.as_object().ok_or_else(|| {
3831        IrDriverError::TypeMismatch(format!(
3832            "expected object {{ x, y }} for JubjubPoint, got {value}"
3833        ))
3834    })?;
3835    let x = obj
3836        .get("x")
3837        .ok_or_else(|| IrDriverError::TypeMismatch("JubjubPoint missing field 'x'".into()))?;
3838    let y = obj
3839        .get("y")
3840        .ok_or_else(|| IrDriverError::TypeMismatch("JubjubPoint missing field 'y'".into()))?;
3841    let x_fr = decode_fr_value("JubjubPoint.x", x)?;
3842    let y_fr = decode_fr_value("JubjubPoint.y", y)?;
3843    // Identity is represented as `(0, 0)` in the alignment-level encoding (see
3844    // `transient-crypto/src/fab.rs::TryFrom<&ValueSlice> for EmbeddedGroupAffine`).
3845    let zero = moonproof_ledger::transient_crypto::curve::Fr::from(0u64);
3846    if x_fr == zero && y_fr == zero {
3847        return Ok(moonproof_ledger::transient_crypto::curve::EmbeddedGroupAffine::identity());
3848    }
3849    moonproof_ledger::transient_crypto::curve::EmbeddedGroupAffine::new(x_fr, y_fr).ok_or_else(
3850        || IrDriverError::TypeMismatch("JubjubPoint: (x, y) is not on the embedded curve".into()),
3851    )
3852}
3853
3854/// Encode an `EmbeddedGroupAffine` back into `Object { x: Bytes, y: Bytes }`.
3855fn encode_jubjub_point(
3856    p: &moonproof_ledger::transient_crypto::curve::EmbeddedGroupAffine,
3857) -> Value {
3858    let zero = moonproof_ledger::transient_crypto::curve::Fr::from(0u64);
3859    let x = p.x().unwrap_or(zero);
3860    let y = p.y().unwrap_or(zero);
3861    let mut obj = std::collections::BTreeMap::new();
3862    obj.insert("x".to_owned(), encode_fr_value(&x));
3863    obj.insert("y".to_owned(), encode_fr_value(&y));
3864    Value::Object(obj)
3865}
3866
3867/// Bridge `createZswapOutput` / `createZswapInput` kernel witness
3868/// invocations into [`InterpState::next_zswap_local_state`]. Both
3869/// witnesses observe a unit value (`[]`) — their semantic effect is
3870/// recording the coin move on the host side, which the call-tx
3871/// pipeline reads out of the local state to materialize the
3872/// `Offer<ProofPreimage>` attached to the resulting `Transaction`.
3873///
3874/// `createZswapOutput(coin: ShieldedCoinInfo, recipient: Either<ZswapCoinPublicKey, ContractAddress>)`
3875/// — pushes a `CompactZswapOutput { coin_info, recipient }` onto
3876/// `state.next_zswap_local_state.outputs`.
3877///
3878/// `createZswapInput(coin: QualifiedShieldedCoinInfo)` — pushes a
3879/// `QualifiedInfo` onto `state.next_zswap_local_state.inputs`.
3880///
3881/// Other witnesses are no-ops here.
3882fn bridge_zswap_kernel_witness(
3883    state: &mut InterpState<'_>,
3884    function: &str,
3885    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3886    arg_values: &[Value],
3887) -> Result<()> {
3888    bridge_zswap_kernel_witness_local(
3889        &mut state.next_zswap_local_state,
3890        function,
3891        arg_defs,
3892        arg_values,
3893    )
3894}
3895
3896pub(crate) fn bridge_zswap_kernel_witness_local(
3897    zswap_local: &mut CompactZswapLocalState,
3898    function: &str,
3899    arg_defs: &[moonproof_runtime_ir::ir::Argument],
3900    arg_values: &[Value],
3901) -> Result<()> {
3902    use moonproof_ledger::base_crypto::fab::Value as FabValue;
3903    use moonproof_ledger::coin_structure::coin::{
3904        Info as CoinInfo, QualifiedInfo as QualifiedCoinInfo,
3905    };
3906    use moonproof_ledger::coin_structure::transfer::Recipient;
3907    match function {
3908        "createZswapOutput" => {
3909            if arg_values.len() != 2 || arg_defs.len() != 2 {
3910                return Err(IrDriverError::ArgCount {
3911                    context: "createZswapOutput".into(),
3912                    expected: 2,
3913                    got: arg_values.len(),
3914                });
3915            }
3916            let coin_av = encode_literal(&arg_defs[0].arg_type, &arg_values[0])?;
3917            let recipient_av = encode_literal(&arg_defs[1].arg_type, &arg_values[1])?;
3918            let coin: CoinInfo = CoinInfo::try_from(&**AsRef::<FabValue>::as_ref(&coin_av))
3919                .map_err(|e| {
3920                    IrDriverError::TypeMismatch(format!("createZswapOutput coin → CoinInfo: {e:?}"))
3921                })?;
3922            let recipient: Recipient =
3923                Recipient::try_from(&**AsRef::<FabValue>::as_ref(&recipient_av)).map_err(|e| {
3924                    IrDriverError::TypeMismatch(format!(
3925                        "createZswapOutput recipient → Recipient: {e:?}"
3926                    ))
3927                })?;
3928            zswap_local.outputs.push(CompactZswapOutput {
3929                coin_info: coin,
3930                recipient,
3931            });
3932            zswap_local.current_index = zswap_local.current_index.saturating_add(1);
3933        }
3934        "createZswapInput" => {
3935            if arg_values.is_empty() || arg_defs.is_empty() {
3936                return Err(IrDriverError::ArgCount {
3937                    context: "createZswapInput".into(),
3938                    expected: 1,
3939                    got: arg_values.len(),
3940                });
3941            }
3942            let qcoin_av = encode_literal(&arg_defs[0].arg_type, &arg_values[0])?;
3943            let qcoin: QualifiedCoinInfo = QualifiedCoinInfo::try_from(
3944                &**AsRef::<FabValue>::as_ref(&qcoin_av),
3945            )
3946            .map_err(|e| {
3947                IrDriverError::TypeMismatch(format!("createZswapInput coin → QualifiedInfo: {e:?}"))
3948            })?;
3949            zswap_local.inputs.push(qcoin);
3950        }
3951        _ => {}
3952    }
3953    Ok(())
3954}
3955
3956/// Run an ADT-Op invocation: decode the IR's pre-expanded vm-ops into
3957/// typed Op<ResultModeGather>, execute against a `QueryContext` seeded
3958/// from the current contract state, fold the resulting state back in,
3959/// append the executed ops to the `public_transcript`.
3960///
3961/// Returns the JSON-decoded read result if the op produced one
3962/// (Cell.read, Map.lookup, Map.member, etc.). Pure-write ops (like
3963/// Cell.write) return `Value::Null`. The decoder picks between these
3964/// modes by inspecting the `result-type` descriptor — an empty Tuple
3965/// means no return value.
3966/// Decode and run a bare vm-op sequence against the contract state,
3967/// returning the events it gathered. Used by `emit`, whose ops are a
3968/// `queryLedgerState` sequence with no ADT context and no popeq reads.
3969fn run_ops_slice(
3970    state: &mut InterpState<'_>,
3971    ops: &[Op<ResultModeGather, InMemoryDB>],
3972    flags: QueryFlags,
3973    err_context: impl FnOnce() -> String,
3974) -> Result<Vec<GatherEvent<InMemoryDB>>> {
3975    let mut session = state
3976        .vm_session
3977        .take()
3978        .unwrap_or_else(|| VmSession::from_interp_state(state));
3979    if flags.reads_context {
3980        session.ensure_context(
3981            &state.contract_state,
3982            state.contract_address,
3983            state.tblock,
3984            &state.coin_commitments,
3985            state.caller,
3986        );
3987    }
3988    let result = session.run_ops(ops, flags, err_context);
3989    state.vm_session = Some(session);
3990    result
3991}
3992
3993fn run_vm_ops(
3994    state: &mut InterpState<'_>,
3995    vm_ops: &[moonproof_runtime_ir::ir::VmInstr],
3996) -> Result<Vec<GatherEvent<InMemoryDB>>> {
3997    if let Some(compiled) = state
3998        .index
3999        .and_then(|idx| idx.compiled_query(state.ir, vm_ops))
4000    {
4001        let flags = compiled.flags;
4002        return match &compiled.body {
4003            CompiledQueryBody::Static(ops) => {
4004                let events = run_ops_slice(state, ops, flags, || "vm-op exec".to_owned())?;
4005                state.public_transcript.extend_from_slice(ops);
4006                Ok(events)
4007            }
4008            CompiledQueryBody::Dynamic(compiled_ops) => {
4009                let scope = EvalScope {
4010                    ir: state.ir,
4011                    locals: &state.locals,
4012                    args: &state.args,
4013                };
4014                let ops = CompiledLedgerQuery::materialize_dynamic(compiled_ops, &scope)?;
4015                run_ops_with_flags(state, ops, flags)
4016            }
4017        };
4018    }
4019    let scope = EvalScope {
4020        ir: state.ir,
4021        locals: &state.locals,
4022        args: &state.args,
4023    };
4024    let mut ops = Vec::with_capacity(vm_ops.len());
4025    for i in vm_ops {
4026        ops.push(decode_op(i, &scope)?);
4027    }
4028    run_ops(state, ops)
4029}
4030
4031fn run_ops_with_flags(
4032    state: &mut InterpState<'_>,
4033    ops: Vec<Op<ResultModeGather, InMemoryDB>>,
4034    flags: QueryFlags,
4035) -> Result<Vec<GatherEvent<InMemoryDB>>> {
4036    let events = run_ops_slice(state, &ops, flags, || "vm-op exec".to_owned())?;
4037    state.public_transcript.extend(ops);
4038    Ok(events)
4039}
4040
4041fn run_ops(
4042    state: &mut InterpState<'_>,
4043    ops: Vec<Op<ResultModeGather, InMemoryDB>>,
4044) -> Result<Vec<GatherEvent<InMemoryDB>>> {
4045    let flags = analyze_ops(&ops);
4046    run_ops_with_flags(state, ops, flags)
4047}
4048
4049fn execute_adt_op(state: &mut InterpState<'_>, invocation: &AdtOpInvocation) -> Result<Value> {
4050    let (vm_op_count, events) = if let Some(compiled) = state
4051        .index
4052        .and_then(|idx| idx.compiled_query(state.ir, &invocation.vm_ops))
4053    {
4054        let flags = compiled.flags;
4055        match &compiled.body {
4056            CompiledQueryBody::Static(ops) => {
4057                let events = run_ops_slice(state, ops, flags, || {
4058                    format!("{}.{} VM exec", invocation.adt, invocation.operation)
4059                })?;
4060                state.public_transcript.extend_from_slice(ops);
4061                (ops.len(), events)
4062            }
4063            CompiledQueryBody::Dynamic(compiled_ops) => {
4064                let scope = EvalScope {
4065                    ir: state.ir,
4066                    locals: &state.locals,
4067                    args: &state.args,
4068                };
4069                let ops = CompiledLedgerQuery::materialize_dynamic(compiled_ops, &scope)?;
4070                let count = ops.len();
4071                let events = run_ops_slice(state, &ops, flags, || {
4072                    format!("{}.{} VM exec", invocation.adt, invocation.operation)
4073                })?;
4074                state.public_transcript.extend(ops);
4075                (count, events)
4076            }
4077        }
4078    } else {
4079        let scope = EvalScope {
4080            ir: state.ir,
4081            locals: &state.locals,
4082            args: &state.args,
4083        };
4084        let mut ops = Vec::with_capacity(invocation.vm_ops.len());
4085        for i in &invocation.vm_ops {
4086            ops.push(decode_op(i, &scope)?);
4087        }
4088        let flags = analyze_ops(&ops);
4089        let count = ops.len();
4090        let events = run_ops_slice(state, &ops, flags, || {
4091            format!("{}.{} VM exec", invocation.adt, invocation.operation)
4092        })?;
4093        state.public_transcript.extend(ops);
4094        (count, events)
4095    };
4096
4097    // Each `popeq` op fires a `GatherEvent::Read(av)` carrying the
4098    // value that landed at the top of the stack. Push reads directly
4099    // into `popeq_read_results` without an intermediate Vec or clone,
4100    // and borrow the last read in place to decode the return value.
4101    let reads_start = state.popeq_read_results.len();
4102    for event in events {
4103        if let GatherEvent::Read(av) = event {
4104            state.popeq_read_results.push(av);
4105        }
4106    }
4107
4108    let return_is_unit = matches!(
4109        &invocation.result_type,
4110        TypeDescriptor::Tuple { types } if types.is_empty()
4111    );
4112    if return_is_unit {
4113        if state.trace_level.includes_details() {
4114            if let Some(trace) = state.trace.as_deref_mut() {
4115                trace.push(crate::trace::TraceEvent::LedgerOp {
4116                    contract: state.contract_label.clone(),
4117                    adt: invocation.adt.clone(),
4118                    operation: invocation.operation.clone(),
4119                    vm_op_count,
4120                    result: None,
4121                    depth: state.trace_depth,
4122                });
4123            }
4124        }
4125        return Ok(Value::Null);
4126    }
4127    if state.popeq_read_results.len() == reads_start {
4128        return Err(IrDriverError::VmOp(format!(
4129            "{}.{} declared a non-unit return-type {:?} but produced no popeq read",
4130            invocation.adt, invocation.operation, invocation.result_type
4131        )));
4132    }
4133    let av = state
4134        .popeq_read_results
4135        .last()
4136        .expect("len > reads_start guarantees at least one read");
4137    let decoded = decode_aligned_value_full(&invocation.result_type, av)?;
4138    if state.trace_level.includes_details() {
4139        if let Some(trace) = state.trace.as_deref_mut() {
4140            trace.push(crate::trace::TraceEvent::LedgerOp {
4141                contract: state.contract_label.clone(),
4142                adt: invocation.adt.clone(),
4143                operation: invocation.operation.clone(),
4144                vm_op_count,
4145                result: Some(decoded.clone()),
4146                depth: state.trace_depth,
4147            });
4148        }
4149    }
4150    Ok(decoded)
4151}
4152
4153/// Encode the circuit's input arguments as a single concatenated
4154/// `AlignedValue` (matching the JS-emit
4155/// `partialProofData.input = _descriptor_N.toValue(arg)` shape).
4156pub fn encode_input<S: std::hash::BuildHasher>(
4157    circuit: &CircuitBody,
4158    args: &HashMap<String, Value, S>,
4159) -> Result<AlignedValue> {
4160    if circuit.arguments.is_empty() {
4161        return Ok(AlignedValue::concat(std::iter::empty::<&AlignedValue>()));
4162    }
4163    let avs: Result<Vec<AlignedValue>> = circuit
4164        .arguments
4165        .iter()
4166        .map(|arg| {
4167            let v = args.get(&arg.name).ok_or_else(|| IrDriverError::ArgCount {
4168                context: format!("circuit '{}' arg '{}'", circuit.name, arg.name),
4169                expected: circuit.arguments.len(),
4170                got: args.len(),
4171            })?;
4172            encode_literal(&arg.arg_type, v)
4173        })
4174        .collect();
4175    let avs = avs?;
4176    let refs: Vec<&AlignedValue> = avs.iter().collect();
4177    Ok(AlignedValue::concat(refs))
4178}
4179
4180/// Encode circuit inputs using a pre-compiled [`CircuitInputPlan`](super::descriptor::CircuitInputPlan)
4181/// from `index` when available, falling back to [`encode_input`].
4182pub(crate) fn encode_input_with_index<S: std::hash::BuildHasher>(
4183    ir: &MoonIr,
4184    index: Option<&IrIndex>,
4185    circuit: &CircuitBody,
4186    args: &HashMap<String, Value, S>,
4187) -> Result<AlignedValue> {
4188    if let Some(plan) = index
4189        .and_then(|idx| idx.circuit_io_plan(ir, circuit))
4190        .and_then(|io| io.input.as_ref())
4191    {
4192        return plan.encode(&circuit.name, args);
4193    }
4194    encode_input(circuit, args)
4195}
4196
4197/// Encode the circuit's result value as an `AlignedValue`.
4198pub fn encode_output(result_type: &TypeDescriptor, result: &Value) -> Result<AlignedValue> {
4199    if matches!(result_type, TypeDescriptor::Tuple { types } if types.is_empty()) {
4200        return Ok(AlignedValue::concat(std::iter::empty::<&AlignedValue>()));
4201    }
4202    encode_literal(result_type, result)
4203}
4204
4205/// Encode a circuit result using a pre-compiled [`FabPlan`] from `index`
4206/// when available, falling back to [`encode_output`].
4207pub(crate) fn encode_output_with_index(
4208    ir: &MoonIr,
4209    index: Option<&IrIndex>,
4210    circuit: &CircuitBody,
4211    result: &Value,
4212) -> Result<AlignedValue> {
4213    if matches!(&circuit.result_type, TypeDescriptor::Tuple { types } if types.is_empty()) {
4214        return Ok(AlignedValue::concat(std::iter::empty::<&AlignedValue>()));
4215    }
4216    if let Some(plan) = index
4217        .and_then(|idx| idx.circuit_io_plan(ir, circuit))
4218        .and_then(|io| io.output.as_ref())
4219    {
4220        return plan.encode(result);
4221    }
4222    encode_literal(&circuit.result_type, result)
4223}
4224
4225#[cfg(test)]
4226mod tests {
4227    use std::collections::BTreeMap;
4228
4229    use moonproof_ledger::ledger::structure::INITIAL_PARAMETERS;
4230    use moonproof_runtime_ir::ir::{
4231        Argument, BindingTarget, Constructor, Native, StateValue as IrStateValue, StructField,
4232    };
4233
4234    use super::*;
4235    use crate::{CircuitCallContext, CoinPublicKey, ConstructorContext, IrExecutable, NoWitnesses};
4236
4237    fn make_ctx(state: ContractState<InMemoryDB>, coin_pk: CoinPublicKey) -> CircuitCallContext {
4238        CircuitCallContext {
4239            contract_address: ContractAddress(HashOutput([0x44u8; 32])),
4240            contract_state: state,
4241            private_state: Value::Null,
4242            ledger_parameters: INITIAL_PARAMETERS,
4243            coin_public_key: coin_pk,
4244            tblock: Timestamp::from_secs(100),
4245        }
4246    }
4247
4248    async fn init_empty(
4249        ir: MoonIr,
4250        coin_pk: CoinPublicKey,
4251    ) -> (IrExecutable<NoWitnesses>, ContractState<InMemoryDB>) {
4252        let exec = IrExecutable::new(Arc::new(ir), Arc::new(NoWitnesses));
4253        let signing_key = moonproof_ledger::signatures::schnorr_signing_key(&[0x11u8; 32]).unwrap();
4254        let init = exec
4255            .initialize(
4256                ConstructorContext {
4257                    initial_private_state: Value::Null,
4258                    initial_zswap_local_state: CompactZswapLocalState::empty(coin_pk),
4259                    coin_public_key: coin_pk,
4260                    signing_key,
4261                    time: Some(Timestamp::from_secs(0)),
4262                },
4263                Value::Null,
4264            )
4265            .await
4266            .unwrap();
4267        (exec, init.initial_contract_state)
4268    }
4269
4270    fn ir_calling_native(
4271        native: Native,
4272        call_args: Vec<Expression>,
4273        circuit_args: Vec<Argument>,
4274        result_type: TypeDescriptor,
4275    ) -> MoonIr {
4276        let fn_name = native.name.clone();
4277        let mut ir = MoonIr::new_v3("test", "0.33", "0.14").with_constructor(Constructor {
4278            arguments: Vec::new(),
4279            initial_state: IrStateValue::Array { items: Vec::new() },
4280            init_ops: Vec::new(),
4281            register_operations: vec!["run".to_owned()],
4282            body: Statement::Noop,
4283        });
4284        ir.add_native(native);
4285        ir.add_circuit(CircuitBody {
4286            name: "run".to_owned(),
4287            internal_name: "run".to_owned(),
4288            internal_uniq: Some(1),
4289            exported: true,
4290            pure: true,
4291            proof: true,
4292            arguments: circuit_args,
4293            result_type,
4294            body: Statement::Expr {
4295                value: Expression::Call {
4296                    function: fn_name,
4297                    function_uniq: None,
4298                    arguments: call_args,
4299                },
4300            },
4301        });
4302        ir
4303    }
4304
4305    async fn run_native_ir(
4306        native: Native,
4307        call_args: Vec<Expression>,
4308        circuit_args: Vec<Argument>,
4309        result_type: TypeDescriptor,
4310        input: Value,
4311        coin_pk: CoinPublicKey,
4312    ) -> crate::ExecuteCircuitResult {
4313        let ir = ir_calling_native(native, call_args, circuit_args, result_type);
4314        let (exec, state) = init_empty(ir, coin_pk).await;
4315        exec.execute_circuit("run", make_ctx(state, coin_pk), input)
4316            .await
4317            .unwrap()
4318    }
4319
4320    #[tokio::test]
4321    async fn intrinsic_dispatch_matches_compact_runtime_persistent_and_transient_hash() {
4322        let coin_pk = CoinPublicKey([0x7au8; 32]);
4323        let bytes32 = TypeDescriptor::Bytes { length: 32 };
4324        let byte_arg = vec![Argument {
4325            name: "x".to_owned(),
4326            arg_type: bytes32.clone(),
4327        }];
4328        let var_x = vec![Expression::Var {
4329            name: "x".to_owned(),
4330        }];
4331
4332        let persistent_natives = [
4333            Native {
4334                name: "persistentHash".to_owned(),
4335                internal_uniq: None,
4336                host_symbol: "__compactRuntime.persistentHash".to_owned(),
4337                intrinsic: None,
4338                class: "circuit".to_owned(),
4339                arguments: byte_arg.clone(),
4340                result_type: bytes32.clone(),
4341            },
4342            Native::new_intrinsic(
4343                "persistentHash",
4344                "persistentHash",
4345                "circuit",
4346                byte_arg.clone(),
4347                bytes32.clone(),
4348            ),
4349            Native::new_intrinsic(
4350                "hash_bytes",
4351                "mp:hash/persistent",
4352                "circuit",
4353                byte_arg.clone(),
4354                bytes32.clone(),
4355            ),
4356        ];
4357        let mut persistent_out = Vec::new();
4358        for native in persistent_natives {
4359            let res = run_native_ir(
4360                native,
4361                var_x.clone(),
4362                byte_arg.clone(),
4363                bytes32.clone(),
4364                Value::Bytes(vec![0x5cu8; 32]),
4365                coin_pk,
4366            )
4367            .await;
4368            persistent_out.push((res.result, res.output));
4369        }
4370        assert_eq!(persistent_out[0], persistent_out[1]);
4371        assert_eq!(persistent_out[0], persistent_out[2]);
4372
4373        let field_arg = vec![Argument {
4374            name: "x".to_owned(),
4375            arg_type: TypeDescriptor::Field,
4376        }];
4377        let transient_natives = [
4378            Native {
4379                name: "transientHash".to_owned(),
4380                internal_uniq: None,
4381                host_symbol: "__compactRuntime.transientHash".to_owned(),
4382                intrinsic: None,
4383                class: "circuit".to_owned(),
4384                arguments: field_arg.clone(),
4385                result_type: TypeDescriptor::Field,
4386            },
4387            Native::new_intrinsic(
4388                "poseidon",
4389                "mp:hash/transient",
4390                "circuit",
4391                field_arg.clone(),
4392                TypeDescriptor::Field,
4393            ),
4394        ];
4395        let mut transient_out = Vec::new();
4396        for native in transient_natives {
4397            let res = run_native_ir(
4398                native,
4399                var_x.clone(),
4400                field_arg.clone(),
4401                TypeDescriptor::Field,
4402                Value::Int(12345),
4403                coin_pk,
4404            )
4405            .await;
4406            transient_out.push((res.result, res.output));
4407        }
4408        assert_eq!(transient_out[0], transient_out[1]);
4409    }
4410
4411    #[tokio::test]
4412    async fn intrinsic_dispatch_matches_compact_runtime_own_public_key() {
4413        let coin_pk = CoinPublicKey([0x7au8; 32]);
4414        let pk_struct = TypeDescriptor::Struct {
4415            name: "ZswapCoinPublicKey".to_owned(),
4416            elements: vec![StructField {
4417                name: "bytes".to_owned(),
4418                field_type: TypeDescriptor::Bytes { length: 32 },
4419            }],
4420        };
4421        let natives = [
4422            Native {
4423                name: "ownPublicKey".to_owned(),
4424                internal_uniq: None,
4425                host_symbol: "__compactRuntime.ownPublicKey".to_owned(),
4426                intrinsic: None,
4427                class: "witness".to_owned(),
4428                arguments: Vec::new(),
4429                result_type: pk_struct.clone(),
4430            },
4431            Native::new_intrinsic(
4432                "ownPublicKey",
4433                "ownPublicKey",
4434                "witness",
4435                Vec::new(),
4436                pk_struct.clone(),
4437            ),
4438            Native::new_intrinsic(
4439                "caller_pk",
4440                "mp:context/own-public-key",
4441                "witness",
4442                Vec::new(),
4443                pk_struct.clone(),
4444            ),
4445        ];
4446        let mut outputs = Vec::new();
4447        for native in natives {
4448            let res = run_native_ir(
4449                native,
4450                Vec::new(),
4451                Vec::new(),
4452                pk_struct.clone(),
4453                Value::Null,
4454                coin_pk,
4455            )
4456            .await;
4457            outputs.push((res.result, res.private_transcript_outputs));
4458        }
4459        assert_eq!(outputs[0], outputs[1]);
4460        assert_eq!(outputs[0], outputs[2]);
4461    }
4462
4463    fn vm_instr(pairs: Vec<(&str, Value)>) -> VmInstr {
4464        let mut map = BTreeMap::new();
4465        for (k, v) in pairs {
4466            map.insert(k.to_owned(), v);
4467        }
4468        VmInstr(map)
4469    }
4470
4471    fn vm_obj(pairs: Vec<(&str, Value)>) -> Value {
4472        let mut map = BTreeMap::new();
4473        for (k, v) in pairs {
4474            map.insert(k.to_owned(), v);
4475        }
4476        Value::Object(map)
4477    }
4478
4479    fn idx_op(slot: u64, push_path: bool) -> VmInstr {
4480        vm_instr(vec![
4481            ("op", Value::String("idx".to_owned())),
4482            ("cached", Value::Bool(false)),
4483            ("pushPath", Value::Bool(push_path)),
4484            (
4485                "path",
4486                Value::Array(vec![vm_obj(vec![
4487                    ("vm", Value::String("align".to_owned())),
4488                    ("value", Value::Int(i128::from(slot))),
4489                    ("bytes", Value::Int(1)),
4490                ])]),
4491            ),
4492        ])
4493    }
4494
4495    fn push_cell_align(storage: bool, val: i128, bytes: i128) -> VmInstr {
4496        vm_instr(vec![
4497            ("op", Value::String("push".to_owned())),
4498            ("storage", Value::Bool(storage)),
4499            (
4500                "value",
4501                vm_obj(vec![
4502                    ("vm", Value::String("state-value".to_owned())),
4503                    ("kind", Value::String("cell".to_owned())),
4504                    (
4505                        "value",
4506                        vm_obj(vec![
4507                            ("vm", Value::String("align".to_owned())),
4508                            ("value", Value::Int(val)),
4509                            ("bytes", Value::Int(bytes)),
4510                        ]),
4511                    ),
4512                ]),
4513            ),
4514        ])
4515    }
4516
4517    fn adt_expr(
4518        adt: &str,
4519        operation: &str,
4520        op_class: &str,
4521        field: &str,
4522        result_type: TypeDescriptor,
4523        vm_ops: Vec<VmInstr>,
4524    ) -> Expression {
4525        Expression::AdtOp(AdtOpInvocation {
4526            adt: adt.to_owned(),
4527            operation: operation.to_owned(),
4528            op_class: op_class.to_owned(),
4529            op_class_coin_index: None,
4530            op_class_recipient_index: None,
4531            field: Some(field.to_owned()),
4532            field_path: Vec::new(),
4533            arguments: Vec::new(),
4534            result_type,
4535            vm_ops,
4536        })
4537    }
4538
4539    fn read_slot_expr(
4540        adt: &str,
4541        field: &str,
4542        slot: u64,
4543        result_type: TypeDescriptor,
4544    ) -> Expression {
4545        adt_expr(
4546            adt,
4547            "read",
4548            "read",
4549            field,
4550            result_type,
4551            vec![
4552                vm_instr(vec![
4553                    ("op", Value::String("dup".to_owned())),
4554                    ("n", Value::Int(0)),
4555                ]),
4556                idx_op(slot, false),
4557                vm_instr(vec![
4558                    ("op", Value::String("popeq".to_owned())),
4559                    ("cached", Value::Bool(false)),
4560                ]),
4561            ],
4562        )
4563    }
4564
4565    fn ins_op(n: i128) -> VmInstr {
4566        vm_instr(vec![
4567            ("op", Value::String("ins".to_owned())),
4568            ("cached", Value::Bool(false)),
4569            ("n", Value::Int(n)),
4570        ])
4571    }
4572
4573    fn var_expr_obj(name: &str) -> Value {
4574        vm_obj(vec![
4575            ("expr", Value::String("var".to_owned())),
4576            ("name", Value::String(name.to_owned())),
4577        ])
4578    }
4579
4580    fn build_multi_op_writes(
4581        unit_ty: &TypeDescriptor,
4582    ) -> (Expression, Expression, Expression, Expression) {
4583        let init_counter = adt_expr(
4584            "Counter",
4585            "resetToDefault",
4586            "write",
4587            "count",
4588            unit_ty.clone(),
4589            vec![
4590                push_cell_align(false, 0, 1),
4591                push_cell_align(true, 10, 8),
4592                ins_op(1),
4593            ],
4594        );
4595        let inc_static = adt_expr(
4596            "Counter",
4597            "increment",
4598            "write",
4599            "count",
4600            unit_ty.clone(),
4601            vec![
4602                idx_op(0, true),
4603                vm_instr(vec![
4604                    ("op", Value::String("addi".to_owned())),
4605                    ("immediate", Value::Int(5)),
4606                ]),
4607                ins_op(1),
4608            ],
4609        );
4610        let write_cell_dynamic = adt_expr(
4611            "Cell",
4612            "write",
4613            "write",
4614            "tag",
4615            unit_ty.clone(),
4616            vec![
4617                push_cell_align(false, 1, 1),
4618                vm_instr(vec![
4619                    ("op", Value::String("push".to_owned())),
4620                    ("storage", Value::Bool(true)),
4621                    (
4622                        "value",
4623                        vm_obj(vec![
4624                            ("vm", Value::String("state-value".to_owned())),
4625                            ("kind", Value::String("cell".to_owned())),
4626                            (
4627                                "value",
4628                                vm_obj(vec![
4629                                    ("vm", Value::String("ref".to_owned())),
4630                                    (
4631                                        "type",
4632                                        vm_obj(vec![
4633                                            ("type-name", Value::String("Bytes".to_owned())),
4634                                            ("length", Value::Int(32)),
4635                                        ]),
4636                                    ),
4637                                    ("value", var_expr_obj("tag")),
4638                                ]),
4639                            ),
4640                        ]),
4641                    ),
4642                ]),
4643                ins_op(1),
4644            ],
4645        );
4646        let inc_dynamic = adt_expr(
4647            "Counter",
4648            "increment",
4649            "write",
4650            "count",
4651            unit_ty.clone(),
4652            vec![
4653                idx_op(0, true),
4654                vm_instr(vec![
4655                    ("op", Value::String("addi".to_owned())),
4656                    (
4657                        "immediate",
4658                        vm_obj(vec![
4659                            ("vm", Value::String("ref".to_owned())),
4660                            ("value", var_expr_obj("delta")),
4661                        ]),
4662                    ),
4663                ]),
4664                ins_op(1),
4665            ],
4666        );
4667        (init_counter, inc_static, write_cell_dynamic, inc_dynamic)
4668    }
4669
4670    fn build_multi_op_ir() -> MoonIr {
4671        let u64_ty = TypeDescriptor::Uint {
4672            maxval: IntLit::from_u128(u128::from(u64::MAX)),
4673            alignment_bytes: None,
4674        };
4675        let bytes32_ty = TypeDescriptor::Bytes { length: 32 };
4676        let unit_ty = TypeDescriptor::Tuple { types: Vec::new() };
4677        let (init_counter, inc_static, write_cell_dynamic, inc_dynamic) =
4678            build_multi_op_writes(&unit_ty);
4679
4680        let tuple_var = |name: &str| TupleItem {
4681            kind: "single".to_owned(),
4682            length: None,
4683            value: Expression::Var {
4684                name: name.to_owned(),
4685            },
4686        };
4687        let mut ir = MoonIr::new_v3("test", "0.33", "0.14").with_constructor(Constructor {
4688            arguments: Vec::new(),
4689            initial_state: IrStateValue::Array {
4690                items: vec![IrStateValue::Null, IrStateValue::Null],
4691            },
4692            init_ops: vec![init_counter],
4693            register_operations: vec!["multi".to_owned()],
4694            body: Statement::Noop,
4695        });
4696        ir.add_circuit(CircuitBody {
4697            name: "multi".to_owned(),
4698            internal_name: "multi".to_owned(),
4699            internal_uniq: Some(1),
4700            exported: true,
4701            pure: false,
4702            proof: true,
4703            arguments: vec![
4704                Argument {
4705                    name: "tag".to_owned(),
4706                    arg_type: bytes32_ty.clone(),
4707                },
4708                Argument {
4709                    name: "delta".to_owned(),
4710                    arg_type: u64_ty.clone(),
4711                },
4712            ],
4713            result_type: TypeDescriptor::Tuple {
4714                types: vec![u64_ty.clone(), u64_ty.clone(), bytes32_ty.clone()],
4715            },
4716            body: Statement::Seq {
4717                items: vec![
4718                    Statement::Expr { value: inc_static },
4719                    Statement::Expr {
4720                        value: write_cell_dynamic,
4721                    },
4722                    Statement::Const {
4723                        binding: BindingTarget {
4724                            name: "c1".to_owned(),
4725                            binding_type: u64_ty.clone(),
4726                        },
4727                        value: read_slot_expr("Counter", "count", 0, u64_ty.clone()),
4728                    },
4729                    Statement::Expr { value: inc_dynamic },
4730                    Statement::Const {
4731                        binding: BindingTarget {
4732                            name: "t".to_owned(),
4733                            binding_type: bytes32_ty.clone(),
4734                        },
4735                        value: read_slot_expr("Cell", "tag", 1, bytes32_ty),
4736                    },
4737                    Statement::Const {
4738                        binding: BindingTarget {
4739                            name: "c2".to_owned(),
4740                            binding_type: u64_ty.clone(),
4741                        },
4742                        value: read_slot_expr("Counter", "count", 0, u64_ty),
4743                    },
4744                    Statement::Expr {
4745                        value: Expression::Tuple {
4746                            items: vec![tuple_var("c1"), tuple_var("c2"), tuple_var("t")],
4747                        },
4748                    },
4749                ],
4750            },
4751        });
4752        ir
4753    }
4754
4755    #[tokio::test]
4756    async fn precompiled_queries_and_persistent_query_context_match_uncached_baseline() {
4757        let ir_arc = Arc::new(build_multi_op_ir());
4758        let idx = IrIndex::build(&ir_arc);
4759        // 1 init op + 6 circuit adt ops = 7 pre-compiled queries cached
4760        assert_eq!(idx.compiled_query_count(), 7);
4761
4762        let coin_pk = CoinPublicKey([0x12u8; 32]);
4763        let exec = IrExecutable::new(ir_arc.clone(), Arc::new(NoWitnesses));
4764        let signing_key = moonproof_ledger::signatures::schnorr_signing_key(&[0x11u8; 32]).unwrap();
4765        let init = exec
4766            .initialize(
4767                ConstructorContext {
4768                    initial_private_state: Value::Null,
4769                    initial_zswap_local_state: CompactZswapLocalState::empty(coin_pk),
4770                    coin_public_key: coin_pk,
4771                    signing_key,
4772                    time: Some(Timestamp::from_secs(0)),
4773                },
4774                Value::Null,
4775            )
4776            .await
4777            .unwrap();
4778
4779        let tag_bytes = vec![0x9au8; 32];
4780        let args = Value::Array(vec![Value::Bytes(tag_bytes.clone()), Value::Int(7)]);
4781
4782        let fast = exec
4783            .execute_circuit(
4784                "multi",
4785                make_ctx(init.initial_contract_state.clone(), coin_pk),
4786                args,
4787            )
4788            .await
4789            .unwrap();
4790        assert_eq!(
4791            fast.result,
4792            Value::Array(vec![
4793                Value::Int(15),
4794                Value::Int(22),
4795                Value::Bytes(tag_bytes.clone()),
4796            ])
4797        );
4798        assert_eq!(fast.popeq_read_results.len(), 3);
4799
4800        let mut baseline_args = VarMap::default();
4801        baseline_args.insert("tag".to_owned(), Value::Bytes(tag_bytes));
4802        baseline_args.insert("delta".to_owned(), Value::Int(7));
4803        let mut baseline_state = InterpState {
4804            ir: &ir_arc,
4805            index: None,
4806            contract_state: init.initial_contract_state,
4807            contract_address: ContractAddress(HashOutput([0x44u8; 32])),
4808            private_state: Value::Null,
4809            locals: VarMap::default(),
4810            args: baseline_args,
4811            public_transcript: Vec::new(),
4812            private_transcript_outputs: Vec::new(),
4813            popeq_read_results: Vec::new(),
4814            witnesses: Arc::new(NoWitnesses),
4815            coin_commitments: Vec::new(),
4816            next_zswap_local_state: CompactZswapLocalState::empty(coin_pk),
4817            emitted_events: Vec::new(),
4818            tblock: Timestamp::from_secs(100),
4819            caller: None,
4820            call_tree: None,
4821            effects: moonproof_ledger::onchain_runtime::context::Effects::default(),
4822            vm_session: None,
4823            contract_label: String::new(),
4824            circuit_name: String::new(),
4825            trace: None,
4826            trace_level: crate::trace::TraceLevel::Off,
4827            trace_depth: 0,
4828            coverage: None,
4829        };
4830        let baseline_result = run_statement(&mut baseline_state, &ir_arc.circuits[0].body).unwrap();
4831        baseline_state.sync_from_query_context();
4832
4833        assert_eq!(fast.result, baseline_result);
4834        assert_eq!(fast.popeq_read_results, baseline_state.popeq_read_results);
4835        assert_eq!(fast.public_transcript, baseline_state.public_transcript);
4836
4837        let mut fast_bytes = Vec::new();
4838        moonproof_ledger::serialize::tagged_serialize(&fast.next_contract_state, &mut fast_bytes)
4839            .unwrap();
4840        let mut base_bytes = Vec::new();
4841        moonproof_ledger::serialize::tagged_serialize(
4842            &baseline_state.contract_state,
4843            &mut base_bytes,
4844        )
4845        .unwrap();
4846        assert_eq!(fast_bytes, base_bytes);
4847    }
4848
4849    #[test]
4850    #[allow(clippy::too_many_lines)]
4851    fn fast_scalar_equality_matches_aligned_value_encoding_across_edge_cases() {
4852        let check = |ty: &TypeDescriptor, l: &Value, r: &Value| {
4853            let fast = values_equal_typed(Some(ty), l, r);
4854            let ref_eq =
4855                encode_literal(ty, l).and_then(|la| encode_literal(ty, r).map(|ra| la == ra));
4856            match (fast, ref_eq) {
4857                (Ok(a), Ok(b)) => assert_eq!(a, b, "equality mismatch for {ty:?}: {l:?} vs {r:?}"),
4858                (Err(_), Err(_)) => {}
4859                (f, s) => {
4860                    panic!("result mismatch for {ty:?} ({l:?} vs {r:?}): fast={f:?}, slow={s:?}")
4861                }
4862            }
4863        };
4864
4865        // Bool
4866        for (l, r) in [
4867            (Value::Bool(true), Value::Bool(true)),
4868            (Value::Bool(true), Value::Bool(false)),
4869            (Value::Bool(false), Value::Bool(false)),
4870            (Value::Bool(false), Value::Int(0)),
4871        ] {
4872            check(&TypeDescriptor::Boolean, &l, &r);
4873        }
4874
4875        // Uint (u8, u64, u128, string vs int, overflow, negative)
4876        let u8_ty = TypeDescriptor::Uint {
4877            maxval: IntLit::from_u128(255),
4878            alignment_bytes: None,
4879        };
4880        let u128_ty = TypeDescriptor::Uint {
4881            maxval: IntLit::from_u128(u128::MAX),
4882            alignment_bytes: None,
4883        };
4884        for (ty, l, r) in [
4885            (&u8_ty, Value::Int(0), Value::Int(0)),
4886            (&u8_ty, Value::Int(255), Value::String("255".to_owned())),
4887            (&u8_ty, Value::Int(10), Value::Int(11)),
4888            (&u8_ty, Value::Int(256), Value::Int(256)),
4889            (&u8_ty, Value::Int(-1), Value::Int(0)),
4890            (
4891                &u128_ty,
4892                Value::String(u128::MAX.to_string()),
4893                Value::String(u128::MAX.to_string()),
4894            ),
4895            (
4896                &u128_ty,
4897                Value::String(u128::MAX.to_string()),
4898                Value::Int(0),
4899            ),
4900            (
4901                &TypeDescriptor::Counter,
4902                Value::Int(42),
4903                Value::String("42".to_owned()),
4904            ),
4905            (
4906                &TypeDescriptor::Counter,
4907                Value::String((u128::from(u64::MAX) + 1).to_string()),
4908                Value::Int(0),
4909            ),
4910        ] {
4911            check(ty, &l, &r);
4912        }
4913
4914        // Field (int vs 32-byte LE bytes vs decimal string, out-of-range)
4915        let mut le_258 = vec![0u8; 32];
4916        le_258[0] = 2;
4917        le_258[1] = 1;
4918        for (l, r) in [
4919            (Value::Int(0), Value::Bytes(vec![0u8; 32])),
4920            (Value::Int(258), Value::Bytes(le_258.clone())),
4921            (
4922                Value::String("258".to_owned()),
4923                Value::Bytes(le_258.clone()),
4924            ),
4925            (Value::Int(258), Value::Int(259)),
4926            (Value::Bytes(vec![0xff; 32]), Value::Bytes(vec![0xff; 32])),
4927            (Value::Int(-5), Value::Int(-5)),
4928        ] {
4929            check(&TypeDescriptor::Field, &l, &r);
4930        }
4931
4932        // Bytes (equal, trailing zeros, distinct, hex string, wrong length)
4933        let b4 = TypeDescriptor::Bytes { length: 4 };
4934        for (l, r) in [
4935            (
4936                Value::Bytes(vec![0, 0, 0, 0]),
4937                Value::Bytes(vec![0, 0, 0, 0]),
4938            ),
4939            (
4940                Value::Bytes(vec![1, 2, 0, 0]),
4941                Value::Bytes(vec![1, 2, 0, 0]),
4942            ),
4943            (
4944                Value::Bytes(vec![1, 2, 0, 0]),
4945                Value::Bytes(vec![1, 2, 0, 1]),
4946            ),
4947            (
4948                Value::Bytes(vec![0xaa, 0xbb, 0xcc, 0xdd]),
4949                Value::String("aabbccdd".to_owned()),
4950            ),
4951            (Value::Bytes(vec![1, 2, 3]), Value::Bytes(vec![1, 2, 3])),
4952        ] {
4953            check(&b4, &l, &r);
4954        }
4955
4956        // Enum (valid equal, valid distinct, invalid variant error parity)
4957        let enum_ty = TypeDescriptor::Enum {
4958            name: "Mode".to_owned(),
4959            elements: vec!["A".to_owned(), "B".to_owned()],
4960        };
4961        for (l, r) in [
4962            (Value::String("A".to_owned()), Value::String("A".to_owned())),
4963            (Value::String("A".to_owned()), Value::String("B".to_owned())),
4964            (
4965                Value::String("Invalid".to_owned()),
4966                Value::String("Invalid".to_owned()),
4967            ),
4968        ] {
4969            check(&enum_ty, &l, &r);
4970        }
4971
4972        // Alias wrapping a primitive
4973        let aliased = TypeDescriptor::Alias {
4974            name: "MyField".to_owned(),
4975            of: Box::new(TypeDescriptor::Field),
4976        };
4977        check(&aliased, &Value::Int(258), &Value::Bytes(le_258));
4978    }
4979
4980    #[tokio::test]
4981    async fn pure_native_classes_route_to_eval_native_circuit() {
4982        let coin_pk = CoinPublicKey([0x33u8; 32]);
4983        let bytes32 = TypeDescriptor::Bytes { length: 32 };
4984        let byte_arg = vec![Argument {
4985            name: "x".to_owned(),
4986            arg_type: bytes32.clone(),
4987        }];
4988        let var_x = vec![Expression::Var {
4989            name: "x".to_owned(),
4990        }];
4991        let input = Value::Bytes(vec![0x42u8; 32]);
4992
4993        let baseline = run_native_ir(
4994            Native::new_intrinsic(
4995                "persistentHash",
4996                "persistentHash",
4997                "circuit",
4998                byte_arg.clone(),
4999                bytes32.clone(),
5000            ),
5001            var_x.clone(),
5002            byte_arg.clone(),
5003            bytes32.clone(),
5004            input.clone(),
5005            coin_pk,
5006        )
5007        .await;
5008
5009        for class in ["hash", "commit", "crypto", "curve", "pure"] {
5010            let res = run_native_ir(
5011                Native::new_intrinsic(
5012                    "zk_hash",
5013                    "mp:hash/persistent",
5014                    class,
5015                    byte_arg.clone(),
5016                    bytes32.clone(),
5017                ),
5018                var_x.clone(),
5019                byte_arg.clone(),
5020                bytes32.clone(),
5021                input.clone(),
5022                coin_pk,
5023            )
5024            .await;
5025            assert_eq!(
5026                res.result, baseline.result,
5027                "class '{class}' must match baseline persistentHash"
5028            );
5029            assert_eq!(res.output, baseline.output);
5030        }
5031    }
5032
5033    #[test]
5034    fn ir_index_guards_lookups_on_ir_pointer_identity() {
5035        let mut ir_a = MoonIr::new_v3("0.1.0", "0.1.0", "0.1.0");
5036        ir_a.add_circuit(CircuitBody {
5037            name: "foo".to_owned(),
5038            internal_name: "foo".to_owned(),
5039            internal_uniq: Some(1),
5040            exported: true,
5041            pure: true,
5042            proof: false,
5043            arguments: Vec::new(),
5044            result_type: TypeDescriptor::Field,
5045            body: Statement::Expr {
5046                value: Expression::Literal {
5047                    value: Value::Int(1),
5048                },
5049            },
5050        });
5051        let ir_a = Arc::new(ir_a);
5052        let ir_b = Arc::new((*ir_a).clone());
5053
5054        let idx = IrIndex::build(&ir_a);
5055        assert!(idx.matches_ir(&ir_a));
5056        assert!(!idx.matches_ir(&ir_b));
5057        assert!(idx.first_circuit(&ir_a, "foo").is_some());
5058        assert!(idx.first_circuit(&ir_b, "foo").is_none());
5059        assert!(idx.circuit_io_plan(&ir_a, &ir_a.circuits[0]).is_some());
5060        assert!(idx.circuit_io_plan(&ir_b, &ir_b.circuits[0]).is_none());
5061    }
5062
5063    #[tokio::test]
5064    #[allow(clippy::too_many_lines)]
5065    async fn native_ed25519_verify_accepts_valid_and_rejects_tampered_or_non_canonical() {
5066        use ethnum::U256;
5067        use moonproof_ledger::foreign_curve::{self as fc, ForeignCurve};
5068        use sha2::Digest;
5069
5070        if !moonproof_ledger::HAS_ZKIR_V3 {
5071            return;
5072        }
5073
5074        // Keypair: sk = 1 -> pk = B (Curve25519 generator); nonce r = 2 -> R = 2*B.
5075        let b_pt = fc::mul_generator(ForeignCurve::Curve25519, &U256::ONE.to_le_bytes()).unwrap();
5076        let pk_bytes = fc::to_bytes(ForeignCurve::Curve25519, &b_pt).unwrap();
5077        let r_pt =
5078            fc::mul_generator(ForeignCurve::Curve25519, &U256::from(2u64).to_le_bytes()).unwrap();
5079        let r_bytes = fc::to_bytes(ForeignCurve::Curve25519, &r_pt).unwrap();
5080
5081        let msg = [0x42u8; 32];
5082        let mut h = sha2::Sha512::new();
5083        h.update(&r_bytes);
5084        h.update(&pk_bytes);
5085        h.update(msg);
5086        let digest: [u8; 64] = h.finalize().into();
5087
5088        let l = num_bigint::BigUint::from_bytes_le(
5089            &super::super::curve::CURVE25519_SCALAR_MODULUS.to_le_bytes(),
5090        );
5091        let mut k_le = (num_bigint::BigUint::from_bytes_le(&digest) % &l).to_bytes_le();
5092        k_le.resize(32, 0);
5093        let k_u256 = U256::from_le_bytes(k_le.try_into().unwrap());
5094        let s_u256 = (U256::from(2u64) + k_u256) % super::super::curve::CURVE25519_SCALAR_MODULUS;
5095
5096        let mut sig_valid = [0u8; 64];
5097        sig_valid[..32].copy_from_slice(&r_bytes);
5098        sig_valid[32..].copy_from_slice(&s_u256.to_le_bytes());
5099
5100        let coin_pk = CoinPublicKey([0x11u8; 32]);
5101        let b32 = TypeDescriptor::Bytes { length: 32 };
5102        let b64 = TypeDescriptor::Bytes { length: 64 };
5103        let args = vec![
5104            Argument {
5105                name: "msg".to_owned(),
5106                arg_type: b32.clone(),
5107            },
5108            Argument {
5109                name: "sig".to_owned(),
5110                arg_type: b64.clone(),
5111            },
5112            Argument {
5113                name: "pk".to_owned(),
5114                arg_type: b32.clone(),
5115            },
5116        ];
5117        let call_args = vec![
5118            Expression::Var {
5119                name: "msg".to_owned(),
5120            },
5121            Expression::Var {
5122                name: "sig".to_owned(),
5123            },
5124            Expression::Var {
5125                name: "pk".to_owned(),
5126            },
5127        ];
5128        let ir = ir_calling_native(
5129            Native::new_intrinsic(
5130                "ed25519Verify",
5131                "ed25519Verify",
5132                "circuit",
5133                args.clone(),
5134                TypeDescriptor::Boolean,
5135            ),
5136            call_args,
5137            args,
5138            TypeDescriptor::Boolean,
5139        );
5140        let (exec, state) = init_empty(ir, coin_pk).await;
5141
5142        // 1. Valid signature -> true
5143        let ok = exec
5144            .execute_circuit(
5145                "run",
5146                make_ctx(state.clone(), coin_pk),
5147                Value::Array(vec![
5148                    Value::Bytes(msg.to_vec()),
5149                    Value::Bytes(sig_valid.to_vec()),
5150                    Value::Bytes(pk_bytes.clone()),
5151                ]),
5152            )
5153            .await
5154            .unwrap();
5155        assert_eq!(ok.result, Value::Bool(true));
5156
5157        // 2. Tampered message -> false
5158        let mut bad_msg = msg;
5159        bad_msg[0] ^= 0x01;
5160        let bad_msg_res = exec
5161            .execute_circuit(
5162                "run",
5163                make_ctx(state.clone(), coin_pk),
5164                Value::Array(vec![
5165                    Value::Bytes(bad_msg.to_vec()),
5166                    Value::Bytes(sig_valid.to_vec()),
5167                    Value::Bytes(pk_bytes.clone()),
5168                ]),
5169            )
5170            .await
5171            .unwrap();
5172        assert_eq!(bad_msg_res.result, Value::Bool(false));
5173
5174        // 3. Tampered scalar -> false
5175        let mut bad_sig = sig_valid;
5176        bad_sig[32] ^= 0x01;
5177        let bad_sig_res = exec
5178            .execute_circuit(
5179                "run",
5180                make_ctx(state.clone(), coin_pk),
5181                Value::Array(vec![
5182                    Value::Bytes(msg.to_vec()),
5183                    Value::Bytes(bad_sig.to_vec()),
5184                    Value::Bytes(pk_bytes.clone()),
5185                ]),
5186            )
5187            .await
5188            .unwrap();
5189        assert_eq!(bad_sig_res.result, Value::Bool(false));
5190
5191        // 4. Non-canonical malleated scalar s + L -> false
5192        let s_malleated = s_u256 + super::super::curve::CURVE25519_SCALAR_MODULUS;
5193        let mut mal_sig = [0u8; 64];
5194        mal_sig[..32].copy_from_slice(&r_bytes);
5195        mal_sig[32..].copy_from_slice(&s_malleated.to_le_bytes());
5196        let mal_res = exec
5197            .execute_circuit(
5198                "run",
5199                make_ctx(state.clone(), coin_pk),
5200                Value::Array(vec![
5201                    Value::Bytes(msg.to_vec()),
5202                    Value::Bytes(mal_sig.to_vec()),
5203                    Value::Bytes(pk_bytes.clone()),
5204                ]),
5205            )
5206            .await
5207            .unwrap();
5208        assert_eq!(mal_res.result, Value::Bool(false));
5209
5210        // 5. Struct { r: Bytes<32>, s: Bytes<32> } layout (Pact 5 shape) -> true
5211        let sig_struct_ty = TypeDescriptor::Struct {
5212            name: "Ed25519Signature".to_owned(),
5213            elements: vec![
5214                moonproof_runtime_ir::ir::StructField {
5215                    name: "r".to_owned(),
5216                    field_type: b32.clone(),
5217                },
5218                moonproof_runtime_ir::ir::StructField {
5219                    name: "s".to_owned(),
5220                    field_type: b32.clone(),
5221                },
5222            ],
5223        };
5224        let struct_args = vec![
5225            Argument {
5226                name: "msg".to_owned(),
5227                arg_type: b32.clone(),
5228            },
5229            Argument {
5230                name: "sig".to_owned(),
5231                arg_type: sig_struct_ty,
5232            },
5233            Argument {
5234                name: "pk".to_owned(),
5235                arg_type: b32,
5236            },
5237        ];
5238        let mut sig_obj = std::collections::BTreeMap::new();
5239        sig_obj.insert("r".to_owned(), Value::Bytes(r_bytes));
5240        sig_obj.insert("s".to_owned(), Value::Bytes(s_u256.to_le_bytes().to_vec()));
5241        let struct_res = run_native_ir(
5242            Native::new_intrinsic(
5243                "ed25519Verify",
5244                "ed25519Verify",
5245                "circuit",
5246                struct_args.clone(),
5247                TypeDescriptor::Boolean,
5248            ),
5249            vec![
5250                Expression::Var {
5251                    name: "msg".to_owned(),
5252                },
5253                Expression::Var {
5254                    name: "sig".to_owned(),
5255                },
5256                Expression::Var {
5257                    name: "pk".to_owned(),
5258                },
5259            ],
5260            struct_args,
5261            TypeDescriptor::Boolean,
5262            Value::Array(vec![
5263                Value::Bytes(msg.to_vec()),
5264                Value::Object(sig_obj),
5265                Value::Bytes(pk_bytes),
5266            ]),
5267            coin_pk,
5268        )
5269        .await;
5270        assert_eq!(struct_res.result, Value::Bool(true));
5271    }
5272
5273    #[tokio::test]
5274    #[allow(clippy::too_many_lines)]
5275    async fn native_secp256r1_and_secp256k1_ecdsa_verify_semantics() {
5276        use ethnum::U256;
5277        use moonproof_ledger::foreign_curve::{self as fc, ForeignCurve};
5278
5279        if !moonproof_ledger::HAS_ZKIR_V3 {
5280            return;
5281        }
5282
5283        let cases = [
5284            (
5285                "secp256r1EcdsaVerify",
5286                ForeignCurve::Secp256r1,
5287                TypeDescriptor::Secp256r1Point,
5288                super::super::curve::SECP256R1_SCALAR_MODULUS,
5289            ),
5290            (
5291                "secp256k1EcdsaVerify",
5292                ForeignCurve::Secp256k1,
5293                TypeDescriptor::Secp256k1Point,
5294                super::super::curve::SECP256K1_SCALAR_MODULUS,
5295            ),
5296        ];
5297
5298        let coin_pk = CoinPublicKey([0x22u8; 32]);
5299        let b32 = TypeDescriptor::Bytes { length: 32 };
5300        let b33 = TypeDescriptor::Bytes { length: 33 };
5301        let sig_struct_ty = TypeDescriptor::Struct {
5302            name: "EcdsaSig".to_owned(),
5303            elements: vec![
5304                moonproof_runtime_ir::ir::StructField {
5305                    name: "r".to_owned(),
5306                    field_type: b32.clone(),
5307                },
5308                moonproof_runtime_ir::ir::StructField {
5309                    name: "s".to_owned(),
5310                    field_type: b32.clone(),
5311                },
5312            ],
5313        };
5314
5315        for (intrinsic, curve, point_ty, n) in cases {
5316            // Valid signature with pk = G (sk = 1), k = 1 -> R = G, r = gx mod n,
5317            // z = (1 - r) mod n, s = 1 -> u1 = 1 - r, u2 = r -> pt = G -> x mod n == r.
5318            let g_affine = fc::mul_generator(curve, &U256::ONE.to_le_bytes()).unwrap();
5319            let (gx_le, _) = g_affine.unwrap();
5320            let gx_u256 = U256::from_le_bytes(gx_le);
5321            let r_valid = gx_u256 % n;
5322            let z_valid = (n + U256::ONE - r_valid) % n;
5323            let s_valid = U256::ONE;
5324
5325            let pk_val = super::super::curve::affine_to_value(curve, &g_affine);
5326            let pk_compressed = fc::to_bytes(curve, &g_affine).unwrap();
5327            assert_eq!(pk_compressed.len(), 33);
5328
5329            let sig_obj = |r_u: U256, s_u: U256| {
5330                let mut m = std::collections::BTreeMap::new();
5331                m.insert("r".to_owned(), Value::Bytes(r_u.to_be_bytes().to_vec()));
5332                m.insert("s".to_owned(), Value::Bytes(s_u.to_be_bytes().to_vec()));
5333                Value::Object(m)
5334            };
5335
5336            let native_args = vec![
5337                Argument {
5338                    name: "msg_hash".to_owned(),
5339                    arg_type: b32.clone(),
5340                },
5341                Argument {
5342                    name: "sig".to_owned(),
5343                    arg_type: sig_struct_ty.clone(),
5344                },
5345                Argument {
5346                    name: "pk".to_owned(),
5347                    arg_type: point_ty.clone(),
5348                },
5349            ];
5350            let ir = ir_calling_native(
5351                Native::new_intrinsic(
5352                    intrinsic,
5353                    intrinsic,
5354                    "circuit",
5355                    native_args.clone(),
5356                    TypeDescriptor::Boolean,
5357                ),
5358                vec![
5359                    Expression::Var {
5360                        name: "msg_hash".to_owned(),
5361                    },
5362                    Expression::Var {
5363                        name: "sig".to_owned(),
5364                    },
5365                    Expression::Var {
5366                        name: "pk".to_owned(),
5367                    },
5368                ],
5369                native_args.clone(),
5370                TypeDescriptor::Boolean,
5371            );
5372            let (exec, state) = init_empty(ir, coin_pk).await;
5373
5374            // 1. Valid signature -> true
5375            let ok = exec
5376                .execute_circuit(
5377                    "run",
5378                    make_ctx(state.clone(), coin_pk),
5379                    Value::Array(vec![
5380                        Value::Bytes(z_valid.to_be_bytes().to_vec()),
5381                        sig_obj(r_valid, s_valid),
5382                        pk_val.clone(),
5383                    ]),
5384                )
5385                .await
5386                .unwrap();
5387            assert_eq!(ok.result, Value::Bool(true), "{intrinsic} valid sig");
5388
5389            // 2. Tampered message hash -> false
5390            let bad_z = exec
5391                .execute_circuit(
5392                    "run",
5393                    make_ctx(state.clone(), coin_pk),
5394                    Value::Array(vec![
5395                        Value::Bytes((z_valid + U256::ONE).to_be_bytes().to_vec()),
5396                        sig_obj(r_valid, s_valid),
5397                        pk_val.clone(),
5398                    ]),
5399                )
5400                .await
5401                .unwrap();
5402            assert_eq!(bad_z.result, Value::Bool(false), "{intrinsic} tampered msg");
5403
5404            // 3. Tampered signature s -> false
5405            let bad_s = exec
5406                .execute_circuit(
5407                    "run",
5408                    make_ctx(state.clone(), coin_pk),
5409                    Value::Array(vec![
5410                        Value::Bytes(z_valid.to_be_bytes().to_vec()),
5411                        sig_obj(r_valid, U256::from(2u64)),
5412                        pk_val.clone(),
5413                    ]),
5414                )
5415                .await
5416                .unwrap();
5417            assert_eq!(bad_s.result, Value::Bool(false), "{intrinsic} tampered sig");
5418
5419            // 4. Non-canonical scalar s = n + 1 -> false
5420            let non_canon = exec
5421                .execute_circuit(
5422                    "run",
5423                    make_ctx(state.clone(), coin_pk),
5424                    Value::Array(vec![
5425                        Value::Bytes(z_valid.to_be_bytes().to_vec()),
5426                        sig_obj(r_valid, n + U256::ONE),
5427                        pk_val.clone(),
5428                    ]),
5429                )
5430                .await
5431                .unwrap();
5432            assert_eq!(
5433                non_canon.result,
5434                Value::Bool(false),
5435                "{intrinsic} non-canonical s"
5436            );
5437
5438            // 5. Identity point pt == O (z = 1, r = n - 1, s = 1 -> G + (-G) = O) -> false
5439            let id_pt = exec
5440                .execute_circuit(
5441                    "run",
5442                    make_ctx(state.clone(), coin_pk),
5443                    Value::Array(vec![
5444                        Value::Bytes(U256::ONE.to_be_bytes().to_vec()),
5445                        sig_obj(n - U256::ONE, U256::ONE),
5446                        pk_val.clone(),
5447                    ]),
5448                )
5449                .await
5450                .unwrap();
5451            assert_eq!(
5452                id_pt.result,
5453                Value::Bool(false),
5454                "{intrinsic} identity pt == O"
5455            );
5456
5457            // 6. CastFromBytes(Bytes<33> -> Point) path (Pact 5 compressed pubkey shape) -> true
5458            let compressed_circuit_args = vec![
5459                Argument {
5460                    name: "msg_hash".to_owned(),
5461                    arg_type: b32.clone(),
5462                },
5463                Argument {
5464                    name: "sig".to_owned(),
5465                    arg_type: sig_struct_ty.clone(),
5466                },
5467                Argument {
5468                    name: "pk_bytes".to_owned(),
5469                    arg_type: b33.clone(),
5470                },
5471            ];
5472            let compressed_res = run_native_ir(
5473                Native::new_intrinsic(
5474                    intrinsic,
5475                    intrinsic,
5476                    "circuit",
5477                    native_args,
5478                    TypeDescriptor::Boolean,
5479                ),
5480                vec![
5481                    Expression::Var {
5482                        name: "msg_hash".to_owned(),
5483                    },
5484                    Expression::Var {
5485                        name: "sig".to_owned(),
5486                    },
5487                    Expression::CastFromBytes {
5488                        to: point_ty,
5489                        length: 33,
5490                        value: Box::new(Expression::Var {
5491                            name: "pk_bytes".to_owned(),
5492                        }),
5493                    },
5494                ],
5495                compressed_circuit_args,
5496                TypeDescriptor::Boolean,
5497                Value::Array(vec![
5498                    Value::Bytes(z_valid.to_be_bytes().to_vec()),
5499                    sig_obj(r_valid, s_valid),
5500                    Value::Bytes(pk_compressed),
5501                ]),
5502                coin_pk,
5503            )
5504            .await;
5505            assert_eq!(
5506                compressed_res.result,
5507                Value::Bool(true),
5508                "{intrinsic} CastFromBytes compressed pk"
5509            );
5510        }
5511    }
5512
5513    #[tokio::test]
5514    async fn downcast_unsigned_enforces_maxval_for_uint16_uint32_uint64_and_bounded() {
5515        let cases: &[(&str, u128, u128)] = &[
5516            ("u8", u128::from(u8::MAX), u128::from(u64::MAX)),
5517            ("u16", u128::from(u16::MAX), u128::from(u64::MAX)),
5518            ("u32", u128::from(u32::MAX), u128::from(u64::MAX)),
5519            ("u64", u128::from(u64::MAX), u128::MAX),
5520            ("bounded_100", 100, u128::from(u64::MAX)),
5521        ];
5522
5523        let mut ir = moonproof_runtime_ir::MoonIr::new_v3("0.36.1", "0.28.0", "0.14.0");
5524        for &(name, maxval, from_max) in cases {
5525            ir.add_circuit(moonproof_runtime_ir::ir::CircuitBody {
5526                name: name.to_owned(),
5527                internal_name: format!("_{name}"),
5528                internal_uniq: None,
5529                exported: true,
5530                pure: true,
5531                proof: true,
5532                arguments: vec![moonproof_runtime_ir::ir::Argument {
5533                    name: "x".to_owned(),
5534                    arg_type: TypeDescriptor::Uint {
5535                        maxval: IntLit::from_u128(from_max),
5536                        alignment_bytes: None,
5537                    },
5538                }],
5539                result_type: TypeDescriptor::Uint {
5540                    maxval: IntLit::from_u128(maxval),
5541                    alignment_bytes: None,
5542                },
5543                body: Statement::Expr {
5544                    value: Expression::DowncastUnsigned {
5545                        from_bits: Some(IntLit::from_u128(from_max)),
5546                        to_bits: IntLit::from_u128(maxval),
5547                        value: Box::new(Expression::Var {
5548                            name: "x".to_owned(),
5549                        }),
5550                    },
5551                },
5552            });
5553        }
5554
5555        let coin_pk = crate::types::CoinPublicKey([0x11; 32]);
5556        let (exec, state) = init_empty(ir, coin_pk).await;
5557
5558        for &(name, maxval, _) in cases {
5559            // Both bytecode VM (no coverage) and tree-walk interpreter (coverage enabled)
5560            // must accept `maxval` and reject `maxval + 1`.
5561            let at_max = uint_value(maxval);
5562            let over_max = uint_value(maxval + 1);
5563
5564            let res_vm = exec
5565                .execute_circuit(name, make_ctx(state.clone(), coin_pk), at_max.clone())
5566                .await
5567                .unwrap_or_else(|e| panic!("VM {name} at maxval={maxval} failed: {e}"));
5568            assert_eq!(res_vm.result, at_max, "VM {name} at maxval");
5569
5570            let err_vm = exec
5571                .execute_circuit(name, make_ctx(state.clone(), coin_pk), over_max.clone())
5572                .await;
5573            assert!(
5574                err_vm.is_err(),
5575                "VM {name} at maxval+1 ({}) must overflow",
5576                maxval + 1
5577            );
5578
5579            // Exercise tree-walk interpreter via `execute_circuit_traced`.
5580            let mut trace = crate::trace::ExecutionTrace::default();
5581            let res_interp = exec
5582                .execute_circuit_traced(
5583                    name,
5584                    make_ctx(state.clone(), coin_pk),
5585                    at_max.clone(),
5586                    crate::trace::TraceLevel::Full,
5587                    Some(&mut trace),
5588                )
5589                .await
5590                .unwrap_or_else(|e| panic!("interp {name} at maxval={maxval} failed: {e}"));
5591            assert_eq!(res_interp.result, at_max, "interp {name} at maxval");
5592
5593            let err_interp = exec
5594                .execute_circuit_traced(
5595                    name,
5596                    make_ctx(state.clone(), coin_pk),
5597                    over_max,
5598                    crate::trace::TraceLevel::Full,
5599                    Some(&mut trace),
5600                )
5601                .await;
5602            assert!(
5603                err_interp.is_err(),
5604                "interp {name} at maxval+1 ({}) must overflow",
5605                maxval + 1
5606            );
5607        }
5608    }
5609}