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_casts` fixture through the
//! generic [`IrExecutable`].
//!
//! Exercises cast/byte-shaped Expression variants no other current
//! fixture reaches: `vector->bytes`, `bytes->vector`, `bytes-ref`,
//! `field->bytes`, and `cast-from-bytes` for non-`Field` targets.

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_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::{IrExecutable, NoWitnesses};

fn synthetic_casts_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_casts.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]))
}

fn fresh_call_ctx(
    state: moonproof_ledger::onchain_runtime::state::ContractState<
        moonproof_ledger::storage::db::InMemoryDB,
    >,
) -> CircuitCallContext {
    CircuitCallContext {
        contract_address: dummy_contract_address(),
        contract_state: 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),
    }
}

async fn loaded_executable() -> (IrExecutable<NoWitnesses>, InitializeResult) {
    let exec = IrExecutable::from_path(synthetic_casts_ir_path(), Arc::new(NoWitnesses))
        .expect("synthetic_casts IR loads");
    let init = 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
        .expect("synthetic_casts initialize");
    (exec, init)
}

#[tokio::test]
async fn ir_executable_synthetic_casts_provable_circuits() {
    let exec = IrExecutable::from_path(synthetic_casts_ir_path(), Arc::new(NoWitnesses))
        .expect("synthetic_casts IR loads");
    let names: Vec<String> = exec
        .provable_circuit_ids()
        .iter()
        .map(|c| c.as_str().to_owned())
        .collect();
    assert_eq!(names.len(), 4);
    for name in &[
        "pack_vector",
        "unpack_to_vector",
        "field_to_bytes_demo",
        "cast_bytes_to_uint",
    ] {
        assert!(
            names.contains(&(*name).to_owned()),
            "expected '{name}' in {names:?}"
        );
    }
}

/// `pack_vector(xs: Vector<8, Uint<8>>)` exercises `Expression::Vector`
/// + `Expression::VectorToBytes` (the `as Bytes<8>` cast). Shape-differs
/// gate: writes the `packed: Bytes<8>` ledger field.
#[tokio::test]
async fn ir_synthetic_casts_pack_vector_executes() {
    let (exec, init) = loaded_executable().await;
    let xs = rv!([1u8, 2u8, 3u8, 4u8, 5u8, 6u8, 7u8, 8u8]);
    let mut before = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(&init.initial_contract_state, &mut before)
        .unwrap();
    let result = exec
        .execute_circuit(
            "pack_vector",
            fresh_call_ctx(init.initial_contract_state),
            xs,
        )
        .await
        .expect("pack_vector executes");
    let mut after = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(&result.next_contract_state, &mut after).unwrap();
    assert_ne!(
        before, after,
        "pack_vector must advance the on-chain `packed` field"
    );
    assert!(after.len() >= before.len() / 2);
}

#[tokio::test]
async fn ir_synthetic_casts_unpack_to_vector_executes() {
    let (exec, init) = loaded_executable().await;
    let bytes = ::moonproof_runtime_ir::RuntimeValue::Bytes(vec![
        0x10u8, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
    ]);
    exec.execute_circuit(
        "unpack_to_vector",
        fresh_call_ctx(init.initial_contract_state),
        bytes,
    )
    .await
    .expect("unpack_to_vector executes (bytes->vector + bytes-ref)");
}

#[tokio::test]
async fn ir_synthetic_casts_field_to_bytes_executes() {
    let (exec, init) = loaded_executable().await;
    let mut le = vec![0u8; 32];
    le[0] = 42;
    let f = ::moonproof_runtime_ir::RuntimeValue::Bytes(le);
    exec.execute_circuit(
        "field_to_bytes_demo",
        fresh_call_ctx(init.initial_contract_state),
        f,
    )
    .await
    .expect("field_to_bytes_demo executes (field->bytes)");
}

#[tokio::test]
async fn ir_synthetic_casts_cast_bytes_to_uint_executes() {
    let (exec, init) = loaded_executable().await;
    let bytes = ::moonproof_runtime_ir::RuntimeValue::Bytes(vec![0x01u8, 0x02, 0x03, 0x04]);
    exec.execute_circuit(
        "cast_bytes_to_uint",
        fresh_call_ctx(init.initial_contract_state),
        bytes,
    )
    .await
    .expect("cast_bytes_to_uint executes (cast-from-bytes Uint<32>)");
}