moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Resolving the callees of a call tree: each callee's code from a
//! [`ContractModuleProvider`], its state from the chain, both pinned to
//! the block the root's state was read at so the whole tree sees one
//! snapshot (midnight-js 5's `makeCalleeStateResolver`).

use std::collections::HashMap;

use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_macros::async_trait;
use moonproof_runtime::executable::CircuitCallContext;
use moonproof_runtime::ir::witnesses::Witnesses;
use moonproof_runtime::types::VerifierKey;
use moonproof_runtime::{
    CallTreeOutcome, CallTreeResult, CalleeContract, CrossContractSession, IrExecutable,
};
use moonproof_runtime_ir::RuntimeValue;
use rand::{CryptoRng, Rng};

use crate::error::{ContractRuntimeError, Result};
use crate::providers::{ContractModuleProvider, PublicDataProvider, ZkConfigProvider};
use crate::types::{CircuitId, ContractStateQueryAt};

/// A callee bound to its code, with the zswap chain state read beside
/// its contract state, which a callee spending a contract-owned coin
/// anchors its input in.
#[derive(Debug, Clone)]
pub struct ResolvedCallee {
    pub contract: CalleeContract,
    pub zswap_chain_state_bytes: Vec<u8>,
}

/// Binds the callees a call tree reaches.
#[async_trait]
pub trait CalleeResolver: Send + Sync {
    /// The code and state of the contract at `address`.
    ///
    /// # Errors
    ///
    /// When nothing is deployed at `address`, or no code is bound to it.
    async fn resolve_callee(&self, address: &ContractAddress) -> Result<ResolvedCallee>;
}

/// Callees from a module provider and the chain, read at one block.
pub struct ChainCallees<'a, M: ?Sized, D: ?Sized> {
    pub modules: &'a M,
    pub public_data: &'a D,
    pub at: ContractStateQueryAt,
}

#[async_trait]
impl<M, D> CalleeResolver for ChainCallees<'_, M, D>
where
    M: ContractModuleProvider + ?Sized,
    D: PublicDataProvider + ?Sized,
{
    async fn resolve_callee(&self, address: &ContractAddress) -> Result<ResolvedCallee> {
        let hex = moonproof_runtime::state::contract_address_to_hex(address);
        let states = self
            .public_data
            .query_zswap_and_contract_state(address, Some(self.at.clone()))
            .await?
            .ok_or_else(|| {
                ContractRuntimeError::NotFound(format!(
                    "no contract is deployed at cross-contract callee {hex}"
                ))
            })?;
        let module =
            self.modules
                .resolve(address)
                .await?
                .ok_or_else(|| ContractRuntimeError::Provider {
                    provider: "contract_modules",
                    message: format!("no contract module is bound to cross-contract callee {hex}"),
                })?;
        let verifier_keys = module_verifier_keys(&module.ir, module.zk_config.as_ref()).await?;
        Ok(ResolvedCallee {
            contract: CalleeContract {
                ir: module.ir,
                state: states.contract_state,
                verifier_keys,
            },
            zswap_chain_state_bytes: states.zswap_chain_state_bytes,
        })
    }
}

/// The verifier keys a module's artifacts hold for its provable
/// circuits. A circuit the artifacts lack is left out, and fails the
/// implementation check only if it is the one called; artifacts that
/// fail their integrity check fail the resolution.
async fn module_verifier_keys(
    ir: &moonproof_runtime_ir::ir::MoonIr,
    zk_config: &dyn ZkConfigProvider,
) -> Result<HashMap<String, VerifierKey>> {
    let mut keys = HashMap::new();
    for circuit in ir.circuits.iter().filter(|c| c.exported && c.proof) {
        match zk_config
            .get_verifier_key(&CircuitId::new(circuit.name.clone()))
            .await
        {
            Ok(vk) => {
                keys.insert(circuit.name.clone(), vk);
            }
            Err(e @ ContractRuntimeError::ZkArtifactIntegrity(_)) => return Err(e),
            Err(_) => {}
        }
    }
    Ok(keys)
}

/// Run `circuit` and every call it makes, binding callees from
/// `resolver` as the tree reaches them. Returns the tree and the zswap
/// chain state of each callee.
pub(crate) async fn execute_call_tree<W, R>(
    rng: &mut R,
    executable: &IrExecutable<W>,
    circuit: &str,
    ctx: CircuitCallContext,
    args: RuntimeValue,
    resolver: &dyn CalleeResolver,
) -> Result<(CallTreeResult, HashMap<ContractAddress, Vec<u8>>)>
where
    W: Witnesses + 'static,
    R: Rng + CryptoRng,
{
    let mut session = CrossContractSession::new();
    let mut chain_states = HashMap::new();
    loop {
        match executable
            .execute_call_tree(rng, circuit, ctx.clone(), args.clone(), &mut session)
            .await?
        {
            CallTreeOutcome::Executed(tree) => return Ok((*tree, chain_states)),
            CallTreeOutcome::CalleeRequired(address) => {
                let found = resolver.resolve_callee(&address).await?;
                chain_states.insert(address, found.zswap_chain_state_bytes);
                session.bind_callee(address, found.contract);
            }
        }
    }
}