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
//! Proof provider trait — port of
//! `@midnight-ntwrk/midnight-js-types/src/proof-provider.ts`.
//!
//! Wraps an HTTP proof server (or an in-process prover) that upgrades
//! a `Transaction<Signature, ProofPreimageMarker, PedersenRandomness>`
//! into `Transaction<Signature, ProofMarker, PedersenRandomness>` —
//! i.e. computes the ZK proofs for every contract-call segment and
//! every zswap input/output.
//!
//! The `cost_model` input from TS `createProofProvider(provingProvider,
//! costModel)` is an implementation detail of the concrete impl;
//! callers only see `prove_tx`.

use std::collections::HashMap;
use std::sync::Arc;

use moonproof_ledger::ledger::structure::{ProofPreimageMarker, Transaction};
use moonproof_ledger::signatures::Signature;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::commitment::PedersenRandomness;
use moonproof_ledger::transient_crypto::proofs::ProvingKeyMaterial;
use moonproof_macros::async_trait;

use crate::error::Result;
use crate::providers::zk_config::ZkConfigProvider;
use crate::tx_phase::{ProvenTx, UnprovenTx};

/// Configuration for a single proof request. Port of TS
/// `ProveTxConfig`.
#[derive(Debug, Clone, Default)]
pub struct ProveTxConfig {
    /// Timeout in milliseconds. `None` = use the implementation's
    /// default (typically "no timeout").
    pub timeout_ms: Option<u64>,
}

/// Rust port of TS `ProofProvider`.
#[async_trait]
pub trait ProofProvider: Send + Sync + std::fmt::Debug {
    /// Create call proofs for the given unproven transaction.
    ///
    /// Input: an [`UnprovenTx`] — the "pre-prove" shape.
    /// Output: a [`ProvenTx`] — the "post-prove, pre-bind" shape the
    /// wallet provider balances.
    async fn prove_tx(&self, tx: UnprovenTx, config: &ProveTxConfig) -> Result<ProvenTx>;
}

#[async_trait]
impl<T: ProofProvider + ?Sized> ProofProvider for std::sync::Arc<T> {
    async fn prove_tx(&self, tx: UnprovenTx, config: &ProveTxConfig) -> Result<ProvenTx> {
        (**self).prove_tx(tx, config).await
    }
}

#[async_trait]
impl<T: ProofProvider + ?Sized> ProofProvider for Box<T> {
    async fn prove_tx(&self, tx: UnprovenTx, config: &ProveTxConfig) -> Result<ProvenTx> {
        (**self).prove_tx(tx, config).await
    }
}

/// The proving keys of every contract call in `tx`, keyed by the key
/// location its preimage names, resolved from `zk_configs` with
/// [`crate::key_location::resolve_key_location`]. Empty when the tx
/// makes no calls or there are no sources (deploy and maintenance).
pub(crate) async fn collect_contract_key_materials(
    tx: &Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
    zk_configs: &[Arc<dyn ZkConfigProvider>],
) -> Result<HashMap<String, ProvingKeyMaterial>> {
    if zk_configs.is_empty() {
        return Ok(HashMap::new());
    }
    let locations = contract_call_key_locations(tx);
    if locations.is_empty() {
        return Ok(HashMap::new());
    }
    let sources: Vec<&dyn ZkConfigProvider> = zk_configs.iter().map(AsRef::as_ref).collect();
    let resolved = futures::future::try_join_all(locations.into_iter().map(|location| {
        let sources = &sources;
        async move {
            let material = crate::key_location::resolve_key_location(&location, sources).await?;
            Ok::<_, crate::error::ContractRuntimeError>(material.map(|m| (location, m)))
        }
    }))
    .await?;
    let mut out = HashMap::with_capacity(resolved.len());
    for pair in resolved.into_iter().flatten() {
        out.insert(pair.0, pair.1);
    }
    Ok(out)
}

/// The unique key locations named by the contract calls in `tx`.
fn contract_call_key_locations(
    tx: &Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
) -> Vec<String> {
    use moonproof_ledger::ledger::structure::{
        ContractAction, ProofPreimageVersioned, Transaction as LedgerTx,
    };
    let mut seen = std::collections::HashSet::<String>::new();
    let mut out = Vec::new();
    if let LedgerTx::Standard(stx) = tx {
        for pair in stx.intents.iter() {
            let (_seg, intent) = &*pair;
            for action in intent.actions.iter_deref() {
                if let ContractAction::Call(call) = action {
                    let ProofPreimageVersioned::V2(preimage) = &call.proof else {
                        continue;
                    };
                    let location = preimage.key_location.0.to_string();
                    if seen.insert(location.clone()) {
                        out.push(location);
                    }
                }
            }
        }
    }
    out
}