moonproof-prover 0.2.1

Core ZK proof engine for Moonproof, dispatching across the Midnight ZKIR v2 + v3 pipelines (mirrors midnight-ledger's proof-server)
Documentation
//! HTTP-based [`ProvingProvider`] that delegates `check` + `prove` to
//! a remote (or local-loopback) Midnight proof-server.
//!
//! Wire format mirrors `crates/proof-server/src/handlers.rs`:
//!
//! - `POST /check` — body: tagged `(ProofPreimageVersioned, Option<WrappedIr>)`,
//!   response: tagged `Vec<Option<usize>>`.
//! - `POST /prove` — body: tagged `(ProofPreimageVersioned, Option<ProvingKeyMaterial>, Option<Fr>)`,
//!   response: tagged `ProofVersioned`.
//!
//! Built-in `ZSwap` / Dust circuits use server-side key resolution
//! (we send `None` for the proving-key material; the proof-server's
//! `BuiltinResolver` fills it in). Contract circuits attach their
//! key material via [`HttpProvingProvider::with_contract_keys`] —
//! same shape as [`crate::EngineProvingProvider::with_contract_keys`].

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

use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
use moonproof_ledger::transient_crypto::curve::Fr;
use moonproof_ledger::transient_crypto::proofs::{
    Proof, ProofPreimage, ProvingKeyMaterial, ProvingProvider,
};

use crate::versioned::{ProofPreimageVersioned, ProofVersioned};

/// HTTP delegate that POSTs `check` / `prove` calls to a remote
/// Midnight proof-server.
#[derive(Clone)]
pub struct HttpProvingProvider {
    base_url: Arc<String>,
    client: reqwest::Client,
    contract_keys: Arc<HashMap<String, ProvingKeyMaterial>>,
    resolver: crate::ContractKeyResolver,
}

impl std::fmt::Debug for HttpProvingProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpProvingProvider")
            .field("base_url", &self.base_url)
            .field("contract_keys_count", &self.contract_keys.len())
            .finish_non_exhaustive()
    }
}

impl HttpProvingProvider {
    /// Create a new provider pointing at `base_url` (no trailing
    /// slash). Built with a tuned `reqwest::Client` (keep-alive pool
    /// and `TCP_NODELAY` on native targets); clone the provider to
    /// share the underlying connection pool.
    pub fn new(base_url: impl Into<String>) -> Self {
        let contract_keys = Arc::new(HashMap::new());
        Self {
            base_url: Arc::new(base_url.into()),
            client: build_http_client(),
            resolver: crate::ContractKeyResolver::new(Arc::clone(&contract_keys)),
            contract_keys,
        }
    }

    /// Attach contract proving-key material so circuit calls (not
    /// just built-in `ZSwap` / Dust) can be proved through the
    /// remote server. Same map shape `EngineProvingProvider`
    /// accepts.
    #[must_use]
    pub fn with_contract_keys(
        mut self,
        contract_keys: HashMap<String, ProvingKeyMaterial>,
    ) -> Self {
        self.contract_keys = Arc::new(contract_keys);
        self.resolver = crate::ContractKeyResolver::new(Arc::clone(&self.contract_keys));
        self
    }

    fn url(&self, path: &str) -> String {
        format!("{}{}", self.base_url, path)
    }

    fn key_ref(&self, key_location: &str) -> Option<&ProvingKeyMaterial> {
        self.contract_keys.get(key_location)
    }
}

fn build_http_client() -> reqwest::Client {
    #[cfg(not(target_arch = "wasm32"))]
    {
        reqwest::Client::builder()
            .tcp_nodelay(true)
            .pool_max_idle_per_host(8)
            .build()
            .unwrap_or_else(|_| reqwest::Client::new())
    }
    #[cfg(target_arch = "wasm32")]
    {
        reqwest::Client::new()
    }
}

impl ProvingProvider for HttpProvingProvider {
    async fn check(&self, preimage: &ProofPreimage) -> Result<Vec<Option<usize>>, anyhow::Error> {
        let ir = self
            .key_ref(&preimage.key_location.0)
            .map(|km| moonproof_ledger::transient_crypto::proofs::WrappedIr(km.ir_source.clone()));
        let est_cap = ir.as_ref().map_or(2048, |w| w.0.len() + 2048);
        let payload: (
            ProofPreimageVersioned,
            Option<moonproof_ledger::transient_crypto::proofs::WrappedIr>,
        ) = (ProofPreimageVersioned::V2(Arc::new(preimage.clone())), ir);
        let mut body = Vec::with_capacity(est_cap);
        tagged_serialize(&payload, &mut body)
            .map_err(|e| anyhow::anyhow!("serialize check payload: {e}"))?;
        let resp = self
            .client
            .post(self.url("/check"))
            .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
            .body(body)
            .send()
            .await
            .map_err(|e| anyhow::anyhow!("HTTP /check: {e}"))?;
        let status = resp.status();
        let bytes = resp
            .bytes()
            .await
            .map_err(|e| anyhow::anyhow!("HTTP /check body: {e}"))?;
        if !status.is_success() {
            anyhow::bail!(
                "remote /check returned {status}: {}",
                String::from_utf8_lossy(&bytes)
            );
        }
        let pi_skips: Vec<Option<u64>> = tagged_deserialize(&bytes[..])
            .map_err(|e| anyhow::anyhow!("deserialize check response: {e}"))?;
        pi_skips
            .into_iter()
            .map(|opt| opt.map(usize::try_from).transpose())
            .collect::<Result<_, _>>()
            .map_err(|e| anyhow::anyhow!("check response skip does not fit in usize: {e}"))
    }

    async fn prove(
        self,
        preimage: &ProofPreimage,
        overwrite_binding_input: Option<Fr>,
    ) -> Result<Proof, anyhow::Error> {
        // Borrow the contract-circuit key material directly (zero multi-MB
        // clone before serialization); leave `None` for built-in ZSwap / Dust
        // circuits so the proof-server resolves them itself.
        let key_material = self.key_ref(&preimage.key_location.0);
        let est_cap = key_material.map_or(2048, |km| {
            km.prover_key.len() + km.verifier_key.len() + km.ir_source.len() + 2048
        });
        let payload: (
            ProofPreimageVersioned,
            Option<&ProvingKeyMaterial>,
            Option<Fr>,
        ) = (
            ProofPreimageVersioned::V2(Arc::new(preimage.clone())),
            key_material,
            overwrite_binding_input,
        );
        let mut body = Vec::with_capacity(est_cap);
        tagged_serialize(&payload, &mut body)
            .map_err(|e| anyhow::anyhow!("serialize prove payload: {e}"))?;
        let resp = self
            .client
            .post(self.url("/prove"))
            .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
            .body(body)
            .send()
            .await
            .map_err(|e| anyhow::anyhow!("HTTP /prove: {e}"))?;
        let status = resp.status();
        let bytes = resp
            .bytes()
            .await
            .map_err(|e| anyhow::anyhow!("HTTP /prove body: {e}"))?;
        if !status.is_success() {
            anyhow::bail!(
                "remote /prove returned {status}: {}",
                String::from_utf8_lossy(&bytes)
            );
        }
        let proof_versioned: ProofVersioned = tagged_deserialize(&bytes[..])
            .map_err(|e| anyhow::anyhow!("deserialize prove response: {e}"))?;
        match proof_versioned {
            ProofVersioned::V2(p) => Ok(p),
        }
    }

    /// Ledger 9 asks a provider for the resolver behind it; ledger 8's
    /// trait has no such method, so it is gated rather than always
    /// present.
    #[cfg(not(feature = "ledger8"))]
    fn resolver(&self) -> &impl moonproof_ledger::transient_crypto::proofs::Resolver {
        &self.resolver
    }

    fn split(&mut self) -> Self {
        self.clone()
    }
}