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
//! The resolver a proving provider owns.
//!
//! Caller-supplied contract-circuit keys first, then the built-in
//! `ZSwap` / Dust keys. Shares the cached [`BuiltinResolver`] cell with
//! [`ProverEngine`](crate::ProverEngine) when attached so built-in keys are
//! read from disk at most once per engine lifetime.

use std::collections::HashMap;
use std::io;
use std::sync::{Arc, OnceLock};

use moonproof_ledger::transient_crypto::proofs::{KeyLocation, ProvingKeyMaterial, Resolver};

use crate::resolver::BuiltinResolver;

/// Contract keys first, built-ins second.
#[derive(Clone, Default)]
pub struct ContractKeyResolver {
    contract_keys: Arc<HashMap<String, ProvingKeyMaterial>>,
    builtin: Arc<OnceLock<Arc<BuiltinResolver>>>,
}

impl ContractKeyResolver {
    #[must_use]
    pub fn new(contract_keys: Arc<HashMap<String, ProvingKeyMaterial>>) -> Self {
        Self {
            contract_keys,
            builtin: Arc::new(OnceLock::new()),
        }
    }

    /// Construct sharing a pre-existing [`BuiltinResolver`] cell (e.g. owned by
    /// [`ProverEngine`](crate::ProverEngine)) so built-in keys stay warm across
    /// every transaction proved by that engine.
    #[must_use]
    pub(crate) fn with_shared_builtin(
        contract_keys: Arc<HashMap<String, ProvingKeyMaterial>>,
        builtin: Arc<OnceLock<Arc<BuiltinResolver>>>,
    ) -> Self {
        Self {
            contract_keys,
            builtin,
        }
    }

    /// The caller-supplied key for `key_location`, ignoring built-ins.
    #[must_use]
    pub fn contract_key(&self, key_location: &str) -> Option<ProvingKeyMaterial> {
        self.contract_keys.get(key_location).cloned()
    }

    /// Borrow a caller-supplied contract key without cloning.
    #[must_use]
    pub fn contract_key_ref(&self, key_location: &str) -> Option<&ProvingKeyMaterial> {
        self.contract_keys.get(key_location)
    }

    #[must_use]
    pub fn contract_key_count(&self) -> usize {
        self.contract_keys.len()
    }

    fn builtin(&self) -> io::Result<&Arc<BuiltinResolver>> {
        if let Some(b) = self.builtin.get() {
            return Ok(b);
        }
        let built = Arc::new(BuiltinResolver::new()?);
        let _ = self.builtin.set(built);
        self.builtin
            .get()
            .ok_or_else(|| io::Error::other("builtin resolver init raced to an empty cell"))
    }
}

impl std::fmt::Debug for ContractKeyResolver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ContractKeyResolver")
            .field("contract_key_count", &self.contract_keys.len())
            .field("builtin_initialized", &self.builtin.get().is_some())
            .finish()
    }
}

impl Resolver for ContractKeyResolver {
    async fn resolve_key(&self, key: KeyLocation) -> io::Result<Option<ProvingKeyMaterial>> {
        if let Some(material) = self.contract_keys.get(key.0.as_ref()) {
            return Ok(Some(material.clone()));
        }
        self.builtin()?.resolve_key(key).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn contract_keys_are_consulted_without_touching_the_builtins() {
        let r = ContractKeyResolver::default();
        assert!(r.contract_key("counter/increment").is_none());
        assert_eq!(r.contract_key_count(), 0);
        assert!(r.builtin.get().is_none());
    }
}