moonproof-runtime 0.2.2

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
//! End-to-end test: drive the `synthetic_iter` fixture through the
//! generic [`IrExecutable`].
//!
//! This fixture exists specifically to exercise the constructs the
//! seven hand-written contracts (counter / registry / mint / vault /
//! issuer-registry / identity-registry / revocation-registry) didn't
//! reach: `Expression::TupleRef` (literal vector indexing) and
//! `Expression::Fold` (`for (const x of vec) { ... }` lowering).
//!
//! Compact source: `crates/runtime-ir/tests/fixtures/synthetic_iter.compact`
//! (committed alongside the JSON for re-derivation).

use std::sync::Arc;

use moonproof_ledger::base_crypto::fab::AlignedValue;
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::signatures::SigningKey;
use moonproof_runtime::executable::{CircuitCallContext, ConstructorContext};
use moonproof_runtime::types::CoinPublicKey;
use moonproof_runtime::CompactZswapLocalState;
use moonproof_runtime::{IrExecutable, NoWitnesses};

fn synthetic_iter_ir_path() -> std::path::PathBuf {
    let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    p.pop();
    p.push("runtime-ir");
    p.push("tests/fixtures/synthetic_iter.cbor");
    p
}

fn dummy_signing_key() -> SigningKey {
    moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32]).expect("32 bytes parse")
}

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

fn dummy_contract_address() -> ContractAddress {
    ContractAddress(HashOutput([0x77u8; 32]))
}

#[tokio::test]
async fn ir_executable_synthetic_iter_provable_circuits() {
    let exec = IrExecutable::from_path(synthetic_iter_ir_path(), Arc::new(NoWitnesses))
        .expect("synthetic_iter IR loads");
    let ids = exec.provable_circuit_ids();
    let names: Vec<&str> = ids
        .iter()
        .map(moonproof_runtime::CircuitId::as_str)
        .collect();
    assert_eq!(names, vec!["add_all"]);
}

/// Drive `add_all([1, 2, 3])` through the IR. Asserts the result is
/// `1+2+3=6` and the on-chain `total: Counter` advanced.
#[tokio::test]
async fn ir_executable_synthetic_iter_add_all_runs_fold_and_tuple_ref() {
    let exec = IrExecutable::from_path(synthetic_iter_ir_path(), Arc::new(NoWitnesses))
        .expect("synthetic_iter IR loads");
    let ctor_ctx = ConstructorContext {
        initial_private_state: moonproof_runtime_ir::RuntimeValue::Null,
        initial_zswap_local_state: CompactZswapLocalState::empty(dummy_coin_public_key()),
        coin_public_key: dummy_coin_public_key(),
        signing_key: dummy_signing_key(),
        time: None,
    };
    let init = exec
        .initialize(ctor_ctx, moonproof_runtime_ir::RuntimeValue::Null)
        .await
        .expect("synthetic_iter initialize succeeds");

    let xs_av = AlignedValue::concat([
        &AlignedValue::from(1u8),
        &AlignedValue::from(2u8),
        &AlignedValue::from(3u8),
    ]);
    let xs_json = moonproof_runtime::decode_aligned_value_full(
        &exec
            .ir()
            .circuits
            .iter()
            .find(|c| c.name == "add_all")
            .unwrap()
            .arguments[0]
            .arg_type,
        &xs_av,
    )
    .expect("decode xs to JSON for the new Value-API");

    let mut before = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(&init.initial_contract_state, &mut before)
        .unwrap();

    let call_ctx = CircuitCallContext {
        contract_address: dummy_contract_address(),
        contract_state: init.initial_contract_state,
        private_state: moonproof_runtime_ir::RuntimeValue::Null,
        ledger_parameters: INITIAL_PARAMETERS.clone(),
        coin_public_key: dummy_coin_public_key(),
        tblock: Timestamp::from_secs(0),
    };

    let result = exec
        .execute_circuit("add_all", call_ctx, xs_json)
        .await
        .expect("add_all executes without Unimplemented");

    let n = result
        .result
        .as_u64()
        .or_else(|| result.result.as_str().and_then(|s| s.parse::<u64>().ok()))
        .or_else(|| {
            result.result.as_str().and_then(|s| {
                let bytes = hex::decode(s).ok()?;
                let mut buf = [0u8; 8];
                buf[..bytes.len().min(8)].copy_from_slice(&bytes[..bytes.len().min(8)]);
                Some(u64::from_le_bytes(buf))
            })
        })
        .expect("result is decodable to a small integer");
    assert_eq!(n, 6, "expected 1+2+3=6, got {}", result.result);
    assert!(
        !result.public_transcript.is_empty(),
        "fold body emits a public transcript per iteration"
    );

    let mut after = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(&result.next_contract_state, &mut after).unwrap();
    assert_ne!(
        before, after,
        "add_all must advance the `total` Counter on-chain"
    );
    assert!(
        after.len() >= before.len() / 2,
        "post-add_all state ({} bytes) shrank suspiciously vs pre-state ({} bytes)",
        after.len(),
        before.len(),
    );
}