moonproof-runtime 0.2.1

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
//! End-to-end smoke tests: drive each midnight-ledger
//! `composable-{burn,inner,relay}` contract through the IR driver.
//!
//! Each test exercises `initialize()` and at least one circuit. The
//! contracts come from the midnight-ledger team (i.e. authored
//! independently of moonproof's IR driver), so passing here is
//! evidence the driver handles real-world contracts beyond the
//! moonproof test fixtures.

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, InitializeResult};
use moonproof_runtime::types::CoinPublicKey;
use moonproof_runtime::CompactZswapLocalState;
use moonproof_runtime::{IrDriverError, IrExecutable, Witnesses};

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

impl Witnesses for GenericWitnesses {
    fn invoke(
        &self,
        witness_name: &str,
        _args: &moonproof_runtime_ir::RuntimeValue,
        private_state: &moonproof_runtime_ir::RuntimeValue,
    ) -> Result<moonproof_runtime::witnesses::WitnessResult, IrDriverError> {
        let observed = match witness_name {
            "tmpCallRand" => moonproof_runtime_ir::RuntimeValue::Bytes(vec![0u8; 32]),
            // tmpDoCall declared `(coin): []` returns the empty tuple.
            // createZswapOutput / createZswapInput — host hooks; void.
            "tmpDoCall" | "createZswapOutput" | "createZswapInput" => {
                moonproof_runtime_ir::RuntimeValue::Array(Vec::new())
            }
            other if other.starts_with("local") || other.starts_with("get") => {
                moonproof_runtime_ir::RuntimeValue::Int(0_i128)
            }
            _ => moonproof_runtime_ir::RuntimeValue::Bytes(vec![0u8; 32]),
        };
        Ok(moonproof_runtime::witnesses::WitnessResult {
            observed,
            next_private_state: private_state.clone(),
        })
    }
}

fn fixture_path(name: &str) -> std::path::PathBuf {
    let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    p.pop();
    p.push("runtime-ir");
    p.push(format!("tests/fixtures/{name}.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]))
}

async fn initialize(name: &str) -> InitializeResult {
    let exec = IrExecutable::from_path(fixture_path(name), Arc::new(GenericWitnesses))
        .unwrap_or_else(|e| panic!("{name} IR loads: {e}"));
    exec.initialize(
        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,
        },
        moonproof_runtime_ir::RuntimeValue::Null,
    )
    .await
    .unwrap_or_else(|e| panic!("{name} initialize: {e}"))
}

#[tokio::test]
async fn ir_composable_burn_initialize_succeeds() {
    let _ = initialize("composable_burn").await;
}

#[tokio::test]
async fn ir_composable_inner_initialize_succeeds() {
    let _ = initialize("composable_inner").await;
}

#[tokio::test]
async fn ir_composable_relay_initialize_succeeds() {
    let _ = initialize("composable_relay").await;
}

/// `composable_inner.set(v: Field)` hits the authority assert when
/// our fake secretKey witness doesn't match the deployed authority.
/// The driver walks the full IR up to that point; the assert firing
/// is itself evidence the IR's `Expression::Assert` arm runs correctly.
#[tokio::test]
async fn ir_composable_inner_set_runs_until_authority_assert() {
    let exec =
        IrExecutable::from_path(fixture_path("composable_inner"), Arc::new(GenericWitnesses))
            .unwrap();
    let init = initialize("composable_inner").await;
    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 f = ::moonproof_runtime_ir::RuntimeValue::String("payload".to_string());
    let err = exec
        .execute_circuit("set", call_ctx, f)
        .await
        .expect_err("set should hit the authority assert with a fake secretKey");
    let msg = format!("{err}");
    assert!(
        msg.contains("must be authority") || msg.contains("authority"),
        "expected authority-assert failure, got: {msg}"
    );
}

/// `composable_burn.burn(coin: ShieldedCoinInfo)` invokes
/// `receiveShielded(coin)`, which lowers to `kernel_self` +
/// `kernel_claim_zswap_coin_receive` op fragments. Those write to the
/// **kernel-side effects** slot, not the user-side state surfaced via
/// `next_contract_state`, so strict before/after byte-comparison shows
/// no diff. Instead, the load-bearing shape assertion is on the public
/// transcript size + popeq read count + private transcript outputs.
#[tokio::test]
async fn ir_composable_burn_advances_state() {
    let exec = IrExecutable::from_path(fixture_path("composable_burn"), Arc::new(GenericWitnesses))
        .unwrap();
    let init = initialize("composable_burn").await;
    let coin = {
        let mut obj = ::std::collections::BTreeMap::new();
        obj.insert(
            "nonce".to_string(),
            ::moonproof_runtime_ir::RuntimeValue::Bytes(vec![0x11u8; 32]),
        );
        obj.insert(
            "color".to_string(),
            ::moonproof_runtime_ir::RuntimeValue::Bytes(vec![0x22u8; 32]),
        );
        obj.insert(
            "value".to_string(),
            ::moonproof_runtime_ir::RuntimeValue::Int(1_000),
        );
        ::moonproof_runtime_ir::RuntimeValue::Object(obj)
    };
    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("burn", call_ctx, coin)
        .await
        .expect("composable_burn.burn executes");

    assert!(
        result.public_transcript.len() >= 9,
        "burn must emit ≥9 public-transcript ops; got {}",
        result.public_transcript.len()
    );
    assert_eq!(
        result.popeq_read_results.len(),
        1,
        "burn's kernel.self() read must produce exactly one popeq result"
    );
    assert_eq!(
        result.private_transcript_outputs.len(),
        1,
        "burn's createZswapOutput witness must fire exactly once"
    );
    let _ = AlignedValue::from(0u8); // silence unused-import warning
}

/// `composable_inner.set(v)` with the `authority` ledger slot
/// pre-populated to match `persistentCommit("mdn:ex:ci", secretKey())`.
/// With auth satisfied the IR walks past the assert into the
/// `value = disclose(v)` write, mutating the on-chain state. This is
/// the load-bearing **shape-differs** test for `composable_inner`: it
/// proves the IR runs the full `set` body when authority matches, not
/// just the prefix up to the assert.
#[tokio::test]
async fn ir_composable_inner_set_advances_state_with_matching_authority() {
    use moonproof_ledger::base_crypto::fab::{
        Alignment, AlignmentAtom, Value as FabValue, ValueAtom,
    };
    use moonproof_ledger::base_crypto::hash::{persistent_commit, HashOutput};
    use moonproof_ledger::onchain_runtime::context::QueryContext;
    use moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
    use moonproof_ledger::onchain_runtime::ops::Op;
    use moonproof_ledger::onchain_runtime::result_mode::ResultModeGather;
    use moonproof_ledger::onchain_runtime::state::{AlignedValueChecked, StateValue};
    use moonproof_ledger::storage::arena::Sp;
    use moonproof_ledger::storage::db::InMemoryDB;
    use moonproof_ledger::transient_crypto::fab::ValueReprAlignedValue;

    // Bytes<9> needs `AlignmentAtom::Bytes { length: 9 }` — NOT
    // `AlignmentAtom::Compress` (what `AlignedValue::from(Vec<u8>)`
    // produces). `persistent_commit` writes alignment alongside bytes,
    // so wrong alignment yields a different hash.
    let value_av = AlignedValue::new(
        FabValue(vec![ValueAtom(b"mdn:ex:ci".to_vec())]),
        Alignment::singleton(AlignmentAtom::Bytes { length: 9 }),
    )
    .expect("Bytes<9> AlignedValue");
    let opening = HashOutput([0u8; 32]);
    let HashOutput(expected_authority) =
        persistent_commit(&ValueReprAlignedValue(value_av), opening);

    let exec =
        IrExecutable::from_path(fixture_path("composable_inner"), Arc::new(GenericWitnesses))
            .unwrap();
    let mut init = initialize("composable_inner").await;

    // Patch the `authority: Bytes<32>` ledger slot (index 0) using a
    // VM-op `Push key, Push value, Ins n=1` sequence.
    let patch_ops: Vec<Op<ResultModeGather, InMemoryDB>> = vec![
        Op::Push {
            storage: false,
            value: StateValue::Cell(Sp::new(AlignedValueChecked::from(0u8))),
        },
        Op::Push {
            storage: true,
            value: StateValue::Cell(Sp::new(
                AlignedValueChecked::try_from(AlignedValue::from(expected_authority))
                    .expect("bytes atoms are always canonical"),
            )),
        },
        Op::Ins {
            cached: false,
            n: 1.try_into().unwrap(),
        },
    ];
    let qctx = QueryContext::new(
        init.initial_contract_state.data.clone(),
        dummy_contract_address(),
    );
    let patched = qctx
        .query::<ResultModeGather>(&patch_ops, None, &INITIAL_COST_MODEL)
        .expect("authority-cell patch ops succeed");
    init.initial_contract_state.data = patched.context.state;

    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),
    };
    // `set(v: Opaque<"string">)` — circuit takes a string arg.
    let v_arg = ::moonproof_runtime_ir::RuntimeValue::String("post-authority-payload".to_string());
    let result = exec
        .execute_circuit("set", call_ctx, v_arg)
        .await
        .expect("set should succeed once authority matches");
    let mut after = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(&result.next_contract_state, &mut after).unwrap();
    assert_ne!(
        before, after,
        "composable_inner.set must advance the on-chain `value` field once authority matches"
    );
    assert!(
        after.len() >= before.len() / 2,
        "post-set state ({} bytes) shrank suspiciously vs pre-state ({} bytes)",
        after.len(),
        before.len(),
    );
}

/// `composable_relay.send_to_burn(coin)` chains receiveShielded +
/// sendImmediateShielded + tmpDoCall + transientCommit +
/// kernel.claimContractCall. All effects are kernel-side; the
/// contract has two ledger fields (`burnContract`, `tmpEpComm`) but
/// only **reads** them.
#[tokio::test]
async fn ir_composable_relay_send_to_burn_advances_state() {
    let exec =
        IrExecutable::from_path(fixture_path("composable_relay"), Arc::new(GenericWitnesses))
            .unwrap();
    let init = initialize("composable_relay").await;
    let coin = {
        let mut obj = ::std::collections::BTreeMap::new();
        obj.insert(
            "nonce".to_string(),
            ::moonproof_runtime_ir::RuntimeValue::Bytes(vec![0x11u8; 32]),
        );
        obj.insert(
            "color".to_string(),
            ::moonproof_runtime_ir::RuntimeValue::Bytes(vec![0x22u8; 32]),
        );
        obj.insert(
            "value".to_string(),
            ::moonproof_runtime_ir::RuntimeValue::Int(1_000),
        );
        ::moonproof_runtime_ir::RuntimeValue::Object(obj)
    };
    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("send_to_burn", call_ctx, coin)
        .await
        .expect("composable_relay.send_to_burn executes");
    assert!(result.public_transcript.len() >= 20);
    assert!(result.popeq_read_results.len() >= 3);
    assert!(result.private_transcript_outputs.len() >= 2);
}