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: load the registry contract's contract.mpir,
//! construct an `IrExecutable` with a mock `Witnesses` provider that
//! mirrors the hand-written `RegistryExecutable`'s witness rule
//! (`(observed, next) = (current, current + 1)`), and exercise both
//! `initialize` and `execute_circuit("incrementBy", ...)`.
//!
//! This is the validation gate the project's been building toward —
//! the IR driver produces an executable that walks contract.mpir
//! and threads through to moonproof's `ContractExecutable` trait.

macro_rules! rv {
    ($($t:tt)*) => { ::moonproof_runtime_ir::RuntimeValue::from(::serde_json::json!($($t)*)) };
}

use std::sync::Arc;

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};

/// Local-count witness — mirrors `RegistryExecutable::local_count_witness`'s
/// `(current, current + 1)` rotation rule.
#[derive(Debug)]
struct LocalCountWitnesses;

impl Witnesses for LocalCountWitnesses {
    fn invoke(
        &self,
        witness_name: &str,
        _args: &moonproof_runtime_ir::RuntimeValue,
        private_state: &moonproof_runtime_ir::RuntimeValue,
    ) -> Result<moonproof_runtime::witnesses::WitnessResult, IrDriverError> {
        if witness_name != "localCount" {
            return Err(IrDriverError::Witness(format!(
                "unexpected witness '{witness_name}'"
            )));
        }
        let current = private_state.as_u64().unwrap_or(0);
        let next = current.saturating_add(1);
        Ok(moonproof_runtime::witnesses::WitnessResult {
            observed: moonproof_runtime_ir::RuntimeValue::Int(i128::from(current)),
            next_private_state: moonproof_runtime_ir::RuntimeValue::Int(i128::from(next)),
        })
    }
}

/// Path to the committed registry contract.mpir fixture.
fn registry_ir_path() -> std::path::PathBuf {
    let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    p.push("..");
    p.push("runtime-ir");
    p.push("tests/fixtures/registry.cbor");
    p
}

#[tokio::test]
async fn ir_executable_provable_circuits_match_ir() {
    let exec = IrExecutable::from_path(registry_ir_path(), Arc::new(LocalCountWitnesses))
        .expect("registry IR loads");
    let ids = exec.provable_circuit_ids();
    assert_eq!(ids.len(), 1);
    assert_eq!(ids[0].as_str(), "incrementBy");
}

#[tokio::test]
async fn ir_executable_initialize_produces_well_formed_state() {
    let exec = IrExecutable::from_path(registry_ir_path(), Arc::new(LocalCountWitnesses))
        .expect("registry IR loads");
    let ctx = ConstructorContext {
        initial_private_state: moonproof_runtime_ir::RuntimeValue::Int(i128::from(0u64)),
        initial_zswap_local_state: CompactZswapLocalState::empty(midnight_zswap_coin_public_key()),
        coin_public_key: midnight_zswap_coin_public_key(),
        signing_key: moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32])
            .expect("32 bytes parse"),
        time: None,
    };
    let init = exec
        .initialize(ctx, moonproof_runtime_ir::RuntimeValue::Null)
        .await
        .expect("initialize succeeds");
    // The initial state must round-trip through tagged_serialize —
    // matching the pattern the hand-written RegistryExecutable's
    // own test uses.
    let mut buf = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(&init.initial_contract_state, &mut buf)
        .expect("initial state must tagged_serialize");
    assert!(
        !buf.is_empty(),
        "initial state serializes to non-empty bytes"
    );
    // Initial private state passes through unchanged.
    assert_eq!(init.initial_private_state.as_u64(), Some(0));
}

#[tokio::test]
async fn ir_executable_increment_by_advances_state_and_rotates_private_state() {
    let exec = IrExecutable::from_path(registry_ir_path(), Arc::new(LocalCountWitnesses))
        .expect("registry IR loads");

    // Initialize the contract.
    let ctor_ctx = ConstructorContext {
        initial_private_state: moonproof_runtime_ir::RuntimeValue::Int(i128::from(7u64)),
        initial_zswap_local_state: CompactZswapLocalState::empty(midnight_zswap_coin_public_key()),
        coin_public_key: midnight_zswap_coin_public_key(),
        signing_key: moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32])
            .expect("32 bytes parse"),
        time: None,
    };
    let init = exec
        .initialize(ctor_ctx, moonproof_runtime_ir::RuntimeValue::Null)
        .await
        .expect("initialize succeeds");

    // Call incrementBy(amount=5).
    let call_ctx = CircuitCallContext {
        contract_address: ContractAddress(HashOutput([0x77u8; 32])),
        contract_state: init.initial_contract_state.clone(),
        private_state: moonproof_runtime_ir::RuntimeValue::Int(i128::from(7u64)),
        ledger_parameters: moonproof_ledger::ledger::structure::INITIAL_PARAMETERS.clone(),
        coin_public_key: midnight_zswap_coin_public_key(),
        tblock: Timestamp::from_secs(0),
    };
    let result = exec
        .execute_circuit("incrementBy", call_ctx, rv!(5u16))
        .await
        .expect("execute_circuit succeeds");

    // The on-chain state must advance.
    let mut init_bytes = Vec::new();
    let mut post_bytes = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(&init.initial_contract_state, &mut init_bytes)
        .expect("init state serializes");
    moonproof_ledger::serialize::tagged_serialize(&result.next_contract_state, &mut post_bytes)
        .expect("post state serializes");
    assert_ne!(
        init_bytes, post_bytes,
        "incrementBy must advance the on-chain state"
    );

    // The private state rotates: (observed, next) = (current, current+1).
    // Initial current was 7, so next = 8.
    assert_eq!(result.next_private_state.as_u64(), Some(8));

    // The result is the witness's observed value (the pre-rotation
    // current = 7).
    assert_eq!(result.result.as_u64(), Some(7));

    // Exactly one private-transcript-output entry — the witness's
    // observed value, encoded via the witness's result-type
    // descriptor (Uint<64>).
    assert_eq!(result.private_transcript_outputs.len(), 1);

    // The public transcript carries the three increment-by ops.
    assert_eq!(result.public_transcript.len(), 3);
}

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