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 mint contract's `contract.mpir`
//! through the generic [`IrExecutable`].
//!
//! Mint exercises the kernel-effects path (`shielded_mints` map
//! increment, claimed-spend insertion) AND the off-chain crypto
//! natives (`persistentCommit` for `tokenType`, `persistentHash` for
//! `coinCommitment`). The IR-driven path emits the full sequence
//! compactc produces — including a `branch` skip for the "first mint
//! under this `domain_sep`" path and an `add` op for the
//! existing-entry accumulation.

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

use moonproof_runtime_ir::RuntimeValue as Value;

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::{IrDriverError, IrExecutable, Witnesses};

#[derive(Debug, Default)]
struct MintWitnesses;

impl Witnesses for MintWitnesses {
    fn invoke(
        &self,
        witness_name: &str,
        _args: &moonproof_runtime_ir::RuntimeValue,
        private_state: &moonproof_runtime_ir::RuntimeValue,
    ) -> Result<moonproof_runtime::witnesses::WitnessResult, IrDriverError> {
        match witness_name {
            "createZswapOutput" => Ok(moonproof_runtime::witnesses::WitnessResult {
                observed: moonproof_runtime_ir::RuntimeValue::Array(Vec::new()),
                next_private_state: private_state.clone(),
            }),
            other => Err(IrDriverError::Witness(format!(
                "unexpected witness '{other}' for mint contract"
            ))),
        }
    }
}

fn mint_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/mint.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]))
}

/// Build the `mint(domainSep, value, nonce, recipient)` args.
fn mint_args(domain_sep: [u8; 32], value: u64, nonce: [u8; 32], recipient: [u8; 32]) -> Value {
    let mut recipient_obj = BTreeMap::new();
    recipient_obj.insert("bytes".to_string(), Value::Bytes(recipient.to_vec()));
    let mut obj = BTreeMap::new();
    obj.insert("domainSep".to_string(), Value::Bytes(domain_sep.to_vec()));
    obj.insert("value".to_string(), Value::Int(i128::from(value)));
    obj.insert("nonce".to_string(), Value::Bytes(nonce.to_vec()));
    obj.insert("recipient".to_string(), Value::Object(recipient_obj));
    Value::Object(obj)
}

#[tokio::test]
async fn ir_executable_mint_provable_circuits_match_ir() {
    let exec =
        IrExecutable::from_path(mint_ir_path(), Arc::new(MintWitnesses)).expect("mint IR loads");
    let ids = exec.provable_circuit_ids();
    assert_eq!(ids.len(), 1);
    assert_eq!(ids[0].as_str(), "mint");
}

#[tokio::test]
async fn ir_executable_mint_initialize_registers_mint_operation() {
    let exec =
        IrExecutable::from_path(mint_ir_path(), Arc::new(MintWitnesses)).expect("mint IR loads");
    let 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(ctx, moonproof_runtime_ir::RuntimeValue::Null)
        .await
        .expect("mint initialize succeeds");
    let entry: moonproof_ledger::onchain_runtime::state::EntryPointBuf = b"mint".as_ref().into();
    assert!(
        init.initial_contract_state.operations.get(&entry).is_some(),
        "mint operation must be registered post-initialize"
    );
}

/// Drive `mint(domainSep, value, nonce, recipient)` through the IR
/// with sample args. Asserts the call succeeds, fires
/// `createZswapOutput` exactly once, emits a non-empty public
/// transcript, and returns unit.
#[tokio::test]
async fn ir_executable_mint_executes_without_unimplemented() {
    let exec =
        IrExecutable::from_path(mint_ir_path(), Arc::new(MintWitnesses)).expect("mint 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("mint initialize succeeds");

    let args = mint_args([0x11u8; 32], 1000, [0x22u8; 32], [0x33u8; 32]);

    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("mint", call_ctx, args)
        .await
        .expect("mint circuit executes without driver-side Unimplemented");

    assert_eq!(
        result.private_transcript_outputs.len(),
        1,
        "createZswapOutput should fire exactly once per mint call"
    );
    assert!(
        !result.public_transcript.is_empty(),
        "mint must emit a non-empty public transcript"
    );
    assert!(
        result.result.is_null()
            || matches!(&result.result, moonproof_runtime_ir::RuntimeValue::Array(a) if a.is_empty()),
        "mint returns unit; got {:?}",
        result.result
    );
}

/// The kernel-witness bridge populates
/// `next_zswap_local_state.outputs` directly from the IR — verifies
/// the typed `CoinInfo` + `Recipient::User` end up in the local
/// state without going through the call-tx pipeline.
#[tokio::test]
async fn ir_executable_mint_bridges_create_zswap_output_into_local_state() {
    let exec =
        IrExecutable::from_path(mint_ir_path(), Arc::new(MintWitnesses)).expect("mint 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("mint initialize");

    let recipient_pk = CoinPublicKey([0xCC; 32]);
    let args = mint_args([0x11u8; 32], 4_242, [0x22u8; 32], recipient_pk.0);

    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("mint", call_ctx, args)
        .await
        .expect("mint executes");

    // Exactly one zswap output recorded in the local state.
    assert_eq!(
        result.next_zswap_local_state.outputs.len(),
        1,
        "createZswapOutput must push one output into next_zswap_local_state"
    );
    let entry = &result.next_zswap_local_state.outputs[0];
    assert_eq!(
        entry.coin_info.value, 4_242,
        "coin_info.value must round-trip through the witness bridge"
    );
    match &entry.recipient {
        moonproof_ledger::coin_structure::transfer::Recipient::User(pk) => {
            assert_eq!(
                pk.0 .0, recipient_pk.0,
                "recipient ZswapCoinPublicKey must round-trip"
            );
        }
        moonproof_ledger::coin_structure::transfer::Recipient::Contract(_) => {
            panic!("expected User recipient; got Contract");
        }
    }
    // The bridge increments current_index for each emitted output.
    assert_eq!(result.next_zswap_local_state.current_index, 1);
    // No inputs for a mint call.
    assert_eq!(result.next_zswap_local_state.inputs, []);
}