Skip to main content

moonproof_contracts/providers/
http_proof.rs

1//! Concrete [`ProofProvider`] backed by [`HttpProvingProvider`] — proves
2//! contract transactions through a Midnight HTTP proof server.
3//!
4//! Resolves contract-circuit key material on demand from attached
5//! [`ZkConfigProvider`]s (such as [`crate::providers::HttpZkConfigProvider`])
6//! and attaches it to the HTTP proof request, leaving built-in `ZSwap` / Dust
7//! circuits to the server. Works identically on native hosts and in browsers
8//! (`wasm32-unknown-unknown`).
9
10use std::sync::Arc;
11use std::time::Duration;
12
13use moonproof_ledger::onchain_runtime::cost_model::{CostModel, INITIAL_COST_MODEL};
14use moonproof_macros::async_trait;
15use moonproof_prover::HttpProvingProvider;
16
17use crate::error::{ContractRuntimeError, Result};
18use crate::providers::proof::{collect_contract_key_materials, ProofProvider, ProveTxConfig};
19use crate::providers::zk_config::ZkConfigProvider;
20
21/// Concrete [`ProofProvider`] delegating `prove_tx` to an HTTP proof server.
22#[derive(Clone)]
23pub struct HttpProofProvider {
24    prover: HttpProvingProvider,
25    cost_model: Arc<CostModel>,
26    zk_configs: Vec<Arc<dyn ZkConfigProvider>>,
27}
28
29impl std::fmt::Debug for HttpProofProvider {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        f.debug_struct("HttpProofProvider")
32            .field("prover", &self.prover)
33            .field("zk_configs_count", &self.zk_configs.len())
34            .finish_non_exhaustive()
35    }
36}
37
38impl HttpProofProvider {
39    /// Construct targeting `base_url` (e.g. `http://127.0.0.1:6300`) with
40    /// the canonical [`INITIAL_COST_MODEL`].
41    #[must_use]
42    pub fn new(base_url: impl Into<String>) -> Self {
43        let trimmed = base_url.into().trim_end_matches('/').to_owned();
44        Self {
45            prover: HttpProvingProvider::new(trimmed),
46            cost_model: Arc::new(INITIAL_COST_MODEL.clone()),
47            zk_configs: Vec::new(),
48        }
49    }
50
51    /// Override the cost model used during proving.
52    #[must_use]
53    pub fn with_cost_model(mut self, cost_model: CostModel) -> Self {
54        self.cost_model = Arc::new(cost_model);
55        self
56    }
57
58    /// Add a [`ZkConfigProvider`] that `prove_tx` resolves contract circuit
59    /// keys from. Sources are queried in insertion order.
60    #[must_use]
61    pub fn with_zk_config(mut self, zk_config: Arc<dyn ZkConfigProvider>) -> Self {
62        self.zk_configs.push(zk_config);
63        self
64    }
65}
66
67#[async_trait]
68impl ProofProvider for HttpProofProvider {
69    async fn prove_tx(
70        &self,
71        tx: crate::tx_phase::UnprovenTx,
72        config: &ProveTxConfig,
73    ) -> Result<crate::tx_phase::ProvenTx> {
74        let unproven = tx.into_inner();
75        let contract_keys = collect_contract_key_materials(&unproven, &self.zk_configs).await?;
76        let http_prover = self.prover.clone().with_contract_keys(contract_keys);
77        let cost_model = Arc::clone(&self.cost_model);
78
79        let prove_fut = async move {
80            moonproof_prover::prove_offthread(move || async move {
81                unproven.prove(http_prover, &cost_model).await
82            })
83            .await
84            .map_err(|e| ContractRuntimeError::Proving(format!("prove(unproven tx): {e}")))?
85            .map_err(|e| ContractRuntimeError::Proving(format!("prove(unproven tx): {e:?}")))
86        };
87
88        let proven = match config.timeout_ms {
89            Some(ms) => moonproof_utils::rt::timeout(Duration::from_millis(ms), prove_fut)
90                .await
91                .map_err(|_| {
92                    ContractRuntimeError::Proving(format!("proof server timed out after {ms}ms"))
93                })??,
94            None => prove_fut.await?,
95        };
96
97        Ok(crate::tx_phase::ProvenTx::new(proven))
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    #[test]
106    fn provider_is_send_sync_and_debug() {
107        fn assert_send_sync<T: Send + Sync + std::fmt::Debug>() {}
108        assert_send_sync::<HttpProofProvider>();
109    }
110}