moonproof-prover 0.2.2

Core ZK proof engine for Moonproof, dispatching across the Midnight ZKIR v2 + v3 pipelines (mirrors midnight-ledger's proof-server)
Documentation
//! [`ProvingProvider`] adapter wrapping a [`ProverEngine`].
//!
//! Shares the engine's cached SRS [`CachingParamsProvider`], cached
//! [`BuiltinResolver`], and cached [`ParsedCircuitCache`] across every
//! `check` and `prove` call in a transaction.

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

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

use crate::engine::ProverEngine;
use crate::versioned_ir::prove_cached;

/// `ProvingProvider` implementation that delegates to a shared
/// [`ProverEngine`].
#[derive(Clone)]
pub struct EngineProvingProvider {
    engine: Arc<ProverEngine>,
    contract_keys: Arc<HashMap<String, ProvingKeyMaterial>>,
    resolver: crate::ContractKeyResolver,
}

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

impl EngineProvingProvider {
    /// Wrap a shared [`ProverEngine`] handle.
    #[inline]
    #[must_use]
    pub fn new(engine: Arc<ProverEngine>) -> Self {
        let contract_keys = Arc::new(HashMap::new());
        let resolver = crate::ContractKeyResolver::with_shared_builtin(
            Arc::clone(&contract_keys),
            engine.builtin_cell(),
        );
        Self {
            engine,
            contract_keys,
            resolver,
        }
    }

    /// Attach a map of contract circuit key locations to
    /// [`ProvingKeyMaterial`].
    #[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::with_shared_builtin(
            Arc::clone(&self.contract_keys),
            self.engine.builtin_cell(),
        );
        self
    }

    /// Inner engine handle.
    #[inline]
    #[must_use]
    pub fn engine(&self) -> &Arc<ProverEngine> {
        &self.engine
    }
}

impl ProvingProvider for EngineProvingProvider {
    async fn check(&self, preimage: &ProofPreimage) -> Result<Vec<Option<usize>>, anyhow::Error> {
        // Fast path: contract keys map (zero clone), else shared cached
        // BuiltinResolver (zero disk I/O after first load).
        let ir = if let Some(material) = self.contract_keys.get(preimage.key_location.0.as_ref()) {
            self.engine
                .circuit_cache()
                .get_or_parse_ir(&material.ir_source)
                .map_err(|e| anyhow::anyhow!("parse_zkir_tagged: {e}"))?
        } else {
            let builtin = self
                .engine
                .builtin_resolver()
                .map_err(|e| anyhow::anyhow!("init builtin resolver: {e}"))?;
            let material = builtin
                .resolve_key_arc(&preimage.key_location.0)
                .await?
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "no key material available for key_location '{}' — \
                         attach contract keys via EngineProvingProvider::with_contract_keys \
                         before proving a contract-call tx",
                        preimage.key_location.0,
                    )
                })?;
            self.engine
                .circuit_cache()
                .get_or_parse_ir(&material.ir_source)
                .map_err(|e| anyhow::anyhow!("parse_zkir_tagged: {e}"))?
        };
        ir.check(preimage)
            .map_err(|e| anyhow::anyhow!("ProofPreimage::check: {e}"))
    }

    async fn prove(
        self,
        preimage: &ProofPreimage,
        overwrite_binding_input: Option<Fr>,
    ) -> Result<Proof, anyhow::Error> {
        // Fast path: borrow contract key material in place (zero multi-MB clone),
        // or fetch shared Arc from the engine's cached BuiltinResolver.
        let (proof, _pi_skips) =
            if let Some(material) = self.contract_keys.get(preimage.key_location.0.as_ref()) {
                prove_cached(
                    preimage,
                    material,
                    overwrite_binding_input,
                    self.engine.params_cache(),
                    self.engine.circuit_cache(),
                    false,
                )
                .await
                .map_err(|e| anyhow::anyhow!("prove: {e}"))?
            } else {
                let builtin = self
                    .engine
                    .builtin_resolver()
                    .map_err(|e| anyhow::anyhow!("init builtin resolver: {e}"))?;
                let material = builtin
                    .resolve_key_arc(&preimage.key_location.0)
                    .await
                    .map_err(|e| anyhow::anyhow!("resolve key: {e}"))?
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "no key material for key_location '{}' — \
                             attach contract keys via EngineProvingProvider::with_contract_keys",
                            preimage.key_location.0,
                        )
                    })?;
                prove_cached(
                    preimage,
                    &material,
                    overwrite_binding_input,
                    self.engine.params_cache(),
                    self.engine.circuit_cache(),
                    false,
                )
                .await
                .map_err(|e| anyhow::anyhow!("prove: {e}"))?
            };
        Ok(proof)
    }

    #[cfg(not(feature = "ledger8"))]
    fn resolver(&self) -> &impl moonproof_ledger::transient_crypto::proofs::Resolver {
        &self.resolver
    }

    fn split(&mut self) -> Self {
        EngineProvingProvider {
            engine: Arc::clone(&self.engine),
            contract_keys: Arc::clone(&self.contract_keys),
            resolver: self.resolver.clone(),
        }
    }
}