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};
pub type ProveTxInput = (
Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
HashMap<String, ProvingKeyMaterial>,
);
pub type ProveTxOutput = Transaction<Signature, ProofMarker, PedersenRandomness, InMemoryDB>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProverStats {
pub jobs_processing: usize,
pub jobs_pending: usize,
pub job_capacity: usize,
}
#[derive(Debug, Clone)]
pub struct ProofResult {
pub proof: Vec<u8>,
pub duration_ms: u64,
pub k: u8,
pub pi_skips: Vec<Option<usize>>,
}
pub struct ProverEngine {
params_cache: Arc<CachingParamsProvider>,
builtin: Arc<OnceLock<Arc<BuiltinResolver>>>,
circuit_cache: Arc<ParsedCircuitCache>,
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()
}
}
#[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 {
pub fn new(params: Arc<MidnightDataProvider>) -> Self {
Self::with_concurrency(params, num_cpus::get().max(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)),
}
}
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)))
}
pub fn params(&self) -> &MidnightDataProvider {
self.params_cache.inner()
}
#[inline]
pub(crate) fn params_cache(&self) -> &CachingParamsProvider {
&self.params_cache
}
#[inline]
pub(crate) fn circuit_cache(&self) -> &ParsedCircuitCache {
&self.circuit_cache
}
#[inline]
pub(crate) fn builtin_cell(&self) -> Arc<OnceLock<Arc<BuiltinResolver>>> {
Arc::clone(&self.builtin)
}
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()))
}
#[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,
}
}
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}")))
}
pub fn parse_zkir(json: &str) -> Result<VersionedIr, ProverError> {
parse_zkir_json(json)
}
#[must_use]
pub fn circuit_k(ir: &VersionedIr) -> u8 {
ir.k()
}
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(())
}
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
}
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,
})
}
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();
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)
}
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())
}
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)
}
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)
}
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())
}
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))
}
pub fn check_preimage(
ir: &VersionedIr,
preimage: &ProofPreimage,
) -> Result<Vec<Option<usize>>, ProverError> {
ir.check(preimage)
}
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
}
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)
}
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}")))?
}
}