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