moonproof-runtime 0.2.1

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
//! The secp256k1, secp256r1 and Curve25519 fields and points, executed
//! through the IR, against the results compact-runtime 0.21 computes
//! for the same contract. The vectors, and the script that produced
//! them, sit beside the fixture in `crates/runtime-ir/tests/fixtures`.

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_runtime::executable::{CircuitCallContext, ConstructorContext, InitializeResult};
use moonproof_runtime::types::CoinPublicKey;
use moonproof_runtime::CompactZswapLocalState;
use moonproof_runtime::{IrExecutable, NoWitnesses};
use moonproof_runtime_ir::RuntimeValue as Value;

const CALLER_KEY: [u8; 32] = [7; 32];

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

async fn loaded() -> (IrExecutable<NoWitnesses>, InitializeResult) {
    let exec = IrExecutable::from_path(
        fixture("extracted_foreign_curves.cbor"),
        Arc::new(NoWitnesses),
    )
    .expect("foreign_curves IR loads");
    let init = exec
        .initialize(
            ConstructorContext {
                initial_private_state: Value::Null,
                initial_zswap_local_state: CompactZswapLocalState::empty(CoinPublicKey(CALLER_KEY)),
                coin_public_key: CoinPublicKey(CALLER_KEY),
                signing_key: moonproof_ledger::signatures::schnorr_signing_key(&[0x42u8; 32])
                    .expect("32 bytes parse"),
                time: None,
            },
            Value::Null,
        )
        .await
        .expect("foreign_curves initialize");
    (exec, init)
}

async fn call(
    exec: &IrExecutable<NoWitnesses>,
    init: &InitializeResult,
    circuit: &str,
    args: Value,
) -> Result<Value, String> {
    let ctx = CircuitCallContext {
        contract_address: ContractAddress(HashOutput([0x77u8; 32])),
        contract_state: init.initial_contract_state.clone(),
        private_state: Value::Null,
        ledger_parameters: INITIAL_PARAMETERS,
        coin_public_key: CoinPublicKey(CALLER_KEY),
        tblock: Timestamp::from_secs(0),
    };
    exec.execute_circuit(circuit, ctx, args)
        .await
        .map(|r| r.result)
        .map_err(|e| e.to_string())
}

/// The vectors write every field element and byte string as hex; the
/// executor's canonical form for both is the bytes.
fn value_of(json: &serde_json::Value) -> Value {
    match json {
        serde_json::Value::String(h) => Value::Bytes(hex::decode(h).expect("vector hex")),
        serde_json::Value::Bool(b) => Value::Bool(*b),
        serde_json::Value::Array(items) => Value::Array(items.iter().map(value_of).collect()),
        serde_json::Value::Object(fields) => Value::Object(
            fields
                .iter()
                .map(|(k, v)| (k.clone(), value_of(v)))
                .collect(),
        ),
        other => panic!("unexpected vector value {other}"),
    }
}

fn vectors(section: &str) -> Vec<serde_json::Value> {
    let all: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(fixture("extracted_foreign_curves_vectors.json"))
            .expect("vectors read"),
    )
    .expect("vectors parse");
    all[section].as_array().expect("vector section").clone()
}

/// A wrong limb split or rotation round-trips through the executor's
/// own encoder and decoder unnoticed, so the wire form is checked
/// against compact-runtime's `toValue` directly.
#[test]
fn every_type_encodes_as_compact_runtime_does() {
    use moonproof_ledger::base_crypto::fab::{AlignmentAtom, AlignmentSegment};

    for case in vectors("encodings") {
        let type_name = case["type"].as_str().expect("type name");
        let descriptor: moonproof_runtime_ir::ir::TypeDescriptor =
            serde_json::from_value(serde_json::json!({ "type-name": type_name }))
                .expect("descriptor");
        let value = value_of(&case["value"]);
        let av = moonproof_runtime::encode_literal(&descriptor, &value)
            .unwrap_or_else(|e| panic!("{type_name} {value}: {e}"));
        let atoms: Vec<String> = av.value.0.iter().map(|a| hex::encode(&a.0)).collect();
        let alignment: Vec<String> = av
            .alignment
            .0
            .iter()
            .map(|s| match s {
                AlignmentSegment::Atom(AlignmentAtom::Field) => "field".to_owned(),
                AlignmentSegment::Atom(AlignmentAtom::Bytes { length }) => {
                    format!("bytes:{length}")
                }
                other => format!("{other:?}"),
            })
            .collect();
        assert_eq!(
            serde_json::json!({ "atoms": atoms, "alignment": alignment }),
            serde_json::json!({ "atoms": case["atoms"], "alignment": case["alignment"] }),
            "{type_name} {value}"
        );
    }
}

#[tokio::test]
async fn every_native_matches_compact_runtime() {
    let vectors = vectors("circuits");
    let (exec, init) = loaded().await;
    let mut failures = Vec::new();
    for case in &vectors {
        let circuit = case["circuit"].as_str().expect("circuit name");
        let args = value_of(&case["args"]);
        let args = match args {
            Value::Array(mut items) if items.len() == 1 => items.remove(0),
            other => other,
        };
        let got = call(&exec, &init, circuit, args.clone()).await;
        match (case.get("result"), got) {
            (Some(expected), Ok(got)) if value_of(expected) == got => {}
            (None, Err(_)) => {}
            // Ledger 8 has no ZKIR v3, so no curve arithmetic to run;
            // everything else still has to match.
            (_, Err(e)) if !moonproof_ledger::HAS_ZKIR_V3 && e.contains("needs ZKIR v3") => {}
            (expected, got) => failures.push(format!(
                "{circuit}({args}): expected {}, got {got:?}",
                expected.map_or_else(|| format!("error {}", case["error"]), ToString::to_string)
            )),
        }
    }
    assert!(
        failures.is_empty(),
        "{} of {} vectors differ:\n{}",
        failures.len(),
        vectors.len(),
        failures.join("\n")
    );
}

#[tokio::test]
async fn own_public_key_is_the_callers() {
    let (exec, init) = loaded().await;
    let got = call(&exec, &init, "myKey", Value::Null)
        .await
        .expect("myKey runs");
    let mut expected = std::collections::BTreeMap::new();
    expected.insert("bytes".to_owned(), Value::Bytes(CALLER_KEY.to_vec()));
    assert_eq!(got, Value::Object(expected));
}