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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Core proof generation engine.
//!
//! Wraps midnight-ledger's ZKIR pipeline (v2 + v3 dispatch, mirrors
//! the upstream proof-server) into a high-level API compatible with
//! Compact compiler output, with:
//! - In-memory SRS (`ParamsProver` + `ParamsVerifier`) caching per `k`
//! - In-memory built-in ZSwap/Dust key caching (zero repeated disk reads)
//! - Bounded LRU cache of parsed ZKIR + initialized v3 prover/verifier keys
//! - Semaphore-bounded Rayon CPU dispatch + live queue/processing metrics

use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, OnceLock};
use web_time::Instant;

use moonproof_ledger::base_crypto::data_provider::MidnightDataProvider;
use moonproof_ledger::ledger::structure::{
    ProofMarker, ProofPreimageMarker, Transaction, INITIAL_TRANSACTION_COST_MODEL,
};
use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
use moonproof_ledger::signatures::Signature;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::commitment::PedersenRandomness;
use moonproof_ledger::transient_crypto::curve::Fr;
use moonproof_ledger::transient_crypto::proofs::{ProofPreimage, ProvingKeyMaterial};
use tracing::{debug, info};

use crate::error::ProverError;
use crate::key_cache::ParsedCircuitCache;
use crate::params_cache::CachingParamsProvider;
use crate::provider::EngineProvingProvider;
use crate::resolver::BuiltinResolver;
use crate::versioned_ir::{parse_zkir_json, prove_cached, VersionedIr};

/// Tagged-binary input/output type for `/prove-tx`. Mirrors upstream
/// `midnight-ledger/proof-server`'s `TransactionProvePayload`.
pub type ProveTxInput = (
    Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
    HashMap<String, ProvingKeyMaterial>,
);
pub type ProveTxOutput = Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB>;

/// Live workload snapshot of a [`ProverEngine`], surfaced by the HTTP
/// proof-server's `/ready` endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProverStats {
    pub jobs_processing: usize,
    pub jobs_pending: usize,
    pub job_capacity: usize,
}

/// Result of a proof generation.
#[derive(Debug, Clone)]
pub struct ProofResult {
    /// The proof bytes.
    pub proof: Vec<u8>,
    /// Time taken for proof generation in milliseconds.
    pub duration_ms: u64,
    /// The k value (circuit size parameter).
    pub k: u8,
    /// Public input skip sequence.
    pub pi_skips: Vec<Option<usize>>,
}

/// High-level proof generation engine.
///
/// Uses midnight-ledger's ZKIR pipeline (v2 + v3 dispatch) to
/// generate proofs for circuits compiled by the Compact compiler.
///
/// `ProverEngine` is `Send + Sync` and cheap to clone via `Arc`.
pub struct ProverEngine {
    params_cache: Arc<CachingParamsProvider>,
    builtin: Arc<OnceLock<Arc<BuiltinResolver>>>,
    circuit_cache: Arc<ParsedCircuitCache>,
    /// Backpressure for in-flight proof jobs. Permits = `max_concurrent`.
    proving_semaphore: Arc<tokio::sync::Semaphore>,
    max_concurrent: usize,
    jobs_processing: Arc<AtomicUsize>,
    jobs_pending: Arc<AtomicUsize>,
}

impl std::fmt::Debug for ProverEngine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProverEngine")
            .field("params_cache", &self.params_cache)
            .field("circuit_cache", &self.circuit_cache)
            .field("max_concurrent_proofs", &self.max_concurrent)
            .field(
                "jobs_processing",
                &self.jobs_processing.load(Ordering::Relaxed),
            )
            .field("jobs_pending", &self.jobs_pending.load(Ordering::Relaxed))
            .finish_non_exhaustive()
    }
}

/// Where keys and SRS parameters are cached: `$MIDNIGHT_PP`, else
/// `$XDG_CACHE_HOME/midnight/zk-params`, else
/// `$HOME/.cache/midnight/zk-params` (or `$LOCALAPPDATA`/`$USERPROFILE` on Windows).
#[must_use]
pub fn params_dir() -> Option<std::path::PathBuf> {
    use std::path::PathBuf;
    std::env::var_os("MIDNIGHT_PP")
        .map(PathBuf::from)
        .or_else(|| {
            std::env::var_os("XDG_CACHE_HOME")
                .map(|p| PathBuf::from(p).join("midnight").join("zk-params"))
        })
        .or_else(|| {
            std::env::var_os("HOME").map(|p| {
                PathBuf::from(p)
                    .join(".cache")
                    .join("midnight")
                    .join("zk-params")
            })
        })
        .or_else(|| {
            std::env::var_os("LOCALAPPDATA")
                .map(|p| PathBuf::from(p).join("midnight").join("zk-params"))
        })
        .or_else(|| {
            std::env::var_os("USERPROFILE").map(|p| {
                PathBuf::from(p)
                    .join(".cache")
                    .join("midnight")
                    .join("zk-params")
            })
        })
}

impl ProverEngine {
    /// Creates a new `ProverEngine` with the given data provider.
    /// Concurrent proof slots default to `num_cpus`.
    pub fn new(params: Arc<MidnightDataProvider>) -> Self {
        Self::with_concurrency(params, num_cpus::get().max(1))
    }

    /// Creates a `ProverEngine` with an explicit concurrent-proof
    /// cap. `max_concurrent` is clamped to at least 1.
    pub fn with_concurrency(params: Arc<MidnightDataProvider>, max_concurrent: usize) -> Self {
        let permits = max_concurrent.max(1);
        Self {
            params_cache: Arc::new(CachingParamsProvider::new(params)),
            builtin: Arc::new(OnceLock::new()),
            circuit_cache: Arc::new(ParsedCircuitCache::default()),
            proving_semaphore: Arc::new(tokio::sync::Semaphore::new(permits)),
            max_concurrent: permits,
            jobs_processing: Arc::new(AtomicUsize::new(0)),
            jobs_pending: Arc::new(AtomicUsize::new(0)),
        }
    }

    /// Creates a `ProverEngine` with default settings.
    pub fn from_env() -> Result<Self, ProverError> {
        let provider = MidnightDataProvider::new(
            moonproof_ledger::base_crypto::data_provider::FetchMode::OnDemand,
            moonproof_ledger::base_crypto::data_provider::OutputMode::Log,
            Vec::new(),
        )
        .map_err(|e| ProverError::SrsLoad(format!("Failed to init data provider: {e}")))?;
        Ok(Self::new(Arc::new(provider)))
    }

    /// Returns the underlying data provider.
    pub fn params(&self) -> &MidnightDataProvider {
        self.params_cache.inner()
    }

    /// Returns the in-memory SRS cache wrapping `params()`.
    #[inline]
    pub(crate) fn params_cache(&self) -> &CachingParamsProvider {
        &self.params_cache
    }

    /// Returns the shared parsed-IR & initialized-key cache.
    #[inline]
    pub(crate) fn circuit_cache(&self) -> &ParsedCircuitCache {
        &self.circuit_cache
    }

    /// Shared cell holding the lazily-initialized cached [`BuiltinResolver`].
    #[inline]
    pub(crate) fn builtin_cell(&self) -> Arc<OnceLock<Arc<BuiltinResolver>>> {
        Arc::clone(&self.builtin)
    }

    /// Lazily initialize and return the engine-wide cached [`BuiltinResolver`].
    pub fn builtin_resolver(&self) -> Result<Arc<BuiltinResolver>, ProverError> {
        if let Some(b) = self.builtin.get() {
            return Ok(Arc::clone(b));
        }
        let built =
            Arc::new(BuiltinResolver::new().map_err(|e| {
                ProverError::Proving(format!("Failed to init builtin resolver: {e}"))
            })?);
        let _ = self.builtin.set(built);
        self.builtin
            .get()
            .map(Arc::clone)
            .ok_or_else(|| ProverError::Proving("builtin resolver init raced to empty".to_owned()))
    }

    /// Snapshot of currently executing and queued proof jobs.
    #[must_use]
    pub fn stats(&self) -> ProverStats {
        ProverStats {
            jobs_processing: self.jobs_processing.load(Ordering::Relaxed),
            jobs_pending: self.jobs_pending.load(Ordering::Relaxed),
            job_capacity: self.max_concurrent,
        }
    }

    /// Pre-load SRS parameters for each `k` into RAM so subsequent proofs hit
    /// the in-memory cache immediately.
    pub async fn warm_srs(&self, ks: &[u8]) -> Result<(), ProverError> {
        self.params_cache
            .warm(ks)
            .await
            .map_err(|e| ProverError::SrsLoad(format!("Failed to warm SRS: {e}")))
    }

    /// Parses a Compact ZKIR JSON string. Auto-detects v2 vs v3.
    pub fn parse_zkir(json: &str) -> Result<VersionedIr, ProverError> {
        parse_zkir_json(json)
    }

    /// Determines the circuit size (k) for a given ZKIR.
    #[must_use]
    pub fn circuit_k(ir: &VersionedIr) -> u8 {
        ir.k()
    }

    /// Fetches SRS parameters for a given k value (disk/S3) and warms RAM.
    pub async fn fetch_srs(&self, k: u8) -> Result<(), ProverError> {
        self.params_cache
            .inner()
            .fetch_k(k)
            .await
            .map_err(|e| ProverError::SrsLoad(format!("Failed to fetch SRS for k={k}: {e}")))?;
        let _ = self.params_cache.get_prover_params(k).await;
        Ok(())
    }

    /// Generates a proof using a `ProofPreimage` and optional `ProvingKeyMaterial`.
    pub async fn prove_preimage(
        self: &Arc<Self>,
        preimage: &ProofPreimage,
        proving_key_material: Option<ProvingKeyMaterial>,
        binding_input: Option<Fr>,
    ) -> Result<ProofResult, ProverError> {
        let me = Arc::clone(self);
        let preimage = preimage.clone();
        self.dispatch_cpu(move || async move {
            me.prove_preimage_inner(&preimage, proving_key_material, binding_input, true)
                .await
        })
        .await
    }

    /// Inner sync-async work for [`Self::prove_preimage`].
    async fn prove_preimage_inner(
        &self,
        preimage: &ProofPreimage,
        proving_key_material: Option<ProvingKeyMaterial>,
        binding_input: Option<Fr>,
        need_pi_skips: bool,
    ) -> Result<ProofResult, ProverError> {
        let start = Instant::now();

        let (proof, pi_skips) = if let Some(ref km) = proving_key_material {
            prove_cached(
                preimage,
                km,
                binding_input,
                &self.params_cache,
                &self.circuit_cache,
                need_pi_skips,
            )
            .await?
        } else {
            let builtin = self.builtin_resolver()?;
            let km = builtin
                .resolve_key_arc(&preimage.key_location.0)
                .await
                .map_err(|e| ProverError::Proving(format!("resolve key for prove: {e}")))?
                .ok_or_else(|| {
                    ProverError::Proving(format!(
                        "no key material for key_location '{}'",
                        preimage.key_location.0,
                    ))
                })?;
            prove_cached(
                preimage,
                &km,
                binding_input,
                &self.params_cache,
                &self.circuit_cache,
                need_pi_skips,
            )
            .await?
        };

        let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
        let k = 0;

        info!(duration_ms, proof_size = proof.0.len(), "Proof generated");

        Ok(ProofResult {
            proof: proof.0,
            duration_ms,
            k,
            pi_skips,
        })
    }

    /// Generate a proof for a tagged-serialized
    /// `(ProofPreimageVersioned, Option<ProvingKeyMaterial>, Option<Fr>)`
    /// payload — the same wire format the standalone proof-server's
    /// `/prove` endpoint accepts.
    pub async fn prove_serialized_preimage(
        self: &Arc<Self>,
        body: &[u8],
    ) -> Result<Vec<u8>, ProverError> {
        use moonproof_ledger::transient_crypto::proofs::Proof;

        let (ppi_versioned, key_material, binding_input) = tagged_deserialize::<(
            crate::versioned::ProofPreimageVersioned,
            Option<ProvingKeyMaterial>,
            Option<Fr>,
        )>(body)
        .map_err(|e| ProverError::Proving(format!("parse tagged prove payload: {e}")))?;

        let preimage = ppi_versioned.inner().clone();
        // `/prove` only serializes `ProofVersioned::V2(Proof)` — it never
        // returns `pi_skips`, so skip the extra v2 pre-check pass.
        let me = Arc::clone(self);
        let result = self
            .dispatch_cpu(move || async move {
                me.prove_preimage_inner(&preimage, key_material, binding_input, false)
                    .await
            })
            .await?;
        let proof_versioned = crate::versioned::ProofVersioned::V2(Proof(result.proof));
        let mut out = Vec::with_capacity(8192);
        tagged_serialize(&proof_versioned, &mut out)
            .map_err(|e| ProverError::Proving(format!("serialize ProofVersioned: {e}")))?;
        Ok(out)
    }

    /// Check a tagged-serialized
    /// `(ProofPreimageVersioned, Option<WrappedIr>)` payload.
    pub async fn check_serialized_preimage(
        &self,
        body: &[u8],
    ) -> Result<Vec<Option<String>>, ProverError> {
        Ok(self
            .check_payload(body)
            .await?
            .into_iter()
            .map(|opt| opt.map(|n| n.to_string()))
            .collect())
    }

    /// A `POST /check` request body, checked using cached built-in keys and
    /// cached parsed ZKIR. Offloads constraint checking off Tokio I/O threads
    /// on native targets.
    pub async fn check_payload(&self, body: &[u8]) -> Result<Vec<Option<usize>>, ProverError> {
        use crate::WrappedIr;

        let (ppi_versioned, wrapped_ir) = tagged_deserialize::<(
            crate::versioned::ProofPreimageVersioned,
            Option<WrappedIr>,
        )>(body)
        .map_err(|e| ProverError::Deserialization(format!("check payload: {e}")))?;
        let crate::versioned::ProofPreimageVersioned::V2(preimage) = ppi_versioned;
        let ir = match wrapped_ir {
            Some(WrappedIr(ir_bytes)) => self.circuit_cache.get_or_parse_ir(&ir_bytes)?,
            None => self.builtin_ir(&preimage).await?,
        };
        #[cfg(not(target_arch = "wasm32"))]
        {
            tokio::task::spawn_blocking(move || Self::check_preimage(&ir, &preimage))
                .await
                .map_err(|e| ProverError::Proving(format!("check task join: {e}")))?
        }
        #[cfg(target_arch = "wasm32")]
        {
            Self::check_preimage(&ir, &preimage)
        }
    }

    async fn builtin_ir(&self, preimage: &ProofPreimage) -> Result<Arc<VersionedIr>, ProverError> {
        let builtin = self.builtin_resolver()?;
        let material = builtin
            .resolve_key_arc(&preimage.key_location.0)
            .await
            .map_err(|e| ProverError::Proving(format!("resolve key for check: {e}")))?
            .ok_or_else(|| {
                ProverError::Proving(format!(
                    "no IR / key material for key_location '{}'",
                    preimage.key_location.0
                ))
            })?;
        self.circuit_cache.get_or_parse_ir(&material.ir_source)
    }

    /// Like [`Self::prove_serialized_preimage`] with out-of-band key material.
    pub async fn prove_with_optional_keys(
        self: &Arc<Self>,
        body: &[u8],
        key_material: Option<ProvingKeyMaterial>,
        binding_input: Option<Fr>,
    ) -> Result<Vec<u8>, ProverError> {
        use moonproof_ledger::transient_crypto::proofs::Proof;

        let ppi_versioned: crate::versioned::ProofPreimageVersioned = tagged_deserialize(body)
            .map_err(|e| ProverError::Proving(format!("parse preimage: {e}")))?;
        let preimage = ppi_versioned.inner().clone();
        let me = Arc::clone(self);
        let result = self
            .dispatch_cpu(move || async move {
                me.prove_preimage_inner(&preimage, key_material, binding_input, false)
                    .await
            })
            .await?;
        let proof_versioned = crate::versioned::ProofVersioned::V2(Proof(result.proof));
        let mut out = Vec::with_capacity(8192);
        tagged_serialize(&proof_versioned, &mut out)
            .map_err(|e| ProverError::Proving(format!("serialize ProofVersioned: {e}")))?;
        Ok(out)
    }

    /// Like [`Self::check_serialized_preimage`] with out-of-band key material.
    pub async fn check_with_optional_keys(
        &self,
        body: &[u8],
        key_material: Option<ProvingKeyMaterial>,
    ) -> Result<Vec<Option<String>>, ProverError> {
        let ppi_versioned: crate::versioned::ProofPreimageVersioned = tagged_deserialize(body)
            .map_err(|e| ProverError::Proving(format!("parse preimage: {e}")))?;
        let preimage = ppi_versioned.inner();

        let ir = if let Some(km) = &key_material {
            self.circuit_cache.get_or_parse_ir(&km.ir_source)?
        } else {
            self.builtin_ir(preimage).await?
        };
        let inputs = Self::check_preimage(&ir, preimage)?;
        Ok(inputs
            .into_iter()
            .map(|opt| opt.map(|n| n.to_string()))
            .collect())
    }

    /// Convenience: parse ZKIR JSON, compute k, and check the circuit.
    pub fn parse_and_analyze(json: &str) -> Result<(VersionedIr, u8), ProverError> {
        let ir = Self::parse_zkir(json)?;
        let k = Self::circuit_k(&ir);
        debug!(k, "Circuit analyzed");
        Ok((ir, k))
    }

    /// Check a proof preimage without generating a proof.
    pub fn check_preimage(
        ir: &VersionedIr,
        preimage: &ProofPreimage,
    ) -> Result<Vec<Option<usize>>, ProverError> {
        ir.check(preimage)
    }

    /// Prove an entire `Transaction` in one call.
    pub async fn prove_tx(
        self: &Arc<Self>,
        tx: Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
        contract_keys: HashMap<String, ProvingKeyMaterial>,
    ) -> Result<ProveTxOutput, ProverError> {
        let me = Arc::clone(self);
        self.dispatch_cpu(move || async move {
            let provider =
                EngineProvingProvider::new(Arc::clone(&me)).with_contract_keys(contract_keys);
            let cost_model = INITIAL_TRANSACTION_COST_MODEL.runtime_cost_model.clone();
            tx.prove(provider, &cost_model)
                .await
                .map_err(|e| ProverError::Proving(format!("prove-tx: {e}")))
        })
        .await
    }

    /// Bytes-in / bytes-out wrapper around [`Self::prove_tx`].
    pub async fn prove_tx_bytes(self: &Arc<Self>, payload: &[u8]) -> Result<Vec<u8>, ProverError> {
        let (tx, contract_keys): ProveTxInput = tagged_deserialize(payload)
            .map_err(|e| ProverError::Deserialization(format!("decode prove-tx payload: {e}")))?;
        let proven = self.prove_tx(tx, contract_keys).await?;
        let mut out = Vec::with_capacity(16 * 1024);
        tagged_serialize(&proven, &mut out)
            .map_err(|e| ProverError::Proving(format!("serialize proven tx: {e}")))?;
        Ok(out)
    }

    /// Run a CPU-heavy async operation on the rayon pool, with a
    /// semaphore-bounded concurrency limit and live queue/processing counters.
    async fn dispatch_cpu<F, Fut, T>(self: &Arc<Self>, f: F) -> Result<T, ProverError>
    where
        F: FnOnce() -> Fut + Send + 'static,
        Fut: std::future::Future<Output = Result<T, ProverError>>,
        T: Send + 'static,
    {
        struct PendingGuard(Arc<AtomicUsize>);
        impl Drop for PendingGuard {
            fn drop(&mut self) {
                self.0.fetch_sub(1, Ordering::Relaxed);
            }
        }
        struct ActiveGuard(Arc<AtomicUsize>);
        impl Drop for ActiveGuard {
            fn drop(&mut self) {
                self.0.fetch_sub(1, Ordering::Relaxed);
            }
        }

        self.jobs_pending.fetch_add(1, Ordering::Relaxed);
        let pending_guard = PendingGuard(Arc::clone(&self.jobs_pending));

        let permit = self
            .proving_semaphore
            .clone()
            .acquire_owned()
            .await
            .map_err(|e| ProverError::Proving(format!("acquire prover slot: {e}")))?;
        drop(pending_guard);

        let jobs_processing = Arc::clone(&self.jobs_processing);
        jobs_processing.fetch_add(1, Ordering::Relaxed);
        let active_guard = ActiveGuard(jobs_processing);

        let handle = tokio::runtime::Handle::current();
        let (tx, rx) = tokio::sync::oneshot::channel::<Result<T, ProverError>>();
        rayon::spawn(move || {
            let _permit = permit;
            let _active = active_guard;
            let result = handle.block_on(f());
            let _ = tx.send(result);
        });
        rx.await
            .map_err(|e| ProverError::Proving(format!("rayon channel closed before send: {e}")))?
    }
}