moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! ZK-config provider trait — port of
//! `@midnight-ntwrk/midnight-js-types/src/zk-config-provider.ts`.
//!
//! Retrieves the ZKIR + prover key + verifier key produced by
//! `compactc` for a given circuit id. Implementations decide where the
//! artifacts live (filesystem, HTTP, embedded in a binary, etc.); the
//! runtime only sees the trait.

use moonproof_macros::async_trait;

use crate::error::Result;
use crate::types::{CircuitId, ProverKey, VerifierKey, ZkConfig, Zkir};

/// Rust port of TS `ZKConfigProvider<K>`.
///
/// The TS abstract class exposes four primitive accessors plus
/// convenience aggregators (`getVerifierKeys`, `get`). The Rust trait
/// matches — concrete `get_verifier_keys` + `get` default
/// implementations dispatch to the primitives so implementors only
/// override them if they have a cheaper batch path.
#[async_trait]
pub trait ZkConfigProvider: Send + Sync + std::fmt::Debug {
    /// Retrieves the ZKIR produced by `compactc` for `circuit_id`.
    async fn get_zkir(&self, circuit_id: &CircuitId) -> Result<Zkir>;

    /// Retrieves the prover key for `circuit_id`.
    async fn get_prover_key(&self, circuit_id: &CircuitId) -> Result<ProverKey>;

    /// Retrieves the verifier key for `circuit_id`.
    async fn get_verifier_key(&self, circuit_id: &CircuitId) -> Result<VerifierKey>;

    /// Retrieves verifier keys for a batch of circuit ids concurrently.
    /// Preserves input order and pairs each result with its id
    /// (matching TS `getVerifierKeys` which returns
    /// `[K, VerifierKey][]`).
    async fn get_verifier_keys(
        &self,
        circuit_ids: &[CircuitId],
    ) -> Result<Vec<(CircuitId, VerifierKey)>> {
        futures::future::try_join_all(circuit_ids.iter().map(|id| async move {
            let vk = self.get_verifier_key(id).await?;
            Ok((id.clone(), vk))
        }))
        .await
    }

    /// Retrieves the full [`ZkConfig`] bundle for `circuit_id`.
    /// Default impl fans out to the three primitives concurrently.
    async fn get(&self, circuit_id: &CircuitId) -> Result<ZkConfig> {
        let (prover_key, verifier_key, zkir) = futures::try_join!(
            self.get_prover_key(circuit_id),
            self.get_verifier_key(circuit_id),
            self.get_zkir(circuit_id),
        )?;
        Ok(ZkConfig {
            circuit_id: circuit_id.clone(),
            prover_key,
            verifier_key,
            zkir,
        })
    }
}

#[async_trait]
impl<T: ZkConfigProvider + ?Sized> ZkConfigProvider for std::sync::Arc<T> {
    async fn get_zkir(&self, circuit_id: &CircuitId) -> Result<Zkir> {
        (**self).get_zkir(circuit_id).await
    }
    async fn get_prover_key(&self, circuit_id: &CircuitId) -> Result<ProverKey> {
        (**self).get_prover_key(circuit_id).await
    }
    async fn get_verifier_key(&self, circuit_id: &CircuitId) -> Result<VerifierKey> {
        (**self).get_verifier_key(circuit_id).await
    }
    async fn get_verifier_keys(
        &self,
        circuit_ids: &[CircuitId],
    ) -> Result<Vec<(CircuitId, VerifierKey)>> {
        (**self).get_verifier_keys(circuit_ids).await
    }
    async fn get(&self, circuit_id: &CircuitId) -> Result<ZkConfig> {
        (**self).get(circuit_id).await
    }
}

#[async_trait]
impl<T: ZkConfigProvider + ?Sized> ZkConfigProvider for Box<T> {
    async fn get_zkir(&self, circuit_id: &CircuitId) -> Result<Zkir> {
        (**self).get_zkir(circuit_id).await
    }
    async fn get_prover_key(&self, circuit_id: &CircuitId) -> Result<ProverKey> {
        (**self).get_prover_key(circuit_id).await
    }
    async fn get_verifier_key(&self, circuit_id: &CircuitId) -> Result<VerifierKey> {
        (**self).get_verifier_key(circuit_id).await
    }
    async fn get_verifier_keys(
        &self,
        circuit_ids: &[CircuitId],
    ) -> Result<Vec<(CircuitId, VerifierKey)>> {
        (**self).get_verifier_keys(circuit_ids).await
    }
    async fn get(&self, circuit_id: &CircuitId) -> Result<ZkConfig> {
        (**self).get(circuit_id).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ContractRuntimeError;
    use async_trait::async_trait;
    use std::collections::HashMap;
    use std::sync::Mutex;

    /// (prover, verifier, zkir) byte triple for a circuit — factored
    /// out so the `HashMap` type below stays within clippy's complexity
    /// threshold.
    type CircuitArtifacts = (Vec<u8>, Vec<u8>, Vec<u8>);

    #[derive(Debug, Default)]
    struct StaticProvider {
        /// `circuit_id` -> (prover, verifier, zkir)
        entries: HashMap<String, CircuitArtifacts>,
        /// Number of calls per primitive — used to assert that the
        /// default aggregators fan out correctly.
        call_log: Mutex<Vec<&'static str>>,
    }

    impl StaticProvider {
        fn with(id: &str, prover: Vec<u8>, verifier: Vec<u8>, zkir: Vec<u8>) -> Self {
            let mut s = Self::default();
            s.entries.insert(id.to_owned(), (prover, verifier, zkir));
            s
        }
    }

    #[async_trait]
    impl ZkConfigProvider for StaticProvider {
        async fn get_zkir(&self, circuit_id: &CircuitId) -> Result<Zkir> {
            self.call_log.lock().unwrap().push("zkir");
            self.entries
                .get(circuit_id.as_str())
                .map(|(_, _, z)| Zkir::new(z.clone()))
                .ok_or_else(|| ContractRuntimeError::NotFound(circuit_id.as_str().to_owned()))
        }
        async fn get_prover_key(&self, circuit_id: &CircuitId) -> Result<ProverKey> {
            self.call_log.lock().unwrap().push("prover");
            self.entries
                .get(circuit_id.as_str())
                .map(|(p, _, _)| ProverKey::new(p.clone()))
                .ok_or_else(|| ContractRuntimeError::NotFound(circuit_id.as_str().to_owned()))
        }
        async fn get_verifier_key(&self, circuit_id: &CircuitId) -> Result<VerifierKey> {
            self.call_log.lock().unwrap().push("verifier");
            self.entries
                .get(circuit_id.as_str())
                .map(|(_, v, _)| VerifierKey::new(v.clone()))
                .ok_or_else(|| ContractRuntimeError::NotFound(circuit_id.as_str().to_owned()))
        }
    }

    #[tokio::test]
    async fn get_returns_bundle_with_all_three_artifacts() {
        let p = StaticProvider::with("inc", vec![1], vec![2], vec![3]);
        let bundle = p.get(&CircuitId::new("inc")).await.unwrap();
        assert_eq!(bundle.circuit_id.as_str(), "inc");
        assert_eq!(bundle.prover_key.as_bytes(), &[1]);
        assert_eq!(bundle.verifier_key.as_bytes(), &[2]);
        assert_eq!(bundle.zkir.as_bytes(), &[3]);
        // The default impl dispatches to all three primitives.
        let calls = p.call_log.lock().unwrap();
        assert_eq!(calls.len(), 3);
        assert!(calls.contains(&"prover"));
        assert!(calls.contains(&"verifier"));
        assert!(calls.contains(&"zkir"));
    }

    #[tokio::test]
    async fn get_verifier_keys_preserves_input_order_and_pairs_ids() {
        let mut p = StaticProvider::default();
        p.entries.insert("a".into(), (vec![1], vec![10], vec![100]));
        p.entries.insert("b".into(), (vec![2], vec![20], vec![200]));
        p.entries.insert("c".into(), (vec![3], vec![30], vec![250]));
        let ids = vec![
            CircuitId::new("c"),
            CircuitId::new("a"),
            CircuitId::new("b"),
        ];
        let pairs = p.get_verifier_keys(&ids).await.unwrap();
        assert_eq!(pairs.len(), 3);
        assert_eq!(pairs[0].0.as_str(), "c");
        assert_eq!(pairs[0].1.as_bytes(), &[30u8]);
        assert_eq!(pairs[1].0.as_str(), "a");
        assert_eq!(pairs[1].1.as_bytes(), &[10]);
        assert_eq!(pairs[2].0.as_str(), "b");
        assert_eq!(pairs[2].1.as_bytes(), &[20]);
    }

    #[tokio::test]
    async fn get_verifier_keys_surfaces_errors_on_missing_id() {
        let p = StaticProvider::with("a", vec![1], vec![2], vec![3]);
        let err = p
            .get_verifier_keys(&[CircuitId::new("a"), CircuitId::new("missing")])
            .await
            .unwrap_err();
        matches!(err, ContractRuntimeError::NotFound(_));
    }
}