Skip to main content

moonproof_prover/
engine.rs

1//! Core proof generation engine.
2//!
3//! Wraps midnight-ledger's ZKIR pipeline (v2 + v3 dispatch, mirrors
4//! the upstream proof-server) into a high-level API compatible with
5//! Compact compiler output, with:
6//! - In-memory SRS (`ParamsProver` + `ParamsVerifier`) caching per `k`
7//! - In-memory built-in ZSwap/Dust key caching (zero repeated disk reads)
8//! - Bounded LRU cache of parsed ZKIR + initialized v3 prover/verifier keys
9//! - Semaphore-bounded Rayon CPU dispatch + live queue/processing metrics
10
11use std::collections::HashMap;
12use std::sync::atomic::{AtomicUsize, Ordering};
13use std::sync::{Arc, OnceLock};
14use web_time::Instant;
15
16use moonproof_ledger::base_crypto::data_provider::MidnightDataProvider;
17use moonproof_ledger::ledger::structure::{
18    ProofMarker, ProofPreimageMarker, Transaction, INITIAL_TRANSACTION_COST_MODEL,
19};
20use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
21use moonproof_ledger::signatures::Signature;
22use moonproof_ledger::storage::db::InMemoryDB;
23use moonproof_ledger::transient_crypto::commitment::PedersenRandomness;
24use moonproof_ledger::transient_crypto::curve::Fr;
25use moonproof_ledger::transient_crypto::proofs::{ProofPreimage, ProvingKeyMaterial};
26use tracing::{debug, info};
27
28use crate::error::ProverError;
29use crate::key_cache::ParsedCircuitCache;
30use crate::params_cache::CachingParamsProvider;
31use crate::provider::EngineProvingProvider;
32use crate::resolver::BuiltinResolver;
33use crate::versioned_ir::{parse_zkir_json, prove_cached, VersionedIr};
34
35/// Tagged-binary input/output type for `/prove-tx`. Mirrors upstream
36/// `midnight-ledger/proof-server`'s `TransactionProvePayload`.
37pub type ProveTxInput = (
38    Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
39    HashMap<String, ProvingKeyMaterial>,
40);
41pub type ProveTxOutput = Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB>;
42
43/// Live workload snapshot of a [`ProverEngine`], surfaced by the HTTP
44/// proof-server's `/ready` endpoint.
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub struct ProverStats {
47    pub jobs_processing: usize,
48    pub jobs_pending: usize,
49    pub job_capacity: usize,
50}
51
52/// Result of a proof generation.
53#[derive(Debug, Clone)]
54pub struct ProofResult {
55    /// The proof bytes.
56    pub proof: Vec<u8>,
57    /// Time taken for proof generation in milliseconds.
58    pub duration_ms: u64,
59    /// The k value (circuit size parameter).
60    pub k: u8,
61    /// Public input skip sequence.
62    pub pi_skips: Vec<Option<usize>>,
63}
64
65/// High-level proof generation engine.
66///
67/// Uses midnight-ledger's ZKIR pipeline (v2 + v3 dispatch) to
68/// generate proofs for circuits compiled by the Compact compiler.
69///
70/// `ProverEngine` is `Send + Sync` and cheap to clone via `Arc`.
71pub struct ProverEngine {
72    params_cache: Arc<CachingParamsProvider>,
73    builtin: Arc<OnceLock<Arc<BuiltinResolver>>>,
74    circuit_cache: Arc<ParsedCircuitCache>,
75    /// Backpressure for in-flight proof jobs. Permits = `max_concurrent`.
76    proving_semaphore: Arc<tokio::sync::Semaphore>,
77    max_concurrent: usize,
78    jobs_processing: Arc<AtomicUsize>,
79    jobs_pending: Arc<AtomicUsize>,
80}
81
82impl std::fmt::Debug for ProverEngine {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.debug_struct("ProverEngine")
85            .field("params_cache", &self.params_cache)
86            .field("circuit_cache", &self.circuit_cache)
87            .field("max_concurrent_proofs", &self.max_concurrent)
88            .field(
89                "jobs_processing",
90                &self.jobs_processing.load(Ordering::Relaxed),
91            )
92            .field("jobs_pending", &self.jobs_pending.load(Ordering::Relaxed))
93            .finish_non_exhaustive()
94    }
95}
96
97/// Where keys and SRS parameters are cached: `$MIDNIGHT_PP`, else
98/// `$XDG_CACHE_HOME/midnight/zk-params`, else
99/// `$HOME/.cache/midnight/zk-params` (or `$LOCALAPPDATA`/`$USERPROFILE` on Windows).
100#[must_use]
101pub fn params_dir() -> Option<std::path::PathBuf> {
102    use std::path::PathBuf;
103    std::env::var_os("MIDNIGHT_PP")
104        .map(PathBuf::from)
105        .or_else(|| {
106            std::env::var_os("XDG_CACHE_HOME")
107                .map(|p| PathBuf::from(p).join("midnight").join("zk-params"))
108        })
109        .or_else(|| {
110            std::env::var_os("HOME").map(|p| {
111                PathBuf::from(p)
112                    .join(".cache")
113                    .join("midnight")
114                    .join("zk-params")
115            })
116        })
117        .or_else(|| {
118            std::env::var_os("LOCALAPPDATA")
119                .map(|p| PathBuf::from(p).join("midnight").join("zk-params"))
120        })
121        .or_else(|| {
122            std::env::var_os("USERPROFILE").map(|p| {
123                PathBuf::from(p)
124                    .join(".cache")
125                    .join("midnight")
126                    .join("zk-params")
127            })
128        })
129}
130
131impl ProverEngine {
132    /// Creates a new `ProverEngine` with the given data provider.
133    /// Concurrent proof slots default to `num_cpus`.
134    pub fn new(params: Arc<MidnightDataProvider>) -> Self {
135        Self::with_concurrency(params, num_cpus::get().max(1))
136    }
137
138    /// Creates a `ProverEngine` with an explicit concurrent-proof
139    /// cap. `max_concurrent` is clamped to at least 1.
140    pub fn with_concurrency(params: Arc<MidnightDataProvider>, max_concurrent: usize) -> Self {
141        let permits = max_concurrent.max(1);
142        Self {
143            params_cache: Arc::new(CachingParamsProvider::new(params)),
144            builtin: Arc::new(OnceLock::new()),
145            circuit_cache: Arc::new(ParsedCircuitCache::default()),
146            proving_semaphore: Arc::new(tokio::sync::Semaphore::new(permits)),
147            max_concurrent: permits,
148            jobs_processing: Arc::new(AtomicUsize::new(0)),
149            jobs_pending: Arc::new(AtomicUsize::new(0)),
150        }
151    }
152
153    /// Creates a `ProverEngine` with default settings.
154    pub fn from_env() -> Result<Self, ProverError> {
155        let provider = MidnightDataProvider::new(
156            moonproof_ledger::base_crypto::data_provider::FetchMode::OnDemand,
157            moonproof_ledger::base_crypto::data_provider::OutputMode::Log,
158            Vec::new(),
159        )
160        .map_err(|e| ProverError::SrsLoad(format!("Failed to init data provider: {e}")))?;
161        Ok(Self::new(Arc::new(provider)))
162    }
163
164    /// Returns the underlying data provider.
165    pub fn params(&self) -> &MidnightDataProvider {
166        self.params_cache.inner()
167    }
168
169    /// Returns the in-memory SRS cache wrapping `params()`.
170    #[inline]
171    pub(crate) fn params_cache(&self) -> &CachingParamsProvider {
172        &self.params_cache
173    }
174
175    /// Returns the shared parsed-IR & initialized-key cache.
176    #[inline]
177    pub(crate) fn circuit_cache(&self) -> &ParsedCircuitCache {
178        &self.circuit_cache
179    }
180
181    /// Shared cell holding the lazily-initialized cached [`BuiltinResolver`].
182    #[inline]
183    pub(crate) fn builtin_cell(&self) -> Arc<OnceLock<Arc<BuiltinResolver>>> {
184        Arc::clone(&self.builtin)
185    }
186
187    /// Lazily initialize and return the engine-wide cached [`BuiltinResolver`].
188    pub fn builtin_resolver(&self) -> Result<Arc<BuiltinResolver>, ProverError> {
189        if let Some(b) = self.builtin.get() {
190            return Ok(Arc::clone(b));
191        }
192        let built =
193            Arc::new(BuiltinResolver::new().map_err(|e| {
194                ProverError::Proving(format!("Failed to init builtin resolver: {e}"))
195            })?);
196        let _ = self.builtin.set(built);
197        self.builtin
198            .get()
199            .map(Arc::clone)
200            .ok_or_else(|| ProverError::Proving("builtin resolver init raced to empty".to_owned()))
201    }
202
203    /// Snapshot of currently executing and queued proof jobs.
204    #[must_use]
205    pub fn stats(&self) -> ProverStats {
206        ProverStats {
207            jobs_processing: self.jobs_processing.load(Ordering::Relaxed),
208            jobs_pending: self.jobs_pending.load(Ordering::Relaxed),
209            job_capacity: self.max_concurrent,
210        }
211    }
212
213    /// Pre-load SRS parameters for each `k` into RAM so subsequent proofs hit
214    /// the in-memory cache immediately.
215    pub async fn warm_srs(&self, ks: &[u8]) -> Result<(), ProverError> {
216        self.params_cache
217            .warm(ks)
218            .await
219            .map_err(|e| ProverError::SrsLoad(format!("Failed to warm SRS: {e}")))
220    }
221
222    /// Parses a Compact ZKIR JSON string. Auto-detects v2 vs v3.
223    pub fn parse_zkir(json: &str) -> Result<VersionedIr, ProverError> {
224        parse_zkir_json(json)
225    }
226
227    /// Determines the circuit size (k) for a given ZKIR.
228    #[must_use]
229    pub fn circuit_k(ir: &VersionedIr) -> u8 {
230        ir.k()
231    }
232
233    /// Fetches SRS parameters for a given k value (disk/S3) and warms RAM.
234    pub async fn fetch_srs(&self, k: u8) -> Result<(), ProverError> {
235        self.params_cache
236            .inner()
237            .fetch_k(k)
238            .await
239            .map_err(|e| ProverError::SrsLoad(format!("Failed to fetch SRS for k={k}: {e}")))?;
240        let _ = self.params_cache.get_prover_params(k).await;
241        Ok(())
242    }
243
244    /// Generates a proof using a `ProofPreimage` and optional `ProvingKeyMaterial`.
245    pub async fn prove_preimage(
246        self: &Arc<Self>,
247        preimage: &ProofPreimage,
248        proving_key_material: Option<ProvingKeyMaterial>,
249        binding_input: Option<Fr>,
250    ) -> Result<ProofResult, ProverError> {
251        let me = Arc::clone(self);
252        let preimage = preimage.clone();
253        self.dispatch_cpu(move || async move {
254            me.prove_preimage_inner(&preimage, proving_key_material, binding_input, true)
255                .await
256        })
257        .await
258    }
259
260    /// Inner sync-async work for [`Self::prove_preimage`].
261    async fn prove_preimage_inner(
262        &self,
263        preimage: &ProofPreimage,
264        proving_key_material: Option<ProvingKeyMaterial>,
265        binding_input: Option<Fr>,
266        need_pi_skips: bool,
267    ) -> Result<ProofResult, ProverError> {
268        let start = Instant::now();
269
270        let (proof, pi_skips) = if let Some(ref km) = proving_key_material {
271            prove_cached(
272                preimage,
273                km,
274                binding_input,
275                &self.params_cache,
276                &self.circuit_cache,
277                need_pi_skips,
278            )
279            .await?
280        } else {
281            let builtin = self.builtin_resolver()?;
282            let km = builtin
283                .resolve_key_arc(&preimage.key_location.0)
284                .await
285                .map_err(|e| ProverError::Proving(format!("resolve key for prove: {e}")))?
286                .ok_or_else(|| {
287                    ProverError::Proving(format!(
288                        "no key material for key_location '{}'",
289                        preimage.key_location.0,
290                    ))
291                })?;
292            prove_cached(
293                preimage,
294                &km,
295                binding_input,
296                &self.params_cache,
297                &self.circuit_cache,
298                need_pi_skips,
299            )
300            .await?
301        };
302
303        let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
304        let k = 0;
305
306        info!(duration_ms, proof_size = proof.0.len(), "Proof generated");
307
308        Ok(ProofResult {
309            proof: proof.0,
310            duration_ms,
311            k,
312            pi_skips,
313        })
314    }
315
316    /// Generate a proof for a tagged-serialized
317    /// `(ProofPreimageVersioned, Option<ProvingKeyMaterial>, Option<Fr>)`
318    /// payload — the same wire format the standalone proof-server's
319    /// `/prove` endpoint accepts.
320    pub async fn prove_serialized_preimage(
321        self: &Arc<Self>,
322        body: &[u8],
323    ) -> Result<Vec<u8>, ProverError> {
324        use moonproof_ledger::transient_crypto::proofs::Proof;
325
326        let (ppi_versioned, key_material, binding_input) = tagged_deserialize::<(
327            crate::versioned::ProofPreimageVersioned,
328            Option<ProvingKeyMaterial>,
329            Option<Fr>,
330        )>(body)
331        .map_err(|e| ProverError::Proving(format!("parse tagged prove payload: {e}")))?;
332
333        let preimage = ppi_versioned.inner().clone();
334        // `/prove` only serializes `ProofVersioned::V2(Proof)` — it never
335        // returns `pi_skips`, so skip the extra v2 pre-check pass.
336        let me = Arc::clone(self);
337        let result = self
338            .dispatch_cpu(move || async move {
339                me.prove_preimage_inner(&preimage, key_material, binding_input, false)
340                    .await
341            })
342            .await?;
343        let proof_versioned = crate::versioned::ProofVersioned::V2(Proof(result.proof));
344        let mut out = Vec::with_capacity(8192);
345        tagged_serialize(&proof_versioned, &mut out)
346            .map_err(|e| ProverError::Proving(format!("serialize ProofVersioned: {e}")))?;
347        Ok(out)
348    }
349
350    /// Check a tagged-serialized
351    /// `(ProofPreimageVersioned, Option<WrappedIr>)` payload.
352    pub async fn check_serialized_preimage(
353        &self,
354        body: &[u8],
355    ) -> Result<Vec<Option<String>>, ProverError> {
356        Ok(self
357            .check_payload(body)
358            .await?
359            .into_iter()
360            .map(|opt| opt.map(|n| n.to_string()))
361            .collect())
362    }
363
364    /// A `POST /check` request body, checked using cached built-in keys and
365    /// cached parsed ZKIR. Offloads constraint checking off Tokio I/O threads
366    /// on native targets.
367    pub async fn check_payload(&self, body: &[u8]) -> Result<Vec<Option<usize>>, ProverError> {
368        use crate::WrappedIr;
369
370        let (ppi_versioned, wrapped_ir) = tagged_deserialize::<(
371            crate::versioned::ProofPreimageVersioned,
372            Option<WrappedIr>,
373        )>(body)
374        .map_err(|e| ProverError::Deserialization(format!("check payload: {e}")))?;
375        let crate::versioned::ProofPreimageVersioned::V2(preimage) = ppi_versioned;
376        let ir = match wrapped_ir {
377            Some(WrappedIr(ir_bytes)) => self.circuit_cache.get_or_parse_ir(&ir_bytes)?,
378            None => self.builtin_ir(&preimage).await?,
379        };
380        #[cfg(not(target_arch = "wasm32"))]
381        {
382            tokio::task::spawn_blocking(move || Self::check_preimage(&ir, &preimage))
383                .await
384                .map_err(|e| ProverError::Proving(format!("check task join: {e}")))?
385        }
386        #[cfg(target_arch = "wasm32")]
387        {
388            Self::check_preimage(&ir, &preimage)
389        }
390    }
391
392    async fn builtin_ir(&self, preimage: &ProofPreimage) -> Result<Arc<VersionedIr>, ProverError> {
393        let builtin = self.builtin_resolver()?;
394        let material = builtin
395            .resolve_key_arc(&preimage.key_location.0)
396            .await
397            .map_err(|e| ProverError::Proving(format!("resolve key for check: {e}")))?
398            .ok_or_else(|| {
399                ProverError::Proving(format!(
400                    "no IR / key material for key_location '{}'",
401                    preimage.key_location.0
402                ))
403            })?;
404        self.circuit_cache.get_or_parse_ir(&material.ir_source)
405    }
406
407    /// Like [`Self::prove_serialized_preimage`] with out-of-band key material.
408    pub async fn prove_with_optional_keys(
409        self: &Arc<Self>,
410        body: &[u8],
411        key_material: Option<ProvingKeyMaterial>,
412        binding_input: Option<Fr>,
413    ) -> Result<Vec<u8>, ProverError> {
414        use moonproof_ledger::transient_crypto::proofs::Proof;
415
416        let ppi_versioned: crate::versioned::ProofPreimageVersioned = tagged_deserialize(body)
417            .map_err(|e| ProverError::Proving(format!("parse preimage: {e}")))?;
418        let preimage = ppi_versioned.inner().clone();
419        let me = Arc::clone(self);
420        let result = self
421            .dispatch_cpu(move || async move {
422                me.prove_preimage_inner(&preimage, key_material, binding_input, false)
423                    .await
424            })
425            .await?;
426        let proof_versioned = crate::versioned::ProofVersioned::V2(Proof(result.proof));
427        let mut out = Vec::with_capacity(8192);
428        tagged_serialize(&proof_versioned, &mut out)
429            .map_err(|e| ProverError::Proving(format!("serialize ProofVersioned: {e}")))?;
430        Ok(out)
431    }
432
433    /// Like [`Self::check_serialized_preimage`] with out-of-band key material.
434    pub async fn check_with_optional_keys(
435        &self,
436        body: &[u8],
437        key_material: Option<ProvingKeyMaterial>,
438    ) -> Result<Vec<Option<String>>, ProverError> {
439        let ppi_versioned: crate::versioned::ProofPreimageVersioned = tagged_deserialize(body)
440            .map_err(|e| ProverError::Proving(format!("parse preimage: {e}")))?;
441        let preimage = ppi_versioned.inner();
442
443        let ir = if let Some(km) = &key_material {
444            self.circuit_cache.get_or_parse_ir(&km.ir_source)?
445        } else {
446            self.builtin_ir(preimage).await?
447        };
448        let inputs = Self::check_preimage(&ir, preimage)?;
449        Ok(inputs
450            .into_iter()
451            .map(|opt| opt.map(|n| n.to_string()))
452            .collect())
453    }
454
455    /// Convenience: parse ZKIR JSON, compute k, and check the circuit.
456    pub fn parse_and_analyze(json: &str) -> Result<(VersionedIr, u8), ProverError> {
457        let ir = Self::parse_zkir(json)?;
458        let k = Self::circuit_k(&ir);
459        debug!(k, "Circuit analyzed");
460        Ok((ir, k))
461    }
462
463    /// Check a proof preimage without generating a proof.
464    pub fn check_preimage(
465        ir: &VersionedIr,
466        preimage: &ProofPreimage,
467    ) -> Result<Vec<Option<usize>>, ProverError> {
468        ir.check(preimage)
469    }
470
471    /// Prove an entire `Transaction` in one call.
472    pub async fn prove_tx(
473        self: &Arc<Self>,
474        tx: Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
475        contract_keys: HashMap<String, ProvingKeyMaterial>,
476    ) -> Result<ProveTxOutput, ProverError> {
477        let me = Arc::clone(self);
478        self.dispatch_cpu(move || async move {
479            let provider =
480                EngineProvingProvider::new(Arc::clone(&me)).with_contract_keys(contract_keys);
481            let cost_model = INITIAL_TRANSACTION_COST_MODEL.runtime_cost_model.clone();
482            tx.prove(provider, &cost_model)
483                .await
484                .map_err(|e| ProverError::Proving(format!("prove-tx: {e}")))
485        })
486        .await
487    }
488
489    /// Bytes-in / bytes-out wrapper around [`Self::prove_tx`].
490    pub async fn prove_tx_bytes(self: &Arc<Self>, payload: &[u8]) -> Result<Vec<u8>, ProverError> {
491        let (tx, contract_keys): ProveTxInput = tagged_deserialize(payload)
492            .map_err(|e| ProverError::Deserialization(format!("decode prove-tx payload: {e}")))?;
493        let proven = self.prove_tx(tx, contract_keys).await?;
494        let mut out = Vec::with_capacity(16 * 1024);
495        tagged_serialize(&proven, &mut out)
496            .map_err(|e| ProverError::Proving(format!("serialize proven tx: {e}")))?;
497        Ok(out)
498    }
499
500    /// Run a CPU-heavy async operation on the rayon pool, with a
501    /// semaphore-bounded concurrency limit and live queue/processing counters.
502    async fn dispatch_cpu<F, Fut, T>(self: &Arc<Self>, f: F) -> Result<T, ProverError>
503    where
504        F: FnOnce() -> Fut + Send + 'static,
505        Fut: std::future::Future<Output = Result<T, ProverError>>,
506        T: Send + 'static,
507    {
508        struct PendingGuard(Arc<AtomicUsize>);
509        impl Drop for PendingGuard {
510            fn drop(&mut self) {
511                self.0.fetch_sub(1, Ordering::Relaxed);
512            }
513        }
514        struct ActiveGuard(Arc<AtomicUsize>);
515        impl Drop for ActiveGuard {
516            fn drop(&mut self) {
517                self.0.fetch_sub(1, Ordering::Relaxed);
518            }
519        }
520
521        self.jobs_pending.fetch_add(1, Ordering::Relaxed);
522        let pending_guard = PendingGuard(Arc::clone(&self.jobs_pending));
523
524        let permit = self
525            .proving_semaphore
526            .clone()
527            .acquire_owned()
528            .await
529            .map_err(|e| ProverError::Proving(format!("acquire prover slot: {e}")))?;
530        drop(pending_guard);
531
532        let jobs_processing = Arc::clone(&self.jobs_processing);
533        jobs_processing.fetch_add(1, Ordering::Relaxed);
534        let active_guard = ActiveGuard(jobs_processing);
535
536        let handle = tokio::runtime::Handle::current();
537        let (tx, rx) = tokio::sync::oneshot::channel::<Result<T, ProverError>>();
538        rayon::spawn(move || {
539            let _permit = permit;
540            let _active = active_guard;
541            let result = handle.block_on(f());
542            let _ = tx.send(result);
543        });
544        rx.await
545            .map_err(|e| ProverError::Proving(format!("rayon channel closed before send: {e}")))?
546    }
547}