moonproof-runtime 0.2.1

Wasm-friendly Compact contract runtime core — IR walker, IR-driven circuit executor, contract state, runtime values
Documentation
//! `kernel.caller()` through the IR executor: a top-level call sees no
//! caller, as compact-runtime records off-chain, and a cross-contract
//! callee sees the contract that called it.

use std::collections::HashMap;
use std::path::PathBuf;
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::onchain_runtime::state::ContractState;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_runtime::executable::{CircuitCallContext, ConstructorContext};
use moonproof_runtime::types::{CoinPublicKey, VerifierKey};
use moonproof_runtime::{
    CallTreeOutcome, CallTreeResult, CalleeContract, CompactZswapLocalState, CrossContractSession,
    IrExecutable, NoWitnesses,
};
use moonproof_runtime_ir::RuntimeValue as Value;
use rand::rngs::StdRng;
use rand::SeedableRng;

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

fn verifier_keys(name: &str) -> HashMap<String, VerifierKey> {
    std::fs::read_dir(fixture(name).join("keys"))
        .unwrap()
        .filter_map(|entry| {
            let path = entry.unwrap().path();
            let circuit = path
                .file_name()?
                .to_str()?
                .strip_suffix(".verifier")?
                .to_owned();
            Some((circuit, VerifierKey::new(std::fs::read(&path).unwrap())))
        })
        .collect()
}

fn executable(name: &str) -> IrExecutable<NoWitnesses> {
    IrExecutable::from_path(fixture(name).join("contract.mpir"), Arc::new(NoWitnesses))
        .unwrap()
        .with_verifier_keys(verifier_keys(name))
}

fn address(byte: u8) -> ContractAddress {
    ContractAddress(HashOutput([byte; 32]))
}

fn address_value(address: ContractAddress) -> Value {
    let mut obj = std::collections::BTreeMap::new();
    obj.insert("bytes".to_owned(), Value::Bytes(address.0 .0.to_vec()));
    Value::Object(obj)
}

async fn deploy(name: &str, args: Value) -> ContractState<InMemoryDB> {
    executable(name)
        .initialize(
            ConstructorContext {
                initial_private_state: Value::Null,
                initial_zswap_local_state: CompactZswapLocalState::empty(CoinPublicKey([0; 32])),
                coin_public_key: CoinPublicKey([0; 32]),
                signing_key: moonproof_ledger::signatures::schnorr_signing_key(&[0x42; 32])
                    .unwrap(),
                time: None,
            },
            args,
        )
        .await
        .unwrap()
        .initial_contract_state
}

fn context(address: ContractAddress, state: ContractState<InMemoryDB>) -> CircuitCallContext {
    CircuitCallContext {
        contract_address: address,
        contract_state: state,
        private_state: Value::Null,
        ledger_parameters: INITIAL_PARAMETERS.clone(),
        coin_public_key: CoinPublicKey([0; 32]),
        tblock: Timestamp::from_secs(0),
    }
}

fn callee(name: &str, state: ContractState<InMemoryDB>) -> CalleeContract {
    CalleeContract {
        ir: Arc::new(executable(name).ir().clone()),
        state,
        verifier_keys: verifier_keys(name),
    }
}

/// Runs the tree to completion, binding each callee the run asks for
/// from `deployed`, and returns the result with the addresses asked for
/// in order.
async fn run_tree(
    root: &IrExecutable<NoWitnesses>,
    circuit: &str,
    ctx: &CircuitCallContext,
    args: &Value,
    deployed: &HashMap<ContractAddress, (&str, ContractState<InMemoryDB>)>,
) -> (CallTreeResult, Vec<ContractAddress>) {
    let mut session = CrossContractSession::new();
    let mut rng = StdRng::seed_from_u64(7);
    let mut asked = Vec::new();
    loop {
        match root
            .execute_call_tree(&mut rng, circuit, ctx.clone(), args.clone(), &mut session)
            .await
            .unwrap()
        {
            CallTreeOutcome::Executed(result) => return (*result, asked),
            CallTreeOutcome::CalleeRequired(address) => {
                assert!(!asked.contains(&address), "{address:?} asked for twice");
                asked.push(address);
                let (name, state) = deployed.get(&address).expect("callee is deployed");
                session.bind_callee(address, callee(name, state.clone()));
            }
        }
    }
}

fn object(fields: &[(&str, Value)]) -> Value {
    Value::Object(
        fields
            .iter()
            .map(|(k, v)| ((*k).to_owned(), v.clone()))
            .collect(),
    )
}

/// A `Maybe<Either<ContractAddress, UserAddress>>` as the executor returns it.
fn maybe_caller(contract: Option<ContractAddress>) -> Value {
    let bytes = |a: Option<ContractAddress>| {
        object(&[(
            "bytes",
            Value::Bytes(a.map_or(vec![0; 32], |a| a.0 .0.to_vec())),
        )])
    };
    object(&[
        ("is_some", Value::Bool(contract.is_some())),
        (
            "value",
            object(&[
                ("is_left", Value::Bool(contract.is_some())),
                ("left", bytes(contract)),
                ("right", bytes(None)),
            ]),
        ),
    ])
}

const PROBE: u8 = 0xc1;
const PROXY: u8 = 0x9e;

#[tokio::test]
async fn a_top_level_call_sees_no_caller() {
    if moonproof_ledger::ERA != moonproof_ledger::LedgerEra::V9 {
        return;
    }
    let probe = executable("caller_probe");
    let state = deploy("caller_probe", Value::Null).await;
    let result = probe
        .execute_circuit("capture", context(address(PROBE), state), Value::Null)
        .await
        .unwrap()
        .result;
    assert_eq!(result, maybe_caller(None));
}

#[tokio::test]
async fn a_callee_sees_the_contract_that_called_it() {
    if moonproof_ledger::ERA != moonproof_ledger::LedgerEra::V9 {
        return;
    }
    let mut deployed = HashMap::new();
    deployed.insert(
        address(PROBE),
        ("caller_probe", deploy("caller_probe", Value::Null).await),
    );
    let proxy_state = deploy("caller_proxy", address_value(address(PROBE))).await;
    let (result, asked) = run_tree(
        &executable("caller_proxy"),
        "forward",
        &context(address(PROXY), proxy_state),
        &Value::Null,
        &deployed,
    )
    .await;
    assert_eq!(asked, vec![address(PROBE)]);
    assert_eq!(result.root.result, maybe_caller(Some(address(PROXY))));
}