moonproof-runtime 0.2.2

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
//! Criterion benches for the IR-driven off-chain executor — the work
//! that runs on EVERY contract deploy (`initialize`) and EVERY contract
//! call (`execute_circuit`). Fixture: the `predicate_registry`
//! contract (13 exported circuits), off-chain only (excludes proving).
//!
//! `cargo bench -p moonproof-runtime --bench exec`
//!
//! Covers: constructor; a LIGHT circuit (`attestAgeGte`, runs clean);
//! a HEAVY circuit (`attestResidencyIn`, walks a depth-8 Merkle path
//! root + several persistent hashes); the full all-13-circuit sweep;
//! and the cold IR parse.

use std::collections::BTreeMap;
use std::sync::Arc;

use criterion::{criterion_group, criterion_main, BatchSize, Criterion};
use std::hint::black_box;

use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::ledger::structure::INITIAL_PARAMETERS;
use moonproof_ledger::onchain_runtime::state::ContractState;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_runtime::executable::{CircuitCallContext, ConstructorContext};
use moonproof_runtime::types::CoinPublicKey;
use moonproof_runtime::witnesses::WitnessResult;
use moonproof_runtime::{CompactZswapLocalState, IrDriverError, IrExecutable, Witnesses};
use moonproof_runtime_ir::RuntimeValue as Value;

/// Witnesses covering every private input the `predicate_registry`
/// circuits read. Values are chosen so the asserts that gate the heavy
/// work pass (`path.leaf == residentCountry`, `age >= threshold`, …).
#[derive(Debug)]
struct RegistryWitnesses;

impl Witnesses for RegistryWitnesses {
    fn invoke(
        &self,
        name: &str,
        _args: &Value,
        ps: &Value,
    ) -> Result<WitnessResult, IrDriverError> {
        let observed = match name {
            "ageValue" => Value::Int(30),
            "emailVerifiedFlag" => Value::Int(1),
            "kycLevel" => Value::Int(3),
            "personhoodSecret" => Value::Bytes(vec![0x22u8; 32]),
            // residentCountry / nationalityCode must equal the Merkle
            // path leaf below so `assert(path.leaf == country)` passes
            // and the depth-8 root computation runs.
            "residentCountry" | "nationalityCode" => Value::Bytes(vec![0x11u8; 32]),
            "verifierIdHash" => Value::Bytes(vec![0x33u8; 32]),
            "allowedCountryPath" => merkle_path_8(),
            other => {
                return Err(IrDriverError::Witness(format!(
                    "unexpected witness '{other}'"
                )));
            }
        };
        Ok(WitnessResult {
            observed,
            next_private_state: ps.clone(),
        })
    }
}

/// `MerkleTreePath<8, Bytes<32>>` witness value — `{ leaf, path: [{
/// sibling, goes_left } × 8] }`, matching the compact-std shape the
/// fork IR encodes. Leaf is `0x11…` to match `residentCountry`.
fn merkle_path_8() -> Value {
    let mut inner = BTreeMap::new();
    inner.insert("leaf".to_string(), Value::Bytes(vec![0x11u8; 32]));
    let path: Vec<Value> = (0..8)
        .map(|_| {
            let mut sibling = BTreeMap::new();
            sibling.insert("field".to_string(), Value::Bytes(vec![0u8; 32]));
            let mut step = BTreeMap::new();
            step.insert("sibling".to_string(), Value::Object(sibling));
            step.insert("goes_left".to_string(), Value::Bool(false));
            Value::Object(step)
        })
        .collect();
    inner.insert("path".to_string(), Value::Array(path));
    Value::Object(inner)
}

fn fixture_cbor() -> Vec<u8> {
    let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../test-fixtures/contracts/predicate_registry/contract.mpir");
    std::fs::read(path).expect("predicate_registry contract.mpir")
}

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

fn ctor_ctx() -> ConstructorContext {
    ConstructorContext {
        initial_private_state: Value::Null,
        initial_zswap_local_state: CompactZswapLocalState::empty(zero_pk()),
        coin_public_key: zero_pk(),
        signing_key: moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32]).unwrap(),
        time: None,
    }
}

fn owner_either() -> Value {
    let b = |v: Vec<u8>| {
        let mut m = BTreeMap::new();
        m.insert("bytes".to_string(), Value::Bytes(v));
        Value::Object(m)
    };
    let mut o = 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 call_ctx(state: ContractState<InMemoryDB>) -> CircuitCallContext {
    CircuitCallContext {
        contract_address: ContractAddress(HashOutput([0x77u8; 32])),
        contract_state: state,
        private_state: Value::Null,
        ledger_parameters: INITIAL_PARAMETERS.clone(),
        coin_public_key: zero_pk(),
        tblock: Timestamp::from_secs(0),
    }
}

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

fn attest_residency_args() -> Value {
    let mut m = BTreeMap::new();
    m.insert("rootHash".to_string(), Value::Bytes(vec![2u8; 32]));
    m.insert("setHash".to_string(), Value::Bytes(vec![3u8; 32]));
    Value::Object(m)
}

/// `(circuit name, args)` for the all-circuit sweep. Some fire a
/// contract-level assert (auth / setHash mismatch) — that's expected;
/// the bench measures the IR walk to that point, deterministically.
fn sweep_inputs() -> Vec<(&'static str, Value)> {
    let pk = |v: u8| {
        let mut m = BTreeMap::new();
        m.insert("bytes".to_string(), Value::Bytes(vec![v; 32]));
        Value::Object(m)
    };
    let either = |v: u8| {
        let mut o = BTreeMap::new();
        o.insert("is_left".to_string(), Value::Bool(true));
        o.insert("left".to_string(), pk(v));
        o.insert("right".to_string(), pk(0));
        Value::Object(o)
    };
    let b32 = |v: u8| Value::Bytes(vec![v; 32]);
    let mut age_range = BTreeMap::new();
    age_range.insert("rootHash".to_string(), b32(2));
    age_range.insert("minAge".to_string(), Value::Int(18));
    age_range.insert("maxAge".to_string(), Value::Int(99));
    let mut kyc = BTreeMap::new();
    kyc.insert("rootHash".to_string(), b32(2));
    kyc.insert("threshold".to_string(), Value::Int(2));
    let mut uniq = BTreeMap::new();
    uniq.insert("rootHash".to_string(), b32(2));
    uniq.insert("epoch".to_string(), b32(7));
    uniq.insert("appId".to_string(), b32(8));
    let mut email = BTreeMap::new();
    email.insert("rootHash".to_string(), b32(2));

    vec![
        ("attestAgeGte", attest_age_args()),
        ("attestAgeRange", Value::Object(age_range)),
        ("attestEmailVerified", Value::Object(email)),
        ("attestKycGte", Value::Object(kyc)),
        ("attestUniquePersonhood", Value::Object(uniq)),
        ("attestResidencyIn", attest_residency_args()),
        ("attestNationalityIn", attest_residency_args()),
        ("isAttested", b32(9)),
        ("pause", Value::Null),
        ("unpause", Value::Null),
        ("transferOwnership", either(5)),
        ("owner", Value::Null),
        ("isPaused", Value::Null),
    ]
}

fn build_exec() -> IrExecutable<RegistryWitnesses> {
    IrExecutable::from_cbor_slice(&fixture_cbor(), Arc::new(RegistryWitnesses))
        .expect("predicate_registry IR loads")
}

fn bench_exec(c: &mut Criterion) {
    let rt = tokio::runtime::Builder::new_current_thread()
        .build()
        .unwrap();
    let exec = build_exec();
    let init = rt
        .block_on(exec.initialize(ctor_ctx(), owner_either()))
        .expect("initialize");
    let initial_state = init.initial_contract_state.clone();

    c.bench_function("constructor", |b| {
        b.iter(|| {
            let r = rt
                .block_on(exec.initialize(ctor_ctx(), owner_either()))
                .expect("init");
            black_box(r);
        });
    });

    c.bench_function("circuit_light_attestAgeGte", |b| {
        b.iter(|| {
            let r = rt
                .block_on(exec.execute_circuit(
                    "attestAgeGte",
                    call_ctx(initial_state.clone()),
                    attest_age_args(),
                ))
                .expect("attestAgeGte");
            black_box(r);
        });
    });

    // Genuinely light circuit — reads ONE Pausable cell. Closest
    // proxy for the interpreter's own per-call floor (minimal ledger
    // VM work), so interpreter-glue optimizations show up here.
    c.bench_function("circuit_glue_isPaused", |b| {
        b.iter(|| {
            let r = rt
                .block_on(exec.execute_circuit(
                    "isPaused",
                    call_ctx(initial_state.clone()),
                    Value::Null,
                ))
                .expect("isPaused");
            black_box(r);
        });
    });

    c.bench_function("circuit_heavy_attestResidencyIn", |b| {
        b.iter(|| {
            // Walks the depth-8 Merkle root + persistent hashes, then
            // fires the final `setHash == computed` assert. Same work
            // every iteration.
            let r = rt.block_on(exec.execute_circuit(
                "attestResidencyIn",
                call_ctx(initial_state.clone()),
                attest_residency_args(),
            ));
            black_box(r.is_ok());
        });
    });

    let sweep = sweep_inputs();
    c.bench_function("all_circuits_sweep", |b| {
        b.iter(|| {
            for (name, args) in &sweep {
                let r = rt.block_on(exec.execute_circuit(
                    name,
                    call_ctx(initial_state.clone()),
                    args.clone(),
                ));
                black_box(r.is_ok());
            }
        });
    });

    let bytes = fixture_cbor();
    c.bench_function("load_ir_from_cbor", |b| {
        b.iter_batched(
            || bytes.clone(),
            |b| {
                let e =
                    IrExecutable::from_cbor_slice(&b, Arc::new(RegistryWitnesses)).expect("load");
                black_box(e.ir().circuits.len());
            },
            BatchSize::SmallInput,
        );
    });
}

criterion_group!(benches, bench_exec);
criterion_main!(benches);