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`] backed by [`HttpProvingProvider`] — proves
//! contract transactions through a Midnight HTTP proof server.
//!
//! Resolves contract-circuit key material on demand from attached
//! [`ZkConfigProvider`]s (such as [`crate::providers::HttpZkConfigProvider`])
//! and attaches it to the HTTP proof request, leaving built-in `ZSwap` / Dust
//! circuits to the server. Works identically on native hosts and in browsers
//! (`wasm32-unknown-unknown`).

use std::sync::Arc;
use std::time::Duration;

use moonproof_ledger::onchain_runtime::cost_model::{CostModel, INITIAL_COST_MODEL};
use moonproof_macros::async_trait;
use moonproof_prover::HttpProvingProvider;

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

/// Concrete [`ProofProvider`] delegating `prove_tx` to an HTTP proof server.
#[derive(Clone)]
pub struct HttpProofProvider {
    prover: HttpProvingProvider,
    cost_model: Arc<CostModel>,
    zk_configs: Vec<Arc<dyn ZkConfigProvider>>,
}

impl std::fmt::Debug for HttpProofProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpProofProvider")
            .field("prover", &self.prover)
            .field("zk_configs_count", &self.zk_configs.len())
            .finish_non_exhaustive()
    }
}

impl HttpProofProvider {
    /// Construct targeting `base_url` (e.g. `http://127.0.0.1:6300`) with
    /// the canonical [`INITIAL_COST_MODEL`].
    #[must_use]
    pub fn new(base_url: impl Into<String>) -> Self {
        let trimmed = base_url.into().trim_end_matches('/').to_owned();
        Self {
            prover: HttpProvingProvider::new(trimmed),
            cost_model: Arc::new(INITIAL_COST_MODEL.clone()),
            zk_configs: Vec::new(),
        }
    }

    /// Override the cost model used during proving.
    #[must_use]
    pub fn with_cost_model(mut self, cost_model: CostModel) -> Self {
        self.cost_model = Arc::new(cost_model);
        self
    }

    /// Add a [`ZkConfigProvider`] that `prove_tx` resolves contract circuit
    /// keys from. Sources are queried in insertion order.
    #[must_use]
    pub fn with_zk_config(mut self, zk_config: Arc<dyn ZkConfigProvider>) -> Self {
        self.zk_configs.push(zk_config);
        self
    }
}

#[async_trait]
impl ProofProvider for HttpProofProvider {
    async fn prove_tx(
        &self,
        tx: crate::tx_phase::UnprovenTx,
        config: &ProveTxConfig,
    ) -> Result<crate::tx_phase::ProvenTx> {
        let unproven = tx.into_inner();
        let contract_keys = collect_contract_key_materials(&unproven, &self.zk_configs).await?;
        let http_prover = self.prover.clone().with_contract_keys(contract_keys);
        let cost_model = Arc::clone(&self.cost_model);

        let prove_fut = async move {
            moonproof_prover::prove_offthread(move || async move {
                unproven.prove(http_prover, &cost_model).await
            })
            .await
            .map_err(|e| ContractRuntimeError::Proving(format!("prove(unproven tx): {e}")))?
            .map_err(|e| ContractRuntimeError::Proving(format!("prove(unproven tx): {e:?}")))
        };

        let proven = match config.timeout_ms {
            Some(ms) => moonproof_utils::rt::timeout(Duration::from_millis(ms), prove_fut)
                .await
                .map_err(|_| {
                    ContractRuntimeError::Proving(format!("proof server timed out after {ms}ms"))
                })??,
            None => prove_fut.await?,
        };

        Ok(crate::tx_phase::ProvenTx::new(proven))
    }
}

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

    #[test]
    fn provider_is_send_sync_and_debug() {
        fn assert_send_sync<T: Send + Sync + std::fmt::Debug>() {}
        assert_send_sync::<HttpProofProvider>();
    }
}