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
//! Built-in key resolvers for `ZSwap` and Dust circuits.
//!
//! Matches the official proof server's key resolution behavior:
//! - `ZSwap` keys: `midnight/zswap/spend`, `midnight/zswap/output`, `midnight/zswap/sign`
//! - Dust keys: `midnight/dust/spend`
//!
//! Key files are loaded from `MidnightDataProvider` (downloaded from S3 on demand)
//! and cached in memory per built-in location so subsequent proofs incur zero disk
//! I/O and zero repeated SHA-256 verification.

use std::io::Read;
use std::sync::Arc;

use moonproof_ledger::base_crypto::data_provider::{FetchMode, MidnightDataProvider, OutputMode};
use moonproof_ledger::ledger::dust::DUST_EXPECTED_FILES;
use moonproof_ledger::transient_crypto::proofs::{KeyLocation, ProvingKeyMaterial, Resolver};
use moonproof_ledger::zswap::ZSWAP_EXPECTED_FILES;
use tokio::sync::OnceCell;
use tracing::debug;

const BUILTIN_SLOTS: usize = 4;

/// Resolver that handles built-in `ZSwap` and Dust key locations with
/// single-flight in-memory caching.
pub struct BuiltinResolver {
    zswap_provider: MidnightDataProvider,
    dust_provider: MidnightDataProvider,
    /// Fixed 4-slot table indexed by slot id:
    /// `0 = zswap/spend`, `1 = zswap/output`, `2 = zswap/sign`, `3 = dust/spend`.
    roots: [Option<String>; BUILTIN_SLOTS],
    cache: [OnceCell<Arc<ProvingKeyMaterial>>; BUILTIN_SLOTS],
}

fn slot_for_location(key_location: &str) -> Option<usize> {
    match key_location {
        "midnight/zswap/spend" => Some(0),
        "midnight/zswap/output" => Some(1),
        "midnight/zswap/sign" => Some(2),
        "midnight/dust/spend" => Some(3),
        _ => None,
    }
}

/// The artifact root for `circuit` within `expected`, e.g. `spend` in
/// `DUST_EXPECTED_FILES` → `dust/<v>/spend`.
fn artifact_root(expected: &[(&'static str, [u8; 32], &str)], circuit: &str) -> Option<String> {
    let suffix = format!("/{circuit}.prover");
    expected
        .iter()
        .find_map(|(path, _, _)| {
            path.strip_suffix(".prover")
                .filter(|_| path.ends_with(&suffix))
        })
        .map(str::to_owned)
}

impl BuiltinResolver {
    pub fn new() -> std::io::Result<Self> {
        let zswap_provider = MidnightDataProvider::new(
            FetchMode::OnDemand,
            OutputMode::Log,
            ZSWAP_EXPECTED_FILES.to_vec(),
        )
        .map_err(|e| std::io::Error::other(format!("Failed to init ZSwap data provider: {e}")))?;

        let dust_provider = MidnightDataProvider::new(
            FetchMode::OnDemand,
            OutputMode::Log,
            DUST_EXPECTED_FILES.to_vec(),
        )
        .map_err(|e| std::io::Error::other(format!("Failed to init Dust data provider: {e}")))?;

        let roots = [
            artifact_root(ZSWAP_EXPECTED_FILES, "spend"),
            artifact_root(ZSWAP_EXPECTED_FILES, "output"),
            artifact_root(ZSWAP_EXPECTED_FILES, "sign"),
            artifact_root(DUST_EXPECTED_FILES, "spend"),
        ];

        Ok(Self {
            zswap_provider,
            dust_provider,
            roots,
            cache: std::array::from_fn(|_| OnceCell::new()),
        })
    }

    /// Resolve a built-in key location, returning a shared `Arc` from the
    /// in-memory cache without cloning the multi-MB key buffers.
    pub async fn resolve_key_arc(
        &self,
        key_location: &str,
    ) -> std::io::Result<Option<Arc<ProvingKeyMaterial>>> {
        let Some(slot) = slot_for_location(key_location) else {
            return Ok(None);
        };
        let Some(file_root) = self.roots[slot].as_deref() else {
            return Ok(None);
        };
        if let Some(cached) = self.cache[slot].get() {
            return Ok(Some(Arc::clone(cached)));
        }
        let provider = if slot == 3 {
            &self.dust_provider
        } else {
            &self.zswap_provider
        };
        let loaded = self.cache[slot]
            .get_or_try_init(|| async move {
                debug!(key_location, file_root, "Resolving built-in key");
                let mat = Self::resolve_builtin(provider, file_root).await?;
                Ok::<_, std::io::Error>(Arc::new(mat))
            })
            .await?;
        Ok(Some(Arc::clone(loaded)))
    }

    async fn resolve_builtin(
        provider: &MidnightDataProvider,
        file_root: &str,
    ) -> std::io::Result<ProvingKeyMaterial> {
        fn read_to_vec(mut reader: impl Read) -> std::io::Result<Vec<u8>> {
            let mut buf = Vec::new();
            reader.read_to_end(&mut buf)?;
            Ok(buf)
        }

        let prover_key = read_to_vec(
            provider
                .get_file(
                    &format!("{file_root}.prover"),
                    &format!("failed to find built-in prover key {file_root}.prover"),
                )
                .await?,
        )?;

        let verifier_key = read_to_vec(
            provider
                .get_file(
                    &format!("{file_root}.verifier"),
                    &format!("failed to find built-in verifier key {file_root}.verifier"),
                )
                .await?,
        )?;

        let ir_source = read_to_vec(
            provider
                .get_file(
                    &format!("{file_root}.bzkir"),
                    &format!("failed to find built-in IR {file_root}.bzkir"),
                )
                .await?,
        )?;

        debug!(
            file_root,
            prover_key_len = prover_key.len(),
            verifier_key_len = verifier_key.len(),
            ir_source_len = ir_source.len(),
            "Resolved built-in key material"
        );

        Ok(ProvingKeyMaterial {
            prover_key,
            verifier_key,
            ir_source,
        })
    }
}

impl Resolver for BuiltinResolver {
    async fn resolve_key(&self, key: KeyLocation) -> std::io::Result<Option<ProvingKeyMaterial>> {
        Ok(self
            .resolve_key_arc(&key.0)
            .await?
            .map(|arc| (*arc).clone()))
    }
}