Skip to main content

moonproof_runtime/
ir_executable.rs

1//! [`IrExecutable`] — the runtime-ir-driven off-chain executor.
2//!
3//! Loads a parsed `contract.mpir` ([`MoonIr`]) plus a host-supplied
4//! [`Witnesses`] callback table, and exposes inherent methods for
5//! `initialize` (run the constructor) and `execute_circuit` (run a
6//! provable circuit body) by walking the IR's Statement / Expression
7//! tree at call time.
8//!
9//! Arguments are `serde_json::Value`. The IR's argument descriptors
10//! tell the executor how to encode each `Value` into the
11//! `AlignedValue` shape the on-chain VM expects. Callers never build
12//! `AlignedValue`s by hand.
13
14use std::sync::{Arc, OnceLock};
15
16use moonproof_ledger::base_crypto::hash::HashOutput;
17use moonproof_ledger::base_crypto::time::Timestamp;
18use moonproof_ledger::coin_structure::contract::ContractAddress;
19use moonproof_ledger::onchain_runtime::ops::Op;
20use moonproof_ledger::onchain_runtime::result_mode::ResultModeGather;
21use moonproof_ledger::onchain_runtime::state::{
22    ContractMaintenanceAuthority, ContractOperation, ContractState, EntryPointBuf, StateValue,
23};
24use moonproof_ledger::storage::db::InMemoryDB;
25use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
26use moonproof_runtime_ir::ir::{Argument, MoonIr};
27use moonproof_runtime_ir::RuntimeValue as Value;
28
29use rand::rngs::StdRng;
30use rand::{CryptoRng, Rng, SeedableRng};
31
32use crate::cross_contract::{CallTreeOutcome, CallTreeResult, CallTreeRun, CrossContractSession};
33use crate::error::{ContractRuntimeError, Result as RuntimeResult};
34use crate::executable::{
35    CircuitCallContext, ConstructorContext, ExecuteCircuitResult, InitializeResult,
36};
37use crate::ir::bytecode::BytecodeVm;
38use crate::ir::descriptor::encode_literal;
39use crate::ir::error::{IrDriverError, Result};
40use crate::ir::index::IrIndex;
41use crate::ir::interp::{
42    empty_contract_state, empty_effects, encode_input, encode_input_with_index,
43    encode_output_with_index, run_statement, InterpState, VarMap, VmSession,
44};
45use crate::ir::state_value::build_state_value;
46use crate::ir::vm_decode::{
47    analyze_ops, decode_op, CompiledLedgerQuery, CompiledQueryBody, EvalScope, QueryFlags,
48};
49use crate::ir::vm_val::VmVal;
50use crate::ir::witnesses::Witnesses;
51use crate::zswap_local::CompactZswapLocalState;
52
53/// Parsed-once schema for one ledger field. Re-export of the IR's
54/// typed [`Storage`](moonproof_runtime_ir::ir::Storage) — kept as a
55/// public alias under the historical `LedgerFieldSchema` name so
56/// generated code referring to
57/// `moonproof_runtime::ir_executable::LedgerFieldSchema` keeps
58/// resolving without an emitter rebuild.
59pub use moonproof_runtime_ir::ir::Storage as LedgerFieldSchema;
60
61type CachedOperationsMap = StorageHashMap<EntryPointBuf, ContractOperation, InMemoryDB>;
62
63/// Off-chain executor backed by a parsed contract.mpir.
64pub struct IrExecutable<W: Witnesses + 'static> {
65    ir: Arc<MoonIr>,
66    index: Arc<IrIndex>,
67    witnesses: Arc<W>,
68    /// Lazily-cloned ledger field schemas for FFI/NAPI/WASM callers that
69    /// request an owned `Arc<Vec<LedgerFieldSchema>>`. Direct Rust callers
70    /// of [`Self::ledger_schema`] read directly from `ir.ledger` with zero
71    /// upfront cloning in [`Self::new`].
72    ledger_schemas: Arc<OnceLock<Arc<Vec<LedgerFieldSchema>>>>,
73    /// Optional per-circuit verifier keys to bake into the
74    /// `ContractState`'s operations table during `initialize`. When
75    /// present, the resulting deploy carries VKs that the ledger's
76    /// `well_formed` check accepts; without them, the operations
77    /// register with `None` (the deploy still succeeds, but a real
78    /// ledger rejects it because declared operations need a VK).
79    verifier_keys: Arc<std::collections::HashMap<String, crate::types::VerifierKey>>,
80    /// Cached `ContractState::operations` MPT built once for the current
81    /// `verifier_keys` map; invalidated when verifier keys are updated.
82    cached_operations: Arc<OnceLock<std::result::Result<CachedOperationsMap, String>>>,
83    /// Cached skeleton `StateValue` from `ir.constructor.initial_state`,
84    /// built lazily on first `initialize`.
85    skeleton_state: Arc<OnceLock<std::result::Result<StateValue<InMemoryDB>, String>>>,
86    /// Pre-registered coin commitments threaded into every
87    /// `execute_circuit` call's `QueryContext.call_context.com_indices`.
88    /// Required for circuits using `update-with-coin-check`
89    /// op-classes (e.g. `Cell.writeCoin`).
90    coin_commitments: Arc<Vec<(moonproof_ledger::coin_structure::coin::Commitment, u64)>>,
91    /// Optional human-readable contract name for execution trace output.
92    contract_name: Option<String>,
93    /// Default execution trace verbosity for [`Self::execute_circuit`] and
94    /// [`Self::execute_call_tree`].
95    trace_level: crate::trace::TraceLevel,
96    /// Lazily-built IR coverage site index. Never populated unless coverage
97    /// instrumentation is requested.
98    coverage_map: Arc<OnceLock<Arc<crate::coverage::IrCoverageMap>>>,
99}
100
101impl<W: Witnesses + 'static> std::fmt::Debug for IrExecutable<W> {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        f.debug_struct("IrExecutable")
104            .field("schema_version", &self.ir.schema_version)
105            .field("compiler_version", &self.ir.compiler_version)
106            .field("circuits", &self.ir.circuits.len())
107            .field("witnesses", &self.ir.witnesses.len())
108            .finish_non_exhaustive()
109    }
110}
111
112impl<W: Witnesses + 'static> Clone for IrExecutable<W> {
113    fn clone(&self) -> Self {
114        Self {
115            ir: self.ir.clone(),
116            index: self.index.clone(),
117            witnesses: self.witnesses.clone(),
118            ledger_schemas: self.ledger_schemas.clone(),
119            verifier_keys: self.verifier_keys.clone(),
120            cached_operations: self.cached_operations.clone(),
121            skeleton_state: self.skeleton_state.clone(),
122            coin_commitments: self.coin_commitments.clone(),
123            contract_name: self.contract_name.clone(),
124            trace_level: self.trace_level,
125            coverage_map: self.coverage_map.clone(),
126        }
127    }
128}
129
130impl<W: Witnesses + 'static> IrExecutable<W> {
131    /// Build an executable from a parsed IR + witnesses callback.
132    #[must_use]
133    pub fn new(ir: Arc<MoonIr>, witnesses: Arc<W>) -> Self {
134        let index = Arc::new(IrIndex::build(&ir));
135        Self {
136            ir,
137            index,
138            witnesses,
139            ledger_schemas: Arc::new(OnceLock::new()),
140            verifier_keys: Arc::new(std::collections::HashMap::new()),
141            cached_operations: Arc::new(OnceLock::new()),
142            skeleton_state: Arc::new(OnceLock::new()),
143            coin_commitments: Arc::new(Vec::new()),
144            contract_name: None,
145            trace_level: crate::trace::TraceLevel::Off,
146            coverage_map: Arc::new(OnceLock::new()),
147        }
148    }
149
150    /// Lazily build and return the IR coverage site map for this executable.
151    #[must_use]
152    pub fn coverage_map(&self) -> Arc<crate::coverage::IrCoverageMap> {
153        self.coverage_map
154            .get_or_init(|| Arc::new(crate::coverage::IrCoverageMap::build(&self.ir)))
155            .clone()
156    }
157
158    /// Read-only access to a ledger field schema, indexed parallel to
159    /// `ir().ledger`, directly borrowing from the underlying `MoonIr`.
160    #[must_use]
161    pub fn ledger_schema(&self, index: usize) -> Option<&LedgerFieldSchema> {
162        self.ir.ledger.get(index).map(|f| &f.storage)
163    }
164
165    /// Shared handle to the parsed-once ledger schemas. FFI bindings
166    /// hand this out as an opaque Object so emitted code can pass it
167    /// to `ContractStateHandle::from_bytes_with_schemas` without
168    /// re-parsing per call.
169    #[must_use]
170    pub fn ledger_schemas_arc(&self) -> Arc<Vec<LedgerFieldSchema>> {
171        self.ledger_schemas
172            .get_or_init(|| Arc::new(self.ir.ledger.iter().map(|f| f.storage.clone()).collect()))
173            .clone()
174    }
175
176    /// Convenience: load an IR file from disk and build the executable.
177    pub fn from_path(path: impl AsRef<std::path::Path>, witnesses: Arc<W>) -> Result<Self> {
178        let ir = moonproof_runtime_ir::from_path(path)?;
179        Ok(Self::new(Arc::new(ir), witnesses))
180    }
181
182    /// Parse an IR CBOR byte slice (typically
183    /// `include_bytes!("contract.mpir")`) and build the executable.
184    /// Avoids disk IO at runtime.
185    pub fn from_cbor_slice(bytes: &[u8], witnesses: Arc<W>) -> Result<Self> {
186        let ir = moonproof_runtime_ir::from_cbor_slice(bytes)?;
187        Ok(Self::new(Arc::new(ir), witnesses))
188    }
189
190    /// Read-only access to the underlying IR (useful for callers that
191    /// want to introspect circuit signatures, ledger schema, etc.).
192    #[must_use]
193    pub fn ir(&self) -> &MoonIr {
194        &self.ir
195    }
196
197    #[cfg(test)]
198    #[must_use]
199    pub(crate) fn index(&self) -> &IrIndex {
200        &self.index
201    }
202
203    /// Attach verifier keys to be embedded into the
204    /// `ContractOperation` table during `initialize`. Map is keyed by
205    /// circuit name (matching the IR's `circuits[].name` and the
206    /// `register-operations` list). Required for the deploy to pass
207    /// `Transaction::well_formed`.
208    #[must_use]
209    pub fn with_verifier_keys(
210        mut self,
211        keys: std::collections::HashMap<String, crate::types::VerifierKey>,
212    ) -> Self {
213        self.verifier_keys = Arc::new(keys);
214        self.cached_operations = Arc::new(OnceLock::new());
215        self
216    }
217
218    /// In-place setter — use when the caller holds `&mut` to an
219    /// already-Arc'd executable (e.g. via [`std::sync::Arc::make_mut`]).
220    pub fn set_verifier_keys(
221        &mut self,
222        keys: std::collections::HashMap<String, crate::types::VerifierKey>,
223    ) {
224        self.verifier_keys = Arc::new(keys);
225        self.cached_operations = Arc::new(OnceLock::new());
226    }
227
228    /// Attach a single verifier key keyed by circuit name. Convenience
229    /// wrapper over [`with_verifier_keys`](Self::with_verifier_keys).
230    #[must_use]
231    pub fn with_verifier_key(
232        mut self,
233        circuit_name: impl Into<String>,
234        vk: crate::types::VerifierKey,
235    ) -> Self {
236        Arc::make_mut(&mut self.verifier_keys).insert(circuit_name.into(), vk);
237        self.cached_operations = Arc::new(OnceLock::new());
238        self
239    }
240
241    /// Attach pre-registered coin commitments. Each tuple is
242    /// `(coin_commitment, merkle_tree_index)`. Required for circuits
243    /// using `update-with-coin-check` op-classes (e.g.
244    /// `Cell.writeCoin`).
245    #[must_use]
246    pub fn with_coin_commitments(
247        mut self,
248        commitments: Vec<(moonproof_ledger::coin_structure::coin::Commitment, u64)>,
249    ) -> Self {
250        self.coin_commitments = Arc::new(commitments);
251        self
252    }
253
254    /// Attach a human-readable contract name used when rendering execution
255    /// traces (falls back to a short contract address hex when omitted).
256    #[must_use]
257    pub fn with_contract_name(mut self, name: impl Into<String>) -> Self {
258        self.contract_name = Some(name.into());
259        self
260    }
261
262    /// Configure the default [`crate::trace::TraceLevel`] for circuit
263    /// executions on this executable.
264    #[must_use]
265    pub fn with_trace_level(mut self, level: crate::trace::TraceLevel) -> Self {
266        self.trace_level = level;
267        self
268    }
269
270    /// Circuit ids the IR marks as exported AND provable.
271    #[must_use]
272    pub fn provable_circuit_ids(&self) -> Vec<crate::types::CircuitId> {
273        self.ir
274            .circuits
275            .iter()
276            .filter(|c| c.proof && c.exported)
277            .map(|c| crate::types::CircuitId::new(c.name.clone()))
278            .collect()
279    }
280
281    /// Verifier key for a circuit, if attached via
282    /// [`with_verifier_keys`](Self::with_verifier_keys).
283    #[must_use]
284    pub fn embedded_verifier_key(
285        &self,
286        circuit_id: &crate::types::CircuitId,
287    ) -> Option<crate::types::VerifierKey> {
288        self.verifier_keys.get(circuit_id.as_str()).cloned()
289    }
290
291    fn skeleton_state(&self) -> RuntimeResult<StateValue<InMemoryDB>> {
292        let res = self.skeleton_state.get_or_init(|| {
293            build_state_value(&self.ir.constructor.initial_state).map_err(|e| e.to_string())
294        });
295        match res {
296            Ok(sv) => Ok(sv.clone()),
297            Err(msg) => Err(driver_to_runtime_err(IrDriverError::InvalidIr(msg.clone()))),
298        }
299    }
300
301    fn cached_operations(&self) -> RuntimeResult<CachedOperationsMap> {
302        let res = self.cached_operations.get_or_init(|| {
303            let mut operations = StorageHashMap::new();
304            for op_name in &self.ir.constructor.register_operations {
305                let entry: EntryPointBuf = op_name.as_bytes().into();
306                let op = match self.verifier_keys.get(op_name) {
307                    Some(vk) => {
308                        let parsed: moonproof_ledger::transient_crypto::proofs::VerifierKey =
309                            moonproof_ledger::serialize::tagged_deserialize(&mut vk.as_bytes())
310                                .map_err(|e| {
311                                    format!(
312                                        "verifier key for '{op_name}' failed to tagged_deserialize: {e}"
313                                    )
314                                })?;
315                        moonproof_ledger::contract_operation(Some(parsed))
316                    }
317                    None => moonproof_ledger::contract_operation(None),
318                };
319                operations = operations.insert(entry, op);
320            }
321            Ok(operations)
322        });
323        match res {
324            Ok(ops) => Ok(ops.clone()),
325            Err(msg) => Err(driver_to_runtime_err(IrDriverError::InvalidIr(msg.clone()))),
326        }
327    }
328
329    /// Run the contract's constructor. `args` is a JSON Value matching
330    /// the IR's constructor argument signature: a single value for a
331    /// 1-arg constructor, an Array for positional, or an Object keyed
332    /// by argument name for named.
333    #[expect(
334        clippy::unused_async,
335        clippy::unused_async_trait_impl,
336        reason = "public async API that callers and generated bindings await; a plain fn returning a ready future would run the body eagerly at call time"
337    )]
338    pub async fn initialize(
339        &self,
340        ctx: ConstructorContext,
341        args: Value,
342    ) -> RuntimeResult<InitializeResult> {
343        self.initialize_inner(ctx, &args, true)
344    }
345
346    #[cfg(test)]
347    pub(crate) fn initialize_ast_only(
348        &self,
349        ctx: ConstructorContext,
350        args: &Value,
351    ) -> RuntimeResult<InitializeResult> {
352        self.initialize_inner(ctx, args, false)
353    }
354
355    fn initialize_inner(
356        &self,
357        ctx: ConstructorContext,
358        args: &Value,
359        use_bytecode: bool,
360    ) -> RuntimeResult<InitializeResult> {
361        // Reuse the cached skeleton StateValue and registered operations MPT
362        // (rebuilt only when verifier keys change).
363        let skeleton_data = self.skeleton_state()?;
364        let operations = self.cached_operations()?;
365        let dummy_address = ContractAddress(HashOutput([0u8; 32]));
366        let constructor_time = match ctx.time {
367            Some(time) => time,
368            None => web_time::SystemTime::now()
369                .duration_since(web_time::UNIX_EPOCH)
370                .map(|d| Timestamp::from_secs(d.as_secs()))
371                .map_err(|e| {
372                    driver_to_runtime_err(IrDriverError::VmOp(format!(
373                        "system clock is before the UNIX epoch: {e}"
374                    )))
375                })?,
376        };
377
378        let body = &self.ir.constructor.body;
379        let body_is_noop = matches!(body, moonproof_runtime_ir::ir::Statement::Noop);
380        let compiled_ctor = if use_bytecode && !body_is_noop {
381            self.index.compiled_constructor(&self.ir)
382        } else {
383            None
384        };
385
386        let init_ops_need_args = self.init_ops_need_args();
387        let args_map = if init_ops_need_args || (!body_is_noop && compiled_ctor.is_none()) {
388            Some(
389                bind_args(&self.ir.constructor.arguments, args, "constructor")
390                    .map_err(driver_to_runtime_err)?,
391            )
392        } else {
393            None
394        };
395        let args_vm = if let Some(compiled) = compiled_ctor {
396            Some((
397                compiled,
398                bind_args_vm(&self.ir.constructor.arguments, args, "constructor")
399                    .map_err(driver_to_runtime_err)?,
400            ))
401        } else {
402            if args_map.is_none() {
403                let _ = bind_args_vm(&self.ir.constructor.arguments, args, "constructor")
404                    .map_err(driver_to_runtime_err)?;
405            }
406            None
407        };
408
409        let mut vm_session = VmSession::from_state_value(skeleton_data.clone());
410        let empty_args = VarMap::default();
411        self.run_init_ops_on_session(
412            &mut vm_session,
413            &skeleton_data,
414            args_map.as_ref().unwrap_or(&empty_args),
415            dummy_address,
416            constructor_time,
417        )?;
418
419        let (final_state, private_state, zswap_state) = self.run_constructor_body(
420            vm_session,
421            skeleton_data,
422            dummy_address,
423            constructor_time,
424            ctx.initial_private_state,
425            CompactZswapLocalState::empty(ctx.coin_public_key),
426            args_vm,
427            args_map,
428        )?;
429
430        let contract_state = ContractState::<InMemoryDB>::new(
431            final_state,
432            operations,
433            ContractMaintenanceAuthority::default(),
434        );
435
436        Ok(InitializeResult {
437            initial_contract_state: contract_state,
438            initial_private_state: private_state,
439            initial_zswap_local_state: zswap_state,
440        })
441    }
442
443    #[allow(clippy::too_many_arguments)]
444    fn run_constructor_body(
445        &self,
446        vm_session: VmSession,
447        skeleton_data: StateValue<InMemoryDB>,
448        dummy_address: ContractAddress,
449        constructor_time: Timestamp,
450        private_state: Value,
451        zswap_state: CompactZswapLocalState,
452        args_vm: Option<(&crate::ir::bytecode::CompiledCircuit, Vec<VmVal>)>,
453        args_map: Option<VarMap>,
454    ) -> RuntimeResult<(StateValue<InMemoryDB>, Value, CompactZswapLocalState)> {
455        let body = &self.ir.constructor.body;
456        if matches!(body, moonproof_runtime_ir::ir::Statement::Noop) {
457            return Ok((vm_session.into_state_value(), private_state, zswap_state));
458        }
459        if let Some((compiled, ctor_args_vm)) = args_vm {
460            let mut vm = BytecodeVm::new(
461                &self.ir,
462                &self.index,
463                empty_contract_state(),
464                dummy_address,
465                private_state,
466                0,
467                self.witnesses.clone() as Arc<dyn crate::witnesses::Witnesses>,
468                Vec::new(),
469                zswap_state,
470                constructor_time,
471                None,
472                None,
473                Some(vm_session),
474            );
475            vm.run_root(compiled, ctor_args_vm)
476                .map_err(driver_to_runtime_err)?;
477            let final_state = vm
478                .vm_session
479                .take()
480                .map_or(skeleton_data, VmSession::into_state_value);
481            return Ok((final_state, vm.private_state, vm.next_zswap_local_state));
482        }
483        let mut state = InterpState {
484            ir: &self.ir,
485            index: Some(&self.index),
486            contract_state: empty_contract_state(),
487            contract_address: dummy_address,
488            private_state,
489            locals: VarMap::default(),
490            args: args_map.unwrap_or_default(),
491            public_transcript: Vec::new(),
492            private_transcript_outputs: Vec::new(),
493            popeq_read_results: Vec::new(),
494            witnesses: self.witnesses.clone() as Arc<dyn crate::witnesses::Witnesses>,
495            coin_commitments: Vec::new(),
496            next_zswap_local_state: zswap_state,
497            emitted_events: Vec::new(),
498            tblock: constructor_time,
499            caller: None,
500            call_tree: None,
501            effects: empty_effects(),
502            vm_session: Some(vm_session),
503            contract_label: String::new(),
504            circuit_name: String::new(),
505            trace: None,
506            trace_level: crate::trace::TraceLevel::Off,
507            trace_depth: 0,
508            coverage: None,
509        };
510        run_statement(&mut state, body).map_err(driver_to_runtime_err)?;
511        let final_state = state
512            .vm_session
513            .take()
514            .map_or(skeleton_data, VmSession::into_state_value);
515        Ok((
516            final_state,
517            state.private_state,
518            state.next_zswap_local_state,
519        ))
520    }
521
522    fn init_ops_need_args(&self) -> bool {
523        self.ir.constructor.init_ops.iter().any(|expr| {
524            let moonproof_runtime_ir::ir::Expression::AdtOp(inv) = expr else {
525                return true;
526            };
527            match self.index.compiled_query(&self.ir, &inv.vm_ops) {
528                Some(q) => !matches!(q.body, CompiledQueryBody::Static(_)),
529                None => true,
530            }
531        })
532    }
533
534    fn run_init_ops_on_session(
535        &self,
536        session: &mut VmSession,
537        skeleton_data: &StateValue<InMemoryDB>,
538        args_map: &VarMap,
539        address: ContractAddress,
540        time: Timestamp,
541    ) -> RuntimeResult<()> {
542        if self.ir.constructor.init_ops.is_empty() {
543            return Ok(());
544        }
545        let empty_locals = VarMap::default();
546        let scope = EvalScope {
547            ir: &self.ir,
548            locals: &empty_locals,
549            args: args_map,
550        };
551        let total_ops: usize = self
552            .ir
553            .constructor
554            .init_ops
555            .iter()
556            .map(|e| match e {
557                moonproof_runtime_ir::ir::Expression::AdtOp(inv) => inv.vm_ops.len(),
558                _ => 0,
559            })
560            .sum();
561        let mut batched_ops: Vec<Op<ResultModeGather, InMemoryDB>> = Vec::with_capacity(total_ops);
562        let mut combined_flags = QueryFlags::READ_ONLY_STATE;
563        let mut has_control_flow = false;
564        for invocation in &self.ir.constructor.init_ops {
565            let invocation = match invocation {
566                moonproof_runtime_ir::ir::Expression::AdtOp(inv) => inv,
567                other => {
568                    return Err(driver_to_runtime_err(IrDriverError::InvalidIr(format!(
569                        "init-ops entry not an adt-op: {other:?}"
570                    ))));
571                }
572            };
573            let start = batched_ops.len();
574            if let Some(compiled) = self.index.compiled_query(&self.ir, &invocation.vm_ops) {
575                combined_flags = combined_flags.union(compiled.flags);
576                match &compiled.body {
577                    CompiledQueryBody::Static(ops) => batched_ops.extend_from_slice(ops),
578                    CompiledQueryBody::Dynamic(compiled_ops) => {
579                        for op in compiled_ops {
580                            batched_ops
581                                .push(op.materialize(&scope).map_err(driver_to_runtime_err)?);
582                        }
583                    }
584                }
585            } else {
586                for instr in &invocation.vm_ops {
587                    batched_ops.push(decode_op(instr, &scope).map_err(driver_to_runtime_err)?);
588                }
589                combined_flags = combined_flags.union(analyze_ops(&batched_ops[start..]));
590            }
591            if !has_control_flow
592                && batched_ops[start..]
593                    .iter()
594                    .any(|op| matches!(op, Op::Branch { .. } | Op::Jmp { .. }))
595            {
596                has_control_flow = true;
597            }
598        }
599        // Execute all init-ops in a single VM program when none use relative
600        // control-flow (`Branch`/`Jmp`). If any init-op contains `Branch`/`Jmp`
601        // (whose skip offsets are scoped to a single op sequence) or the
602        // batched run errors, fall back to sequential execution on a clean
603        // session so the exact failing init-op is reported.
604        if !has_control_flow {
605            if combined_flags.reads_context {
606                session.ensure_context(&empty_contract_state(), address, time, &[], None);
607            }
608            if session
609                .run_ops(&batched_ops, combined_flags, || "init-ops batch".to_owned())
610                .is_ok()
611            {
612                return Ok(());
613            }
614            *session = VmSession::from_state_value(skeleton_data.clone());
615        }
616        self.run_init_ops_sequential(session, &scope, address, time)
617    }
618
619    fn run_init_ops_sequential(
620        &self,
621        session: &mut VmSession,
622        scope: &EvalScope<'_>,
623        address: ContractAddress,
624        time: Timestamp,
625    ) -> RuntimeResult<()> {
626        for invocation in &self.ir.constructor.init_ops {
627            let moonproof_runtime_ir::ir::Expression::AdtOp(invocation) = invocation else {
628                continue;
629            };
630            let (ops, flags): (Vec<Op<ResultModeGather, InMemoryDB>>, QueryFlags) =
631                if let Some(compiled) = self.index.compiled_query(&self.ir, &invocation.vm_ops) {
632                    let ops = match &compiled.body {
633                        CompiledQueryBody::Static(ops) => ops.clone(),
634                        CompiledQueryBody::Dynamic(compiled_ops) => {
635                            CompiledLedgerQuery::materialize_dynamic(compiled_ops, scope)
636                                .map_err(driver_to_runtime_err)?
637                        }
638                    };
639                    (ops, compiled.flags)
640                } else {
641                    let ops = invocation
642                        .vm_ops
643                        .iter()
644                        .map(|i| decode_op(i, scope))
645                        .collect::<std::result::Result<Vec<_>, IrDriverError>>()
646                        .map_err(driver_to_runtime_err)?;
647                    let flags = analyze_ops(&ops);
648                    (ops, flags)
649                };
650            if flags.reads_context {
651                session.ensure_context(&empty_contract_state(), address, time, &[], None);
652            }
653            session
654                .run_ops(&ops, flags, || {
655                    format!(
656                        "init-op '{}.{}' failed",
657                        invocation.adt, invocation.operation
658                    )
659                })
660                .map_err(driver_to_runtime_err)?;
661        }
662        Ok(())
663    }
664
665    /// Run a provable circuit. `args` is a JSON Value matching the
666    /// circuit's argument signature: a single value for 1-arg, an
667    /// Array for positional, or an Object keyed by argument name for
668    /// named.
669    ///
670    /// A circuit that calls another contract fails here; run it with
671    /// [`execute_call_tree`](Self::execute_call_tree).
672    #[expect(
673        clippy::unused_async,
674        clippy::unused_async_trait_impl,
675        reason = "public async API that callers and generated bindings await; a plain fn returning a ready future would run the body eagerly at call time"
676    )]
677    pub async fn execute_circuit(
678        &self,
679        circuit_name: &str,
680        ctx: CircuitCallContext,
681        args: Value,
682    ) -> RuntimeResult<ExecuteCircuitResult> {
683        let mut local_trace = self
684            .trace_level
685            .is_enabled()
686            .then(crate::trace::ExecutionTrace::new);
687        let mut res = self
688            .run_circuit(
689                circuit_name,
690                ctx,
691                &args,
692                self.witnesses.clone() as Arc<dyn Witnesses>,
693                None,
694                self.trace_level,
695                local_trace.as_mut(),
696                None,
697            )
698            .map_err(driver_to_runtime_err)?;
699        res.trace = local_trace;
700        Ok(res)
701    }
702
703    /// Like [`Self::execute_circuit`], recording into a caller-supplied
704    /// [`crate::trace::ExecutionTrace`] so partial traces remain available
705    /// even when execution reverts.
706    #[expect(
707        clippy::unused_async,
708        clippy::unused_async_trait_impl,
709        reason = "public async API matching execute_circuit"
710    )]
711    pub async fn execute_circuit_traced(
712        &self,
713        circuit_name: &str,
714        ctx: CircuitCallContext,
715        args: Value,
716        trace_level: crate::trace::TraceLevel,
717        trace: Option<&mut crate::trace::ExecutionTrace>,
718    ) -> RuntimeResult<ExecuteCircuitResult> {
719        self.run_circuit(
720            circuit_name,
721            ctx,
722            &args,
723            self.witnesses.clone() as Arc<dyn Witnesses>,
724            None,
725            trace_level,
726            trace,
727            None,
728        )
729        .map_err(driver_to_runtime_err)
730    }
731
732    /// Like [`Self::execute_circuit_traced`], also recording into an optional
733    /// [`crate::coverage::IrCoverageCollector`]. Both `trace` and `coverage`
734    /// capture partial execution up to and including an assertion revert.
735    #[allow(clippy::too_many_arguments)]
736    #[expect(
737        clippy::unused_async,
738        clippy::unused_async_trait_impl,
739        reason = "public async API matching execute_circuit"
740    )]
741    pub async fn execute_circuit_instrumented(
742        &self,
743        circuit_name: &str,
744        ctx: CircuitCallContext,
745        args: Value,
746        trace_level: crate::trace::TraceLevel,
747        trace: Option<&mut crate::trace::ExecutionTrace>,
748        coverage: Option<&mut crate::coverage::IrCoverageCollector>,
749    ) -> RuntimeResult<ExecuteCircuitResult> {
750        self.run_circuit(
751            circuit_name,
752            ctx,
753            &args,
754            self.witnesses.clone() as Arc<dyn Witnesses>,
755            None,
756            trace_level,
757            trace,
758            coverage,
759        )
760        .map_err(driver_to_runtime_err)
761    }
762
763    /// Run a provable circuit together with every cross-contract call
764    /// it makes.
765    ///
766    /// The callees' code and deployed state come from `session`. A run
767    /// that reaches an address `session` has no binding for returns
768    /// [`CallTreeOutcome::CalleeRequired`]; bind it with
769    /// [`CrossContractSession::bind_callee`] and call this again with
770    /// the same `ctx` and `args`. Witness results observed by an earlier
771    /// run are replayed rather than asked for again.
772    pub async fn execute_call_tree<R: Rng + CryptoRng>(
773        &self,
774        rng: &mut R,
775        circuit_name: &str,
776        ctx: CircuitCallContext,
777        args: Value,
778        session: &mut CrossContractSession,
779    ) -> RuntimeResult<CallTreeOutcome> {
780        let mut local_trace = self
781            .trace_level
782            .is_enabled()
783            .then(crate::trace::ExecutionTrace::new);
784        let outcome = self
785            .execute_call_tree_traced(
786                rng,
787                circuit_name,
788                ctx,
789                args,
790                session,
791                self.trace_level,
792                local_trace.as_mut(),
793            )
794            .await?;
795        match outcome {
796            CallTreeOutcome::Executed(mut tree) => {
797                tree.root.trace = local_trace;
798                Ok(CallTreeOutcome::Executed(tree))
799            }
800            other @ CallTreeOutcome::CalleeRequired(_) => Ok(other),
801        }
802    }
803
804    /// Like [`Self::execute_call_tree`], recording into a caller-supplied
805    /// [`crate::trace::ExecutionTrace`] so partial call trees remain
806    /// available even when a root or callee circuit reverts.
807    #[allow(clippy::too_many_arguments)]
808    pub async fn execute_call_tree_traced<R: Rng + CryptoRng>(
809        &self,
810        rng: &mut R,
811        circuit_name: &str,
812        ctx: CircuitCallContext,
813        args: Value,
814        session: &mut CrossContractSession,
815        trace_level: crate::trace::TraceLevel,
816        trace: Option<&mut crate::trace::ExecutionTrace>,
817    ) -> RuntimeResult<CallTreeOutcome> {
818        self.execute_call_tree_instrumented(
819            rng,
820            circuit_name,
821            ctx,
822            args,
823            session,
824            trace_level,
825            trace,
826            None,
827        )
828        .await
829    }
830
831    /// Like [`Self::execute_call_tree_traced`], also recording into an
832    /// optional [`crate::coverage::IrCoverageCollector`].
833    #[allow(clippy::too_many_arguments)]
834    #[expect(
835        clippy::unused_async,
836        clippy::unused_async_trait_impl,
837        reason = "public async API matching execute_call_tree"
838    )]
839    pub async fn execute_call_tree_instrumented<R: Rng + CryptoRng>(
840        &self,
841        rng: &mut R,
842        circuit_name: &str,
843        ctx: CircuitCallContext,
844        args: Value,
845        session: &mut CrossContractSession,
846        trace_level: crate::trace::TraceLevel,
847        mut trace: Option<&mut crate::trace::ExecutionTrace>,
848        mut coverage: Option<&mut crate::coverage::IrCoverageCollector>,
849    ) -> RuntimeResult<CallTreeOutcome> {
850        let seed = StdRng::from_rng(rng).map_err(|e| {
851            driver_to_runtime_err(IrDriverError::CrossContract(format!(
852                "seeding the call tree's randomness: {e}"
853            )))
854        })?;
855        let (mut run, witnesses) =
856            session.start_run(self.witnesses.clone() as Arc<dyn Witnesses>, seed);
857        run.active.push(ctx.contract_address);
858        if let Some(t) = trace.as_deref_mut() {
859            t.clear();
860        }
861        if let Some(c) = coverage.as_deref_mut() {
862            c.clear();
863        }
864        let outcome = self.run_circuit(
865            circuit_name,
866            ctx,
867            &args,
868            witnesses.clone() as Arc<dyn Witnesses>,
869            Some(&mut run),
870            trace_level,
871            trace,
872            coverage,
873        );
874        session
875            .finish_run(&witnesses)
876            .map_err(driver_to_runtime_err)?;
877        if let Some(address) = run.required {
878            return Ok(CallTreeOutcome::CalleeRequired(address));
879        }
880        let root = outcome.map_err(driver_to_runtime_err)?;
881        Ok(CallTreeOutcome::Executed(Box::new(CallTreeResult {
882            root,
883            callees: run.calls,
884        })))
885    }
886
887    #[cfg(test)]
888    pub(crate) fn execute_call_tree_ast_only<R: Rng + CryptoRng>(
889        &self,
890        rng: &mut R,
891        circuit_name: &str,
892        ctx: CircuitCallContext,
893        args: &Value,
894        session: &mut CrossContractSession,
895    ) -> RuntimeResult<CallTreeOutcome> {
896        let seed = StdRng::from_rng(rng).map_err(|e| {
897            driver_to_runtime_err(IrDriverError::CrossContract(format!(
898                "seeding the call tree's randomness: {e}"
899            )))
900        })?;
901        let (mut run, witnesses) =
902            session.start_run(self.witnesses.clone() as Arc<dyn Witnesses>, seed);
903        run.active.push(ctx.contract_address);
904        let outcome = self.run_circuit_inner(
905            circuit_name,
906            ctx,
907            args,
908            witnesses.clone() as Arc<dyn Witnesses>,
909            Some(&mut run),
910            crate::trace::TraceLevel::Off,
911            None,
912            None,
913            false,
914        );
915        session
916            .finish_run(&witnesses)
917            .map_err(driver_to_runtime_err)?;
918        if let Some(address) = run.required {
919            return Ok(CallTreeOutcome::CalleeRequired(address));
920        }
921        let root = outcome.map_err(driver_to_runtime_err)?;
922        Ok(CallTreeOutcome::Executed(Box::new(CallTreeResult {
923            root,
924            callees: run.calls,
925        })))
926    }
927
928    #[cfg(test)]
929    pub(crate) fn run_circuit_ast_only(
930        &self,
931        circuit_name: &str,
932        ctx: CircuitCallContext,
933        args: &Value,
934        call_tree: Option<&mut CallTreeRun>,
935    ) -> Result<ExecuteCircuitResult> {
936        self.run_circuit_inner(
937            circuit_name,
938            ctx,
939            args,
940            self.witnesses.clone() as Arc<dyn Witnesses>,
941            call_tree,
942            crate::trace::TraceLevel::Off,
943            None,
944            None,
945            false,
946        )
947    }
948
949    #[allow(clippy::too_many_arguments)]
950    fn run_circuit(
951        &self,
952        circuit_name: &str,
953        ctx: CircuitCallContext,
954        args: &Value,
955        witnesses: Arc<dyn Witnesses>,
956        call_tree: Option<&mut CallTreeRun>,
957        trace_level: crate::trace::TraceLevel,
958        trace: Option<&mut crate::trace::ExecutionTrace>,
959        coverage: Option<&mut crate::coverage::IrCoverageCollector>,
960    ) -> Result<ExecuteCircuitResult> {
961        self.run_circuit_inner(
962            circuit_name,
963            ctx,
964            args,
965            witnesses,
966            call_tree,
967            trace_level,
968            trace,
969            coverage,
970            true,
971        )
972    }
973
974    #[allow(clippy::too_many_arguments)]
975    fn run_circuit_inner(
976        &self,
977        circuit_name: &str,
978        ctx: CircuitCallContext,
979        args: &Value,
980        witnesses: Arc<dyn Witnesses>,
981        call_tree: Option<&mut CallTreeRun>,
982        trace_level: crate::trace::TraceLevel,
983        mut trace: Option<&mut crate::trace::ExecutionTrace>,
984        coverage: Option<&mut crate::coverage::IrCoverageCollector>,
985        use_bytecode: bool,
986    ) -> Result<ExecuteCircuitResult> {
987        let circuit_idx = self
988            .index
989            .first_circuit_index(&self.ir, circuit_name)
990            .ok_or_else(|| IrDriverError::UnknownCircuit(circuit_name.to_string()))?;
991        let circuit = &self.ir.circuits[circuit_idx];
992
993        if use_bytecode && trace_level == crate::trace::TraceLevel::Off && coverage.is_none() {
994            if let Some(compiled) = self.index.compiled_circuit(&self.ir, circuit_idx) {
995                return self
996                    .run_circuit_bytecode(circuit, compiled, ctx, args, witnesses, call_tree);
997            }
998        }
999
1000        let args_map = bind_args(&circuit.arguments, args, &circuit.name)?;
1001        let tracing_active = trace_level.is_enabled() && trace.is_some();
1002        let (contract_label, circuit_label, active_trace) = if tracing_active {
1003            let contract_label = self
1004                .contract_name
1005                .clone()
1006                .unwrap_or_else(|| crate::trace::short_address(&ctx.contract_address));
1007            let circuit_label = circuit.name.clone();
1008            if let Some(t) = trace.as_deref_mut() {
1009                t.push(crate::trace::TraceEvent::CircuitEnter {
1010                    contract: contract_label.clone(),
1011                    circuit: circuit_label.clone(),
1012                    args: args.clone(),
1013                    depth: 0,
1014                });
1015            }
1016            (contract_label, circuit_label, trace)
1017        } else {
1018            (String::new(), String::new(), None)
1019        };
1020
1021        let effects = empty_effects();
1022        let transcript_cap = self.index.estimated_transcript_ops(&self.ir, circuit);
1023        let coin_commitments = if self.coin_commitments.is_empty() {
1024            Vec::new()
1025        } else {
1026            (*self.coin_commitments).clone()
1027        };
1028
1029        let mut state = InterpState {
1030            ir: &self.ir,
1031            index: Some(&self.index),
1032            // `ctx` is owned here, so move the state in rather than
1033            // clone it — the caller already handed us ownership.
1034            contract_state: ctx.contract_state,
1035            contract_address: ctx.contract_address,
1036            private_state: ctx.private_state,
1037            locals: VarMap::default(),
1038            args: args_map,
1039            public_transcript: Vec::with_capacity(transcript_cap),
1040            private_transcript_outputs: Vec::new(),
1041            popeq_read_results: Vec::new(),
1042            witnesses,
1043            coin_commitments,
1044            next_zswap_local_state: CompactZswapLocalState::empty(ctx.coin_public_key),
1045            emitted_events: Vec::new(),
1046            tblock: ctx.tblock,
1047            caller: None,
1048            call_tree,
1049            effects,
1050            vm_session: None,
1051            contract_label,
1052            circuit_name: circuit_label,
1053            trace: active_trace,
1054            trace_level,
1055            trace_depth: 0,
1056            coverage,
1057        };
1058
1059        if let Some(cov) = state.coverage.as_deref_mut() {
1060            cov.record_circuit(circuit);
1061        }
1062        let result_value = run_statement(&mut state, &circuit.body)?;
1063        state.try_sync_from_query_context()?;
1064
1065        if let Some(t) = state.trace.as_deref_mut() {
1066            t.push(crate::trace::TraceEvent::CircuitExit {
1067                contract: std::mem::take(&mut state.contract_label),
1068                circuit: std::mem::take(&mut state.circuit_name),
1069                result: result_value.clone(),
1070                depth: 0,
1071            });
1072        }
1073
1074        let input_av = encode_input_with_index(&self.ir, Some(&self.index), circuit, &state.args)?;
1075        let output_av =
1076            encode_output_with_index(&self.ir, Some(&self.index), circuit, &result_value)?;
1077
1078        Ok(ExecuteCircuitResult {
1079            next_contract_state: state.contract_state,
1080            next_private_state: state.private_state,
1081            next_zswap_local_state: state.next_zswap_local_state,
1082            emitted_events: state.emitted_events,
1083            input: input_av,
1084            output: output_av,
1085            result: result_value,
1086            public_transcript: state.public_transcript,
1087            private_transcript_outputs: state.private_transcript_outputs,
1088            popeq_read_results: state.popeq_read_results,
1089            effects: state.effects,
1090            trace: None,
1091        })
1092    }
1093
1094    fn run_circuit_bytecode(
1095        &self,
1096        circuit: &moonproof_runtime_ir::ir::CircuitBody,
1097        compiled: &crate::ir::bytecode::CompiledCircuit,
1098        ctx: CircuitCallContext,
1099        args: &Value,
1100        witnesses: Arc<dyn Witnesses>,
1101        call_tree: Option<&mut CallTreeRun>,
1102    ) -> Result<ExecuteCircuitResult> {
1103        let args_vm = bind_args_vm(&circuit.arguments, args, &circuit.name)?;
1104        let transcript_cap = self.index.estimated_transcript_ops(&self.ir, circuit);
1105        let coin_commitments = if self.coin_commitments.is_empty() {
1106            Vec::new()
1107        } else {
1108            (*self.coin_commitments).clone()
1109        };
1110
1111        let mut vm = BytecodeVm::new(
1112            &self.ir,
1113            &self.index,
1114            ctx.contract_state,
1115            ctx.contract_address,
1116            ctx.private_state,
1117            transcript_cap,
1118            witnesses,
1119            coin_commitments,
1120            CompactZswapLocalState::empty(ctx.coin_public_key),
1121            ctx.tblock,
1122            None,
1123            call_tree,
1124            None,
1125        );
1126
1127        let result_vm = vm.run_root(compiled, args_vm)?;
1128        vm.sync_vm_session()?;
1129
1130        let io_plan = self.index.circuit_io_plan(&self.ir, circuit);
1131        let input_av = if let Some(plan) = io_plan.and_then(|io| io.input.as_ref()) {
1132            plan.encode_vm_vals(&circuit.name, &vm.regs[..circuit.arguments.len()])?
1133        } else {
1134            let args_map = bind_args(&circuit.arguments, args, &circuit.name)?;
1135            encode_input(circuit, &args_map)?
1136        };
1137        let output_av = if matches!(
1138            &circuit.result_type,
1139            moonproof_runtime_ir::ir::TypeDescriptor::Tuple { types } if types.is_empty()
1140        ) {
1141            moonproof_ledger::base_crypto::fab::AlignedValue::concat(std::iter::empty::<
1142                &moonproof_ledger::base_crypto::fab::AlignedValue,
1143            >())
1144        } else if let Some(plan) = io_plan.and_then(|io| io.output.as_ref()) {
1145            plan.encode_vm_val(&result_vm)?
1146        } else {
1147            encode_literal(&circuit.result_type, &result_vm.to_runtime_value())?
1148        };
1149        let result_value = result_vm.into_runtime_value();
1150
1151        Ok(ExecuteCircuitResult {
1152            next_contract_state: vm.contract_state,
1153            next_private_state: vm.private_state,
1154            next_zswap_local_state: vm.next_zswap_local_state,
1155            emitted_events: vm.emitted_events,
1156            input: input_av,
1157            output: output_av,
1158            result: result_value,
1159            public_transcript: vm.public_transcript,
1160            private_transcript_outputs: vm.private_transcript_outputs,
1161            popeq_read_results: vm.popeq_read_results,
1162            effects: vm.effects,
1163            trace: None,
1164        })
1165    }
1166}
1167
1168/// Bind a JSON `args` Value directly into positional [`VmVal`] register slots
1169/// without allocating a `VarMap` or cloning argument names.
1170fn bind_args_vm(defs: &[Argument], args: &Value, context: &str) -> Result<Vec<VmVal>> {
1171    if defs.is_empty() {
1172        return Ok(Vec::new());
1173    }
1174    if defs.len() == 1 {
1175        return Ok(vec![VmVal::from_runtime_value(args)]);
1176    }
1177    let mut out = Vec::with_capacity(defs.len());
1178    match args {
1179        Value::Array(arr) => {
1180            if arr.len() != defs.len() {
1181                return Err(IrDriverError::ArgCount {
1182                    context: format!("{context} (positional)"),
1183                    expected: defs.len(),
1184                    got: arr.len(),
1185                });
1186            }
1187            for v in arr {
1188                out.push(VmVal::from_runtime_value(v));
1189            }
1190        }
1191        Value::Object(map) => {
1192            for arg in defs {
1193                let v = map.get(&arg.name).ok_or_else(|| IrDriverError::ArgCount {
1194                    context: format!("{context} arg '{}'", arg.name),
1195                    expected: defs.len(),
1196                    got: map.len(),
1197                })?;
1198                out.push(VmVal::from_runtime_value(v));
1199            }
1200        }
1201        _ => {
1202            return Err(IrDriverError::TypeMismatch(format!(
1203                "{context} expects {} args (use Array or Object); got {args}",
1204                defs.len()
1205            )));
1206        }
1207    }
1208    Ok(out)
1209}
1210
1211/// Bind a JSON `args` Value to a `name → Value` map, validating
1212/// against the IR's argument descriptors. Accepts:
1213///
1214/// - Single value when `defs.len() == 1`
1215/// - Array (positional) when `arr.len() == defs.len()`
1216/// - Object keyed by argument name
1217fn bind_args(defs: &[Argument], args: &Value, context: &str) -> Result<VarMap> {
1218    let mut out = VarMap::with_capacity_and_hasher(defs.len(), rustc_hash::FxBuildHasher);
1219    if defs.is_empty() {
1220        return Ok(out);
1221    }
1222    if defs.len() == 1 {
1223        out.insert(defs[0].name.clone(), args.clone());
1224        return Ok(out);
1225    }
1226    match args {
1227        Value::Array(arr) => {
1228            if arr.len() != defs.len() {
1229                return Err(IrDriverError::ArgCount {
1230                    context: format!("{context} (positional)"),
1231                    expected: defs.len(),
1232                    got: arr.len(),
1233                });
1234            }
1235            for (def, v) in defs.iter().zip(arr.iter()) {
1236                out.insert(def.name.clone(), v.clone());
1237            }
1238        }
1239        Value::Object(map) => {
1240            for arg in defs {
1241                let v = map
1242                    .get(&arg.name)
1243                    .cloned()
1244                    .ok_or_else(|| IrDriverError::ArgCount {
1245                        context: format!("{context} arg '{}'", arg.name),
1246                        expected: defs.len(),
1247                        got: map.len(),
1248                    })?;
1249                out.insert(arg.name.clone(), v);
1250            }
1251        }
1252        _ => {
1253            return Err(IrDriverError::TypeMismatch(format!(
1254                "{context} expects {} args (use Array or Object); got {args}",
1255                defs.len()
1256            )));
1257        }
1258    }
1259    Ok(out)
1260}
1261
1262fn driver_to_runtime_err(e: IrDriverError) -> ContractRuntimeError {
1263    match e {
1264        IrDriverError::AssertionFailed(message) => ContractRuntimeError::AssertionFailed(message),
1265        other => ContractRuntimeError::Provider {
1266            provider: "runtime-ir-driver",
1267            message: other.to_string(),
1268        },
1269    }
1270}