Skip to main content

moonproof_prover/
http_provider.rs

1//! HTTP-based [`ProvingProvider`] that delegates `check` + `prove` to
2//! a remote (or local-loopback) Midnight proof-server.
3//!
4//! Wire format mirrors `crates/proof-server/src/handlers.rs`:
5//!
6//! - `POST /check` — body: tagged `(ProofPreimageVersioned, Option<WrappedIr>)`,
7//!   response: tagged `Vec<Option<usize>>`.
8//! - `POST /prove` — body: tagged `(ProofPreimageVersioned, Option<ProvingKeyMaterial>, Option<Fr>)`,
9//!   response: tagged `ProofVersioned`.
10//!
11//! Built-in `ZSwap` / Dust circuits use server-side key resolution
12//! (we send `None` for the proving-key material; the proof-server's
13//! `BuiltinResolver` fills it in). Contract circuits attach their
14//! key material via [`HttpProvingProvider::with_contract_keys`] —
15//! same shape as [`crate::EngineProvingProvider::with_contract_keys`].
16
17use std::collections::HashMap;
18use std::sync::Arc;
19
20use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
21use moonproof_ledger::transient_crypto::curve::Fr;
22use moonproof_ledger::transient_crypto::proofs::{
23    Proof, ProofPreimage, ProvingKeyMaterial, ProvingProvider,
24};
25
26use crate::versioned::{ProofPreimageVersioned, ProofVersioned};
27
28/// HTTP delegate that POSTs `check` / `prove` calls to a remote
29/// Midnight proof-server.
30#[derive(Clone)]
31pub struct HttpProvingProvider {
32    base_url: Arc<String>,
33    client: reqwest::Client,
34    contract_keys: Arc<HashMap<String, ProvingKeyMaterial>>,
35    resolver: crate::ContractKeyResolver,
36}
37
38impl std::fmt::Debug for HttpProvingProvider {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("HttpProvingProvider")
41            .field("base_url", &self.base_url)
42            .field("contract_keys_count", &self.contract_keys.len())
43            .finish_non_exhaustive()
44    }
45}
46
47impl HttpProvingProvider {
48    /// Create a new provider pointing at `base_url` (no trailing
49    /// slash). Built with a tuned `reqwest::Client` (keep-alive pool
50    /// and `TCP_NODELAY` on native targets); clone the provider to
51    /// share the underlying connection pool.
52    pub fn new(base_url: impl Into<String>) -> Self {
53        let contract_keys = Arc::new(HashMap::new());
54        Self {
55            base_url: Arc::new(base_url.into()),
56            client: build_http_client(),
57            resolver: crate::ContractKeyResolver::new(Arc::clone(&contract_keys)),
58            contract_keys,
59        }
60    }
61
62    /// Attach contract proving-key material so circuit calls (not
63    /// just built-in `ZSwap` / Dust) can be proved through the
64    /// remote server. Same map shape `EngineProvingProvider`
65    /// accepts.
66    #[must_use]
67    pub fn with_contract_keys(
68        mut self,
69        contract_keys: HashMap<String, ProvingKeyMaterial>,
70    ) -> Self {
71        self.contract_keys = Arc::new(contract_keys);
72        self.resolver = crate::ContractKeyResolver::new(Arc::clone(&self.contract_keys));
73        self
74    }
75
76    fn url(&self, path: &str) -> String {
77        format!("{}{}", self.base_url, path)
78    }
79
80    fn key_ref(&self, key_location: &str) -> Option<&ProvingKeyMaterial> {
81        self.contract_keys.get(key_location)
82    }
83}
84
85fn build_http_client() -> reqwest::Client {
86    #[cfg(not(target_arch = "wasm32"))]
87    {
88        reqwest::Client::builder()
89            .tcp_nodelay(true)
90            .pool_max_idle_per_host(8)
91            .build()
92            .unwrap_or_else(|_| reqwest::Client::new())
93    }
94    #[cfg(target_arch = "wasm32")]
95    {
96        reqwest::Client::new()
97    }
98}
99
100impl ProvingProvider for HttpProvingProvider {
101    async fn check(&self, preimage: &ProofPreimage) -> Result<Vec<Option<usize>>, anyhow::Error> {
102        let ir = self
103            .key_ref(&preimage.key_location.0)
104            .map(|km| moonproof_ledger::transient_crypto::proofs::WrappedIr(km.ir_source.clone()));
105        let est_cap = ir.as_ref().map_or(2048, |w| w.0.len() + 2048);
106        let payload: (
107            ProofPreimageVersioned,
108            Option<moonproof_ledger::transient_crypto::proofs::WrappedIr>,
109        ) = (ProofPreimageVersioned::V2(Arc::new(preimage.clone())), ir);
110        let mut body = Vec::with_capacity(est_cap);
111        tagged_serialize(&payload, &mut body)
112            .map_err(|e| anyhow::anyhow!("serialize check payload: {e}"))?;
113        let resp = self
114            .client
115            .post(self.url("/check"))
116            .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
117            .body(body)
118            .send()
119            .await
120            .map_err(|e| anyhow::anyhow!("HTTP /check: {e}"))?;
121        let status = resp.status();
122        let bytes = resp
123            .bytes()
124            .await
125            .map_err(|e| anyhow::anyhow!("HTTP /check body: {e}"))?;
126        if !status.is_success() {
127            anyhow::bail!(
128                "remote /check returned {status}: {}",
129                String::from_utf8_lossy(&bytes)
130            );
131        }
132        let pi_skips: Vec<Option<u64>> = tagged_deserialize(&bytes[..])
133            .map_err(|e| anyhow::anyhow!("deserialize check response: {e}"))?;
134        pi_skips
135            .into_iter()
136            .map(|opt| opt.map(usize::try_from).transpose())
137            .collect::<Result<_, _>>()
138            .map_err(|e| anyhow::anyhow!("check response skip does not fit in usize: {e}"))
139    }
140
141    async fn prove(
142        self,
143        preimage: &ProofPreimage,
144        overwrite_binding_input: Option<Fr>,
145    ) -> Result<Proof, anyhow::Error> {
146        // Borrow the contract-circuit key material directly (zero multi-MB
147        // clone before serialization); leave `None` for built-in ZSwap / Dust
148        // circuits so the proof-server resolves them itself.
149        let key_material = self.key_ref(&preimage.key_location.0);
150        let est_cap = key_material.map_or(2048, |km| {
151            km.prover_key.len() + km.verifier_key.len() + km.ir_source.len() + 2048
152        });
153        let payload: (
154            ProofPreimageVersioned,
155            Option<&ProvingKeyMaterial>,
156            Option<Fr>,
157        ) = (
158            ProofPreimageVersioned::V2(Arc::new(preimage.clone())),
159            key_material,
160            overwrite_binding_input,
161        );
162        let mut body = Vec::with_capacity(est_cap);
163        tagged_serialize(&payload, &mut body)
164            .map_err(|e| anyhow::anyhow!("serialize prove payload: {e}"))?;
165        let resp = self
166            .client
167            .post(self.url("/prove"))
168            .header(reqwest::header::CONTENT_TYPE, "application/octet-stream")
169            .body(body)
170            .send()
171            .await
172            .map_err(|e| anyhow::anyhow!("HTTP /prove: {e}"))?;
173        let status = resp.status();
174        let bytes = resp
175            .bytes()
176            .await
177            .map_err(|e| anyhow::anyhow!("HTTP /prove body: {e}"))?;
178        if !status.is_success() {
179            anyhow::bail!(
180                "remote /prove returned {status}: {}",
181                String::from_utf8_lossy(&bytes)
182            );
183        }
184        let proof_versioned: ProofVersioned = tagged_deserialize(&bytes[..])
185            .map_err(|e| anyhow::anyhow!("deserialize prove response: {e}"))?;
186        match proof_versioned {
187            ProofVersioned::V2(p) => Ok(p),
188        }
189    }
190
191    /// Ledger 9 asks a provider for the resolver behind it; ledger 8's
192    /// trait has no such method, so it is gated rather than always
193    /// present.
194    #[cfg(not(feature = "ledger8"))]
195    fn resolver(&self) -> &impl moonproof_ledger::transient_crypto::proofs::Resolver {
196        &self.resolver
197    }
198
199    fn split(&mut self) -> Self {
200        self.clone()
201    }
202}