moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Concrete [`ProofProvider`] that drives a [`EngineProvingProvider`]
//! to upgrade every proof-preimage in a contract transaction into a
//! fully-proven one.
//!
//! Port of the TS reference's local-prover path — no HTTP proof
//! server, just an in-process prover that resolves `ZSwap` / Dust keys
//! via [`moonproof_prover::ProverEngine`]'s built-in
//! [`MidnightDataProvider`](moonproof_ledger::base_crypto::data_provider::MidnightDataProvider).
//!
//! # Transaction stages
//!
//! - **Input**: tagged-serialized
//!   `Transaction<Signature, ProofPreimageMarker, PedersenRandomness,
//!   InMemoryDB>` — the shape
//!   [`crate::unproven_deploy_tx::create_unproven_deploy_tx`] emits.
//! - **Output**: tagged-serialized
//!   `Transaction<Signature, ProofMarker, PedersenRandomness,
//!   InMemoryDB>` — post-prove, pre-seal. The wallet provider is the
//!   next stage and returns the sealed wire bytes.

use std::sync::Arc;

use moonproof_ledger::ledger::structure::{ProofMarker, ProofPreimageMarker, Transaction};
use moonproof_ledger::onchain_runtime::cost_model::{CostModel, INITIAL_COST_MODEL};
use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
use moonproof_ledger::signatures::Signature;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::commitment::{PedersenRandomness, PureGeneratorPedersen};
use moonproof_macros::async_trait;
use moonproof_prover::EngineProvingProvider;
use rand::rngs::OsRng;

use crate::error::{ContractRuntimeError, Result};
use crate::providers::proof::{collect_contract_key_materials, ProofProvider, ProveTxConfig};
use crate::providers::zk_config::ZkConfigProvider;

/// Concrete [`ProofProvider`] backed by [`EngineProvingProvider`].
///
/// Cheap to clone — the underlying engine is `Arc`-backed.
///
/// # Contract-circuit keys
///
/// When `prove_tx` receives a transaction that contains
/// contract-call preimages, the prover needs the target circuits'
/// ZKIR + prover/verifier keys. For each `ContractCallPrototype` in
/// the tx, the provider loads the circuit's key material from the
/// first source attached via [`Self::with_zk_config`] whose verifier
/// key matches the call's key location (midnight-js 5's
/// `ZKConfigRegistry`), and attaches it to the underlying
/// [`EngineProvingProvider`] before proving. A transaction whose calls
/// span several contracts, as a cross-contract call tree does, needs
/// each contract's artifacts attached. Deploys and maintenance-only
/// txs without call prototypes skip this step.
#[derive(Clone)]
pub struct InProcessProofProvider {
    engine: EngineProvingProvider,
    cost_model: Arc<CostModel>,
    zk_configs: Vec<Arc<dyn ZkConfigProvider>>,
}

impl std::fmt::Debug for InProcessProofProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InProcessProofProvider")
            .finish_non_exhaustive()
    }
}

impl InProcessProofProvider {
    /// Construct with the canonical [`INITIAL_COST_MODEL`]. Deploy /
    /// maintenance-only callers don't need to attach a
    /// `ZkConfigProvider`. Call-tx callers must thread one in via
    /// [`Self::with_zk_config`].
    #[must_use]
    pub fn new(engine: EngineProvingProvider) -> Self {
        Self {
            engine,
            cost_model: Arc::new(INITIAL_COST_MODEL.clone()),
            zk_configs: Vec::new(),
        }
    }

    /// Construct with a caller-supplied cost model — used when the
    /// chain has bumped its runtime `CostModel` past
    /// [`INITIAL_COST_MODEL`] and the caller already pulled the
    /// up-to-date one out of `ChainParameters`.
    #[must_use]
    pub fn with_cost_model(engine: EngineProvingProvider, cost_model: CostModel) -> Self {
        Self {
            engine,
            cost_model: Arc::new(cost_model),
            zk_configs: Vec::new(),
        }
    }

    /// Add a [`ZkConfigProvider`] `prove_tx` loads contract-circuit
    /// keys from. Required for call txs; sources are tried in the order
    /// they were added.
    #[must_use]
    pub fn with_zk_config(mut self, zk_config: Arc<dyn ZkConfigProvider>) -> Self {
        self.zk_configs.push(zk_config);
        self
    }

    /// Borrow the underlying [`EngineProvingProvider`].
    ///
    /// Useful for wallet sub-wallet pipelines (transfer / dust-with-spends /
    /// shielded-only) that build their own
    /// [`moonproof_ledger::transient_crypto::proofs::ProvingProvider`] flow without
    /// going through the runtime's contract-tx
    /// `prove_tx` → `balance_tx` two-step.
    #[inline]
    #[must_use]
    pub fn engine(&self) -> &EngineProvingProvider {
        &self.engine
    }

    /// Prove **and seal** an unproven transaction in one step. Suitable
    /// for the wallet sub-wallet path — transfer/registration/swap recipes
    /// from `moonproof_wallet::facade` and dust-spend-bearing flows from
    /// `moonproof_wallet::dust::ledger_adapter`. Both go from
    /// `Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>`
    /// straight to wire-format
    /// `Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB>`
    /// without a separate balance/seal stage.
    ///
    /// Contract-call key resolution is identical to
    /// [`ProofProvider::prove_tx`] — when the unproven tx contains
    /// contract-call prototypes AND a [`ZkConfigProvider`] is attached,
    /// the matching circuit keys are pre-loaded into the engine before
    /// `Transaction::prove` runs.
    pub async fn prove_and_seal_tx(&self, unproven_tx_bytes: Vec<u8>) -> Result<Vec<u8>> {
        let unproven: Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> =
            tagged_deserialize(&mut unproven_tx_bytes.as_slice()).map_err(|e| {
                ContractRuntimeError::Deserialize {
                    context: "InProcessProofProvider::prove_and_seal_tx(unproven)",
                    source: e,
                }
            })?;

        let contract_keys = collect_contract_key_materials(&unproven, &self.zk_configs).await?;
        let engine_with_keys = self.engine.clone().with_contract_keys(contract_keys);

        // Off the async runtime: proving is CPU-bound, and on ledger 9
        // the ledger's proving future is `!Send` (its resolver is an
        // `async fn` in trait), which the `#[uniffi::export]` callers
        // of this method cannot be.
        let cost_model = self.cost_model.clone();
        let proven = moonproof_prover::prove_offthread(move || async move {
            unproven.prove(engine_with_keys, &cost_model).await
        })
        .await
        .map_err(|e| ContractRuntimeError::Proving(format!("prove_and_seal_tx(prove): {e}")))?
        .map_err(|e| ContractRuntimeError::Proving(format!("prove_and_seal_tx(prove): {e:?}")))?;
        let sealed: Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB> =
            proven.seal(OsRng);

        let mut out = Vec::with_capacity(unproven_tx_bytes.len());
        tagged_serialize(&sealed, &mut out).map_err(|e| ContractRuntimeError::Serialize {
            context: "InProcessProofProvider::prove_and_seal_tx(serialize sealed)",
            source: e,
        })?;
        Ok(out)
    }
}

#[async_trait]
impl ProofProvider for InProcessProofProvider {
    async fn prove_tx(
        &self,
        tx: crate::tx_phase::UnprovenTx,
        _config: &ProveTxConfig,
    ) -> Result<crate::tx_phase::ProvenTx> {
        let unproven = tx.into_inner();

        // Pre-load every contract-circuit's ZK key material so the
        // proving engine's combined resolver can serve them up during
        // `check` / `prove`. Deploys + maintenance-only txs contain
        // no call prototypes and skip this entirely.
        let contract_keys = collect_contract_key_materials(&unproven, &self.zk_configs).await?;
        let engine_with_keys = self.engine.clone().with_contract_keys(contract_keys);

        // Off the async runtime: proving is CPU-bound, and on ledger 9
        // the ledger's proving future is `!Send` (its resolver is an
        // `async fn` in trait), which this impl cannot be.
        let cost_model = self.cost_model.clone();
        let proven = moonproof_prover::prove_offthread(move || async move {
            unproven.prove(engine_with_keys, &cost_model).await
        })
        .await
        .map_err(|e| ContractRuntimeError::Proving(format!("prove(unproven tx): {e}")))?
        .map_err(|e| ContractRuntimeError::Proving(format!("prove(unproven tx): {e:?}")))?;
        Ok(crate::tx_phase::ProvenTx::new(proven))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn provider_is_debug_and_clone() {
        // Construct without a real engine — the only non-pedantic path
        // is to verify the type-level traits are available on the
        // struct. A real prove round-trip is exercised by the
        // integration test that drives the full counter-deploy
        // pipeline; building an EngineProvingProvider here would
        // require the MidnightDataProvider's SRS cache, which is a
        // network dependency we explicitly don't want in unit tests.
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<InProcessProofProvider>();
    }
}