moonproof-runtime 0.2.1

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
//! Throwaway bench: time the IR-driven off-chain execution
//! (constructor plus a circuit) the deploy/call path runs — the Rust
//! counterpart to executing the JS contract via compact-runtime.
//!
//! `cargo run --release -p moonproof-runtime --example bench_exec`

use std::sync::Arc;
use std::time::Instant;

use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_runtime::executable::{CircuitCallContext, ConstructorContext};
use moonproof_runtime::CompactZswapLocalState;
use moonproof_runtime::{IrDriverError, IrExecutable, Witnesses};
use moonproof_runtime_ir::RuntimeValue as Value;

#[derive(Debug)]
struct PredicateWitnesses;

impl Witnesses for PredicateWitnesses {
    fn invoke(
        &self,
        name: &str,
        _args: &Value,
        ps: &Value,
    ) -> Result<moonproof_runtime::witnesses::WitnessResult, IrDriverError> {
        let observed = match name {
            "ageValue" => Value::Int(30),
            other => {
                return Err(IrDriverError::Witness(format!(
                    "unexpected witness '{other}'"
                )))
            }
        };
        Ok(moonproof_runtime::witnesses::WitnessResult {
            observed,
            next_private_state: ps.clone(),
        })
    }
}

fn fixture_cbor() -> std::path::PathBuf {
    std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../test-fixtures/contracts/predicate_registry/contract.mpir")
}

fn zero_pk() -> moonproof_runtime::types::CoinPublicKey {
    moonproof_runtime::types::CoinPublicKey([0u8; 32])
}

fn ctor_ctx(signing_key: &moonproof_ledger::signatures::SigningKey) -> ConstructorContext {
    ConstructorContext {
        initial_private_state: Value::Null,
        initial_zswap_local_state: CompactZswapLocalState::empty(zero_pk()),
        coin_public_key: zero_pk(),
        signing_key: signing_key.clone(),
        time: None,
    }
}

fn owner_either() -> Value {
    let b = |v: Vec<u8>| {
        let mut m = std::collections::BTreeMap::new();
        m.insert("bytes".to_string(), Value::Bytes(v));
        Value::Object(m)
    };
    let mut o = std::collections::BTreeMap::new();
    o.insert("is_left".to_string(), Value::Bool(true));
    o.insert("left".to_string(), Value::Bytes(vec![1u8; 32]));
    o.insert("right".to_string(), b(vec![0u8; 32]));
    Value::Object(o)
}

fn attest_args() -> Value {
    let mut m = std::collections::BTreeMap::new();
    m.insert("rootHash".to_string(), Value::Bytes(vec![2u8; 32]));
    m.insert("threshold".to_string(), Value::Int(21));
    Value::Object(m)
}

#[tokio::main]
async fn main() {
    let exec = IrExecutable::from_path(fixture_cbor(), Arc::new(PredicateWitnesses))
        .expect("predicate_registry cbor loads");

    let signing_key = moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32]).unwrap();

    // ── Constructor (the deploy's off-chain work) ──
    exec.initialize(ctor_ctx(&signing_key), owner_either())
        .await
        .expect("init");
    let n_ctor = 200u32;
    let t = Instant::now();
    for _ in 0..n_ctor {
        exec.initialize(ctor_ctx(&signing_key), owner_either())
            .await
            .expect("init");
    }
    let ctor_ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(n_ctor);

    // ── Circuit call (the call path's off-chain work) ──
    let init = exec
        .initialize(ctor_ctx(&signing_key), owner_either())
        .await
        .expect("init");
    let mk_ctx = || CircuitCallContext {
        contract_address: ContractAddress(HashOutput([0x77u8; 32])),
        contract_state: init.initial_contract_state.clone(),
        private_state: Value::Null,
        ledger_parameters: moonproof_ledger::ledger::structure::INITIAL_PARAMETERS.clone(),
        coin_public_key: zero_pk(),
        tblock: Timestamp::from_secs(0),
    };
    exec.execute_circuit("attestAgeGte", mk_ctx(), attest_args())
        .await
        .expect("circuit");
    let n_call = 200u32;
    let t = Instant::now();
    for _ in 0..n_call {
        exec.execute_circuit("attestAgeGte", mk_ctx(), attest_args())
            .await
            .expect("circuit");
    }
    let call_ms = t.elapsed().as_secs_f64() * 1000.0 / f64::from(n_call);

    println!("rust constructor (initialize):      {ctor_ms:.4} ms/iter ({n_ctor} iters)");
    println!("rust circuit (attestAgeGte exec):   {call_ms:.4} ms/iter ({n_call} iters)");
}