Skip to main content

moonproof_contracts/providers/
in_process_proof.rs

1//! Concrete [`ProofProvider`] that drives a [`EngineProvingProvider`]
2//! to upgrade every proof-preimage in a contract transaction into a
3//! fully-proven one.
4//!
5//! Port of the TS reference's local-prover path — no HTTP proof
6//! server, just an in-process prover that resolves `ZSwap` / Dust keys
7//! via [`moonproof_prover::ProverEngine`]'s built-in
8//! [`MidnightDataProvider`](moonproof_ledger::base_crypto::data_provider::MidnightDataProvider).
9//!
10//! # Transaction stages
11//!
12//! - **Input**: tagged-serialized
13//!   `Transaction<Signature, ProofPreimageMarker, PedersenRandomness,
14//!   InMemoryDB>` — the shape
15//!   [`crate::unproven_deploy_tx::create_unproven_deploy_tx`] emits.
16//! - **Output**: tagged-serialized
17//!   `Transaction<Signature, ProofMarker, PedersenRandomness,
18//!   InMemoryDB>` — post-prove, pre-seal. The wallet provider is the
19//!   next stage and returns the sealed wire bytes.
20
21use std::sync::Arc;
22
23use moonproof_ledger::ledger::structure::{ProofMarker, ProofPreimageMarker, Transaction};
24use moonproof_ledger::onchain_runtime::cost_model::{CostModel, INITIAL_COST_MODEL};
25use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
26use moonproof_ledger::signatures::Signature;
27use moonproof_ledger::storage::db::InMemoryDB;
28use moonproof_ledger::transient_crypto::commitment::{PedersenRandomness, PureGeneratorPedersen};
29use moonproof_macros::async_trait;
30use moonproof_prover::EngineProvingProvider;
31use rand::rngs::OsRng;
32
33use crate::error::{ContractRuntimeError, Result};
34use crate::providers::proof::{collect_contract_key_materials, ProofProvider, ProveTxConfig};
35use crate::providers::zk_config::ZkConfigProvider;
36
37/// Concrete [`ProofProvider`] backed by [`EngineProvingProvider`].
38///
39/// Cheap to clone — the underlying engine is `Arc`-backed.
40///
41/// # Contract-circuit keys
42///
43/// When `prove_tx` receives a transaction that contains
44/// contract-call preimages, the prover needs the target circuits'
45/// ZKIR + prover/verifier keys. For each `ContractCallPrototype` in
46/// the tx, the provider loads the circuit's key material from the
47/// first source attached via [`Self::with_zk_config`] whose verifier
48/// key matches the call's key location (midnight-js 5's
49/// `ZKConfigRegistry`), and attaches it to the underlying
50/// [`EngineProvingProvider`] before proving. A transaction whose calls
51/// span several contracts, as a cross-contract call tree does, needs
52/// each contract's artifacts attached. Deploys and maintenance-only
53/// txs without call prototypes skip this step.
54#[derive(Clone)]
55pub struct InProcessProofProvider {
56    engine: EngineProvingProvider,
57    cost_model: Arc<CostModel>,
58    zk_configs: Vec<Arc<dyn ZkConfigProvider>>,
59}
60
61impl std::fmt::Debug for InProcessProofProvider {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        f.debug_struct("InProcessProofProvider")
64            .finish_non_exhaustive()
65    }
66}
67
68impl InProcessProofProvider {
69    /// Construct with the canonical [`INITIAL_COST_MODEL`]. Deploy /
70    /// maintenance-only callers don't need to attach a
71    /// `ZkConfigProvider`. Call-tx callers must thread one in via
72    /// [`Self::with_zk_config`].
73    #[must_use]
74    pub fn new(engine: EngineProvingProvider) -> Self {
75        Self {
76            engine,
77            cost_model: Arc::new(INITIAL_COST_MODEL.clone()),
78            zk_configs: Vec::new(),
79        }
80    }
81
82    /// Construct with a caller-supplied cost model — used when the
83    /// chain has bumped its runtime `CostModel` past
84    /// [`INITIAL_COST_MODEL`] and the caller already pulled the
85    /// up-to-date one out of `ChainParameters`.
86    #[must_use]
87    pub fn with_cost_model(engine: EngineProvingProvider, cost_model: CostModel) -> Self {
88        Self {
89            engine,
90            cost_model: Arc::new(cost_model),
91            zk_configs: Vec::new(),
92        }
93    }
94
95    /// Add a [`ZkConfigProvider`] `prove_tx` loads contract-circuit
96    /// keys from. Required for call txs; sources are tried in the order
97    /// they were added.
98    #[must_use]
99    pub fn with_zk_config(mut self, zk_config: Arc<dyn ZkConfigProvider>) -> Self {
100        self.zk_configs.push(zk_config);
101        self
102    }
103
104    /// Borrow the underlying [`EngineProvingProvider`].
105    ///
106    /// Useful for wallet sub-wallet pipelines (transfer / dust-with-spends /
107    /// shielded-only) that build their own
108    /// [`moonproof_ledger::transient_crypto::proofs::ProvingProvider`] flow without
109    /// going through the runtime's contract-tx
110    /// `prove_tx` → `balance_tx` two-step.
111    #[inline]
112    #[must_use]
113    pub fn engine(&self) -> &EngineProvingProvider {
114        &self.engine
115    }
116
117    /// Prove **and seal** an unproven transaction in one step. Suitable
118    /// for the wallet sub-wallet path — transfer/registration/swap recipes
119    /// from `moonproof_wallet::facade` and dust-spend-bearing flows from
120    /// `moonproof_wallet::dust::ledger_adapter`. Both go from
121    /// `Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>`
122    /// straight to wire-format
123    /// `Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB>`
124    /// without a separate balance/seal stage.
125    ///
126    /// Contract-call key resolution is identical to
127    /// [`ProofProvider::prove_tx`] — when the unproven tx contains
128    /// contract-call prototypes AND a [`ZkConfigProvider`] is attached,
129    /// the matching circuit keys are pre-loaded into the engine before
130    /// `Transaction::prove` runs.
131    pub async fn prove_and_seal_tx(&self, unproven_tx_bytes: Vec<u8>) -> Result<Vec<u8>> {
132        let unproven: Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB> =
133            tagged_deserialize(&mut unproven_tx_bytes.as_slice()).map_err(|e| {
134                ContractRuntimeError::Deserialize {
135                    context: "InProcessProofProvider::prove_and_seal_tx(unproven)",
136                    source: e,
137                }
138            })?;
139
140        let contract_keys = collect_contract_key_materials(&unproven, &self.zk_configs).await?;
141        let engine_with_keys = self.engine.clone().with_contract_keys(contract_keys);
142
143        // Off the async runtime: proving is CPU-bound, and on ledger 9
144        // the ledger's proving future is `!Send` (its resolver is an
145        // `async fn` in trait), which the `#[uniffi::export]` callers
146        // of this method cannot be.
147        let cost_model = self.cost_model.clone();
148        let proven = moonproof_prover::prove_offthread(move || async move {
149            unproven.prove(engine_with_keys, &cost_model).await
150        })
151        .await
152        .map_err(|e| ContractRuntimeError::Proving(format!("prove_and_seal_tx(prove): {e}")))?
153        .map_err(|e| ContractRuntimeError::Proving(format!("prove_and_seal_tx(prove): {e:?}")))?;
154        let sealed: Transaction<Signature, ProofMarker, PureGeneratorPedersen, InMemoryDB> =
155            proven.seal(OsRng);
156
157        let mut out = Vec::with_capacity(unproven_tx_bytes.len());
158        tagged_serialize(&sealed, &mut out).map_err(|e| ContractRuntimeError::Serialize {
159            context: "InProcessProofProvider::prove_and_seal_tx(serialize sealed)",
160            source: e,
161        })?;
162        Ok(out)
163    }
164}
165
166#[async_trait]
167impl ProofProvider for InProcessProofProvider {
168    async fn prove_tx(
169        &self,
170        tx: crate::tx_phase::UnprovenTx,
171        _config: &ProveTxConfig,
172    ) -> Result<crate::tx_phase::ProvenTx> {
173        let unproven = tx.into_inner();
174
175        // Pre-load every contract-circuit's ZK key material so the
176        // proving engine's combined resolver can serve them up during
177        // `check` / `prove`. Deploys + maintenance-only txs contain
178        // no call prototypes and skip this entirely.
179        let contract_keys = collect_contract_key_materials(&unproven, &self.zk_configs).await?;
180        let engine_with_keys = self.engine.clone().with_contract_keys(contract_keys);
181
182        // Off the async runtime: proving is CPU-bound, and on ledger 9
183        // the ledger's proving future is `!Send` (its resolver is an
184        // `async fn` in trait), which this impl cannot be.
185        let cost_model = self.cost_model.clone();
186        let proven = moonproof_prover::prove_offthread(move || async move {
187            unproven.prove(engine_with_keys, &cost_model).await
188        })
189        .await
190        .map_err(|e| ContractRuntimeError::Proving(format!("prove(unproven tx): {e}")))?
191        .map_err(|e| ContractRuntimeError::Proving(format!("prove(unproven tx): {e:?}")))?;
192        Ok(crate::tx_phase::ProvenTx::new(proven))
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    #[test]
201    fn provider_is_debug_and_clone() {
202        // Construct without a real engine — the only non-pedantic path
203        // is to verify the type-level traits are available on the
204        // struct. A real prove round-trip is exercised by the
205        // integration test that drives the full counter-deploy
206        // pipeline; building an EngineProvingProvider here would
207        // require the MidnightDataProvider's SRS cache, which is a
208        // network dependency we explicitly don't want in unit tests.
209        fn assert_send_sync<T: Send + Sync>() {}
210        assert_send_sync::<InProcessProofProvider>();
211    }
212}