moonproof-prover 0.2.1

Core ZK proof engine for Moonproof, dispatching across the Midnight ZKIR v2 + v3 pipelines (mirrors midnight-ledger's proof-server)
Documentation
//! Bounded in-memory LRU caches for parsed ZKIR and initialized proving/verifying keys.
//!
//! Why this exists alongside `midnight-transient-crypto`'s internal `PK_CACHE`:
//! 1. Upstream's `PK_CACHE` holds only 5 entries, so multi-circuit contracts
//!    (e.g., 14–49 circuits across 3 contracts) thrash continuously and
//!    re-decompress 22–43 MiB Halo2 proving keys on every 6th circuit.
//! 2. Upstream's `ProofPreimage::prove` re-deserializes `IrSource`,
//!    `VerifierKey` (calling `force_init()`), and `ProverKey` on every call.
//! 3. Caching the parsed `VersionedIr` also makes repeated `/check` calls
//!    skip tagged ZKIR deserialization altogether.

use std::collections::{HashMap, VecDeque};
#[cfg(not(feature = "ledger8"))]
use std::io::Cursor;
use std::sync::Arc;

#[cfg(not(feature = "ledger8"))]
use moonproof_ledger::transient_crypto::proofs::ProvingKeyMaterial;
use parking_lot::Mutex;
use sha2::{Digest, Sha256};

#[cfg(not(feature = "ledger8"))]
use moonproof_ledger::serialize::{tagged_deserialize, Deserializable, Serializable};
#[cfg(not(feature = "ledger8"))]
use moonproof_ledger::transient_crypto::proofs::{ProverKey, VerifierKey, Zkir};
#[cfg(not(feature = "ledger8"))]
use moonproof_ledger::zkir::{IrMinorVersion, IrSource as IrSourceV2};
#[cfg(not(feature = "ledger8"))]
use moonproof_ledger::zkir_v3::IrSource as IrSourceV3;

use crate::error::ProverError;
use crate::versioned_ir::{parse_zkir_tagged, VersionedIr};

/// Default capacity of the parsed circuit & initialized-key LRU cache.
pub const DEFAULT_CIRCUIT_CACHE_CAPACITY: usize = 32;

/// Default capacity of the parsed-IR-only cache (used by `/check`).
pub const DEFAULT_IR_CACHE_CAPACITY: usize = 64;

/// A fully parsed and initialized ZKIR v3 circuit ready for immediate proving
/// and self-verification with zero deserialization or key decompression.
#[cfg(not(feature = "ledger8"))]
pub struct CachedV3Circuit {
    pub ir: IrSourceV3,
    pub pk: ProverKey<IrSourceV3>,
    pub vk: VerifierKey,
    pub k: u8,
}

/// A fully parsed and initialized ZKIR v2 (V0/V1 legacy or V2) circuit ready
/// for direct proving without `LocalProvingProvider`'s per-call `ProverKey` /
/// SRS re-serialization bridge.
#[cfg(not(feature = "ledger8"))]
pub enum CachedV2Circuit {
    V1 {
        ir: IrSourceV2,
        pk: moonproof_ledger::transient_crypto_v1::proofs::ProverKey<IrSourceV2>,
    },
    V2 {
        ir: IrSourceV2,
        pk: ProverKey<IrSourceV2>,
        vk: VerifierKey,
        k: u8,
    },
}

/// Minimal bounded LRU map backed by `HashMap` + `VecDeque` (no extra crate).
struct BoundedLru<K, V> {
    capacity: usize,
    entries: HashMap<K, V>,
    order: VecDeque<K>,
}

impl<K: Eq + std::hash::Hash + Clone, V: Clone> BoundedLru<K, V> {
    fn new(capacity: usize) -> Self {
        let cap = capacity.max(1);
        Self {
            capacity: cap,
            entries: HashMap::with_capacity(cap),
            order: VecDeque::with_capacity(cap),
        }
    }

    fn get(&mut self, key: &K) -> Option<V> {
        let val = self.entries.get(key)?.clone();
        if let Some(pos) = self.order.iter().position(|k| k == key) {
            self.order.remove(pos);
            self.order.push_back(key.clone());
        }
        Some(val)
    }

    fn insert(&mut self, key: K, value: V) {
        if let Some(pos) = self.order.iter().position(|k| k == &key) {
            self.order.remove(pos);
        } else if self.entries.len() >= self.capacity {
            if let Some(oldest) = self.order.pop_front() {
                self.entries.remove(&oldest);
            }
        }
        self.order.push_back(key.clone());
        self.entries.insert(key, value);
    }
}

/// Thread-safe cache for parsed IRs and initialized ZKIR v2/v3 circuit bundles.
pub struct ParsedCircuitCache {
    ir_cache: Mutex<BoundedLru<[u8; 32], Arc<VersionedIr>>>,
    #[cfg(not(feature = "ledger8"))]
    v2_circuits: Mutex<BoundedLru<[u8; 32], Arc<CachedV2Circuit>>>,
    #[cfg(not(feature = "ledger8"))]
    v3_circuits: Mutex<BoundedLru<[u8; 32], Arc<CachedV3Circuit>>>,
}

impl std::fmt::Debug for ParsedCircuitCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let ir_len = self.ir_cache.lock().entries.len();
        #[cfg(not(feature = "ledger8"))]
        let v2_len = self.v2_circuits.lock().entries.len();
        #[cfg(feature = "ledger8")]
        let v2_len = 0usize;
        #[cfg(not(feature = "ledger8"))]
        let v3_len = self.v3_circuits.lock().entries.len();
        #[cfg(feature = "ledger8")]
        let v3_len = 0usize;
        f.debug_struct("ParsedCircuitCache")
            .field("ir_entries", &ir_len)
            .field("v2_circuit_entries", &v2_len)
            .field("v3_circuit_entries", &v3_len)
            .finish()
    }
}

impl Default for ParsedCircuitCache {
    fn default() -> Self {
        Self::new(DEFAULT_CIRCUIT_CACHE_CAPACITY)
    }
}

impl ParsedCircuitCache {
    /// Construct with the given circuit cache capacity (or env override
    /// `MOONPROOF_PROVER_KEY_CACHE_SIZE`).
    #[must_use]
    pub fn new(circuit_capacity: usize) -> Self {
        let cap = std::env::var("MOONPROOF_PROVER_KEY_CACHE_SIZE")
            .ok()
            .and_then(|s| s.parse::<usize>().ok())
            .filter(|&n| n > 0)
            .unwrap_or(circuit_capacity)
            .max(1);
        Self {
            ir_cache: Mutex::new(BoundedLru::new(DEFAULT_IR_CACHE_CAPACITY.max(cap))),
            #[cfg(not(feature = "ledger8"))]
            v2_circuits: Mutex::new(BoundedLru::new(cap)),
            #[cfg(not(feature = "ledger8"))]
            v3_circuits: Mutex::new(BoundedLru::new(cap)),
        }
    }

    /// Return a cached parsed [`VersionedIr`] for tagged binary `ir_bytes`,
    /// parsing and inserting on miss.
    pub fn get_or_parse_ir(&self, ir_bytes: &[u8]) -> Result<Arc<VersionedIr>, ProverError> {
        let digest: [u8; 32] = Sha256::digest(ir_bytes).into();
        if let Some(hit) = self.ir_cache.lock().get(&digest) {
            return Ok(hit);
        }
        let parsed = Arc::new(parse_zkir_tagged(ir_bytes)?);
        self.ir_cache.lock().insert(digest, Arc::clone(&parsed));
        Ok(parsed)
    }

    /// Return a cached, fully initialized [`CachedV2Circuit`] for `material`,
    /// converting and initializing the v1 or v2 prover key once on miss.
    #[cfg(not(feature = "ledger8"))]
    pub fn get_or_init_v2(
        &self,
        material: &ProvingKeyMaterial,
    ) -> Result<Arc<CachedV2Circuit>, ProverError> {
        let digest = material_digest(material);
        if let Some(hit) = self.v2_circuits.lock().get(&digest) {
            return Ok(hit);
        }
        let ir = IrSourceV2::load_from_tagged(Cursor::new(&material.ir_source[..]))
            .map_err(|e| ProverError::ZkirParse(format!("v2 IR decode: {e}")))?;
        let current_pk =
            IrSourceV2::load_prover_key_from_tagged(Cursor::new(&material.prover_key[..]))
                .map_err(|e| ProverError::Proving(format!("v2 prover key decode: {e}")))?;

        let entry = match ir.version {
            IrMinorVersion::V0 | IrMinorVersion::V1 => {
                let mut pk_buf = Vec::with_capacity(material.prover_key.len());
                Serializable::serialize(&current_pk, &mut pk_buf)
                    .map_err(|e| ProverError::Proving(format!("v1 pk bridge serialize: {e}")))?;
                let pk: moonproof_ledger::transient_crypto_v1::proofs::ProverKey<IrSourceV2> =
                    Deserializable::deserialize(&mut &pk_buf[..], 0).map_err(|e| {
                        ProverError::Proving(format!("v1 pk bridge deserialize: {e}"))
                    })?;
                let _ = pk
                    .init()
                    .map_err(|e| ProverError::Proving(format!("v1 prover key init: {e}")))?;
                Arc::new(CachedV2Circuit::V1 { ir, pk })
            }
            _ => {
                let inner_pk = current_pk
                    .init()
                    .map_err(|e| ProverError::Proving(format!("v2 prover key init: {e}")))?;
                let k = inner_pk.k();
                let vk = tagged_deserialize::<VerifierKey>(&mut &material.verifier_key[..])
                    .map_err(|e| ProverError::Proving(format!("v2 verifier key decode: {e}")))?;
                vk.init()
                    .map_err(|e| ProverError::Proving(format!("v2 verifier key init: {e}")))?;
                Arc::new(CachedV2Circuit::V2 {
                    ir,
                    pk: current_pk,
                    vk,
                    k,
                })
            }
        };
        self.v2_circuits.lock().insert(digest, Arc::clone(&entry));
        Ok(entry)
    }

    /// Return a cached, fully initialized [`CachedV3Circuit`] for `material`,
    /// decoding and calling `pk.init()` + `vk.force_init()` once on miss.
    #[cfg(not(feature = "ledger8"))]
    pub fn get_or_init_v3(
        &self,
        material: &ProvingKeyMaterial,
    ) -> Result<Arc<CachedV3Circuit>, ProverError> {
        let digest = material_digest(material);
        if let Some(hit) = self.v3_circuits.lock().get(&digest) {
            return Ok(hit);
        }
        let ir = IrSourceV3::load_ir_from_tagged(Cursor::new(&material.ir_source[..]))
            .map_err(|e| ProverError::ZkirParse(format!("v3 IR decode: {e}")))?;
        let vk = tagged_deserialize::<VerifierKey>(&mut &material.verifier_key[..])
            .map_err(|e| ProverError::Proving(format!("v3 verifier key decode: {e}")))?;
        let pk = IrSourceV3::load_prover_key_from_tagged(Cursor::new(&material.prover_key[..]))
            .map_err(|e| ProverError::Proving(format!("v3 prover key decode: {e}")))?;
        // Eagerly initialize both keys once so every subsequent proof skips
        // curve-point decompression and polynomial deserialization completely.
        let inner_pk = pk
            .init()
            .map_err(|e| ProverError::Proving(format!("v3 prover key init: {e}")))?;
        let k = inner_pk.k();
        vk.init()
            .map_err(|e| ProverError::Proving(format!("v3 verifier key init: {e}")))?;
        let entry = Arc::new(CachedV3Circuit { ir, pk, vk, k });
        self.v3_circuits.lock().insert(digest, Arc::clone(&entry));
        Ok(entry)
    }
}

/// Fast content fingerprint for `ProvingKeyMaterial` cache lookups.
///
/// Always hashes the entire `ir_source` and `verifier_key` (which are small and
/// cryptographically bind the circuit) plus `prover_key.len()`. For small prover
/// keys (<= 64 KiB) hashes the entire `prover_key`; for multi-megabyte Halo2
/// keys (2–43 MiB) hashes 16 evenly-spaced 256-byte windows (including start and
/// end) so cache lookups stay ~15 µs instead of spending ~50–100 ms hashing
/// 43 MiB of already-verified key material on every proof.
#[cfg(not(feature = "ledger8"))]
fn material_digest(material: &ProvingKeyMaterial) -> [u8; 32] {
    const FULL_HASH_THRESHOLD: usize = 64 * 1024;
    const SAMPLE_WINDOWS: usize = 16;
    const WINDOW_BYTES: usize = 256;

    let mut h = Sha256::new();
    h.update((material.ir_source.len() as u64).to_le_bytes());
    h.update(&material.ir_source);
    h.update((material.verifier_key.len() as u64).to_le_bytes());
    h.update(&material.verifier_key);
    let pk = &material.prover_key;
    h.update((pk.len() as u64).to_le_bytes());
    if pk.len() <= FULL_HASH_THRESHOLD {
        h.update(pk);
    } else {
        let max_start = pk.len() - WINDOW_BYTES;
        for i in 0..SAMPLE_WINDOWS {
            let offset = (max_start * i) / (SAMPLE_WINDOWS - 1);
            h.update(&pk[offset..offset + WINDOW_BYTES]);
        }
    }
    h.finalize().into()
}