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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Shared mock providers used by the runtime's offline unit tests.
//!
//! Each `#[cfg(test)]` mod that needs to script a finalized
//! transaction status against the submit pipeline previously
//! re-defined the same five trait stubs (proof / wallet / midnight /
//! zk-config + a pair of public-data + private-state scripted
//! providers). This module hosts the canonical versions so those test
//! mods can `use` rather than copy-paste.
//!
//! Kept under `#[cfg(test)]` so it compiles only for tests, and
//! re-exports public types from the providers traits without exposing
//! anything internal.

#![cfg(test)]

use std::sync::Arc;

use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::state::{
    ContractMaintenanceAuthority, ContractOperation, ContractState, EntryPointBuf, StateValue,
};
use moonproof_ledger::signatures::SigningKey;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use moonproof_macros::async_trait;

use crate::error::Result;
use crate::providers::public_data::{PublicDataStream, ZSwapAndContractState};
use crate::providers::{
    ErasedProviders, MidnightProvider, PrivateStateProvider, ProofProvider, ProveTxConfig,
    PublicDataProvider, WalletProvider, ZkConfigProvider,
};
use crate::types::{
    BlockHash, CircuitId, CoinPublicKey, ContractStateQueryAt, ContractStateStreamStart,
    EncPublicKey, Fees, FinalizedTxData, PrivateStateId, ProverKey, TransactionHash, TransactionId,
    TxStatus, UnshieldedBalances, UnshieldedUtxos, VerifierKey, Zkir,
};

/// Returns `0x77...` — a deterministic dummy contract address used
/// across the test suite when the actual address doesn't matter.
#[must_use]
pub fn dummy_address() -> ContractAddress {
    ContractAddress(HashOutput([0x77u8; 32]))
}

/// Build a minimal `ContractState` whose maintenance committee
/// contains exactly `signing_key`'s verifying key. If
/// `circuit_present` is true, the state's operations map carries a
/// stub `ContractOperation` keyed at `circuit_id` (no verifier key
/// installed — the maintenance pre-condition checks only existence,
/// not the VK content).
#[must_use]
pub fn contract_state_with_committee(
    signing_key: &SigningKey,
    circuit_id: &str,
    circuit_present: bool,
) -> ContractState<InMemoryDB> {
    let mut ops: StorageHashMap<EntryPointBuf, ContractOperation, InMemoryDB> =
        StorageHashMap::new();
    if circuit_present {
        let entry: EntryPointBuf = circuit_id.as_bytes().into();
        ops = ops.insert(entry, moonproof_ledger::contract_operation(None));
    }
    ContractState::<InMemoryDB>::new(
        StateValue::Null,
        ops,
        ContractMaintenanceAuthority {
            committee: vec![moonproof_ledger::signatures::maintenance_verifying_key(
                signing_key,
            )],
            threshold: 1,
            counter: 0,
        },
    )
}

/// Public-data provider whose `query_contract_state` returns a fixed
/// optional state and whose `watch_for_tx_data` returns a finalized
/// record stamped with the supplied [`TxStatus`]. The remaining trait
/// methods panic with `unimplemented!()` — call sites that exercise
/// them script their own provider.
#[derive(Debug)]
pub struct ScriptedPublicData {
    pub state: Option<ContractState<InMemoryDB>>,
    pub status: TxStatus,
    /// If set, returned from `query_zswap_and_contract_state`. Tests
    /// that exercise the call-tx path script this; tests that hit
    /// only `query_contract_state` (the maintenance-tx path) leave
    /// it as `None`.
    pub zswap_bundle: Option<ZSwapAndContractState>,
}
#[async_trait]
impl PublicDataProvider for ScriptedPublicData {
    async fn query_contract_state(
        &self,
        _address: &ContractAddress,
        _at: Option<ContractStateQueryAt>,
    ) -> Result<Option<ContractState<InMemoryDB>>> {
        Ok(self.state.clone())
    }
    async fn query_zswap_and_contract_state(
        &self,
        _address: &ContractAddress,
        _at: Option<ContractStateQueryAt>,
    ) -> Result<Option<ZSwapAndContractState>> {
        Ok(self.zswap_bundle.clone())
    }
    async fn query_deploy_contract_state(
        &self,
        _address: &ContractAddress,
    ) -> Result<Option<ContractState<InMemoryDB>>> {
        unimplemented!("ScriptedPublicData: query_deploy_contract_state not used")
    }
    async fn query_unshielded_balances(
        &self,
        _address: &ContractAddress,
        _at: Option<ContractStateQueryAt>,
    ) -> Result<Option<UnshieldedBalances>> {
        unimplemented!("ScriptedPublicData: query_unshielded_balances not used")
    }
    async fn watch_for_deploy_tx_data(
        &self,
        _address: &ContractAddress,
    ) -> Result<FinalizedTxData> {
        unimplemented!("ScriptedPublicData: watch_for_deploy_tx_data not used")
    }
    async fn watch_for_tx_data(&self, tx_id: &TransactionId) -> Result<FinalizedTxData> {
        Ok(FinalizedTxData {
            tx_id: tx_id.clone(),
            identifiers: vec![tx_id.clone()],
            tx_hash: TransactionHash::new("0x"),
            block_hash: BlockHash::new("0x"),
            block_height: 1,
            block_timestamp_ms: 0,
            block_author: None,
            indexer_id: 0,
            protocol_version: moonproof_wallet::ProtocolVersion(8),
            status: self.status,
            segment_status_map: None,
            fees: Fees {
                paid_fees: "0".into(),
                estimated_fees: "0".into(),
            },
            unshielded: UnshieldedUtxos::default(),
            tx_bytes: Vec::new(),
        })
    }
    async fn watch_for_contract_state(
        &self,
        _address: &ContractAddress,
    ) -> Result<ContractState<InMemoryDB>> {
        unimplemented!("ScriptedPublicData: watch_for_contract_state not used")
    }
    async fn watch_for_unshielded_balances(
        &self,
        _address: &ContractAddress,
    ) -> Result<UnshieldedBalances> {
        unimplemented!("ScriptedPublicData: watch_for_unshielded_balances not used")
    }
    async fn contract_state_stream(
        &self,
        _address: &ContractAddress,
        _start: ContractStateStreamStart,
    ) -> Result<PublicDataStream<ContractState<InMemoryDB>>> {
        unimplemented!("ScriptedPublicData: contract_state_stream not used")
    }
    async fn unshielded_balances_stream(
        &self,
        _address: &ContractAddress,
        _start: ContractStateStreamStart,
    ) -> Result<PublicDataStream<UnshieldedBalances>> {
        unimplemented!("ScriptedPublicData: unshielded_balances_stream not used")
    }
}

/// Private-state provider whose `get_signing_key` returns a fixed
/// `Option<SigningKey>` and whose `set_signing_key` records every
/// invocation. The set-private-state methods are no-ops; tests that
/// need fine-grained capture script their own.
#[derive(Debug, Default)]
pub struct ScriptedPrivateState {
    pub signing_key: std::sync::Mutex<Option<SigningKey>>,
    pub set_signing_key_calls: std::sync::Mutex<Vec<(ContractAddress, SigningKey)>>,
}
impl ScriptedPrivateState {
    #[must_use]
    pub fn with_signing_key(signing_key: Option<SigningKey>) -> Self {
        Self {
            signing_key: std::sync::Mutex::new(signing_key),
            set_signing_key_calls: std::sync::Mutex::new(Vec::new()),
        }
    }
}
#[async_trait]
impl PrivateStateProvider for ScriptedPrivateState {
    async fn set_contract_address(&self, _address: &ContractAddress) -> Result<()> {
        Ok(())
    }
    async fn set(&self, _: &PrivateStateId, _: Vec<u8>) -> Result<()> {
        Ok(())
    }
    async fn get(&self, _: &PrivateStateId) -> Result<Option<Vec<u8>>> {
        Ok(None)
    }
    async fn remove(&self, _: &PrivateStateId) -> Result<()> {
        Ok(())
    }
    async fn clear(&self) -> Result<()> {
        Ok(())
    }
    async fn set_signing_key(&self, address: &ContractAddress, sk: SigningKey) -> Result<()> {
        self.set_signing_key_calls
            .lock()
            .unwrap()
            .push((*address, sk.clone()));
        *self.signing_key.lock().unwrap() = Some(sk);
        Ok(())
    }
    async fn get_signing_key(&self, _: &ContractAddress) -> Result<Option<SigningKey>> {
        Ok(self.signing_key.lock().unwrap().clone())
    }
    async fn remove_signing_key(&self, _: &ContractAddress) -> Result<()> {
        Ok(())
    }
    async fn clear_signing_keys(&self) -> Result<()> {
        Ok(())
    }
    async fn export_private_states(
        &self,
        _options: &crate::providers::ExportPrivateStatesOptions,
    ) -> Result<crate::providers::PrivateStateExport> {
        unimplemented!()
    }
    async fn import_private_states(
        &self,
        _export: &crate::providers::PrivateStateExport,
        _options: &crate::providers::ImportPrivateStatesOptions,
    ) -> Result<crate::providers::ImportPrivateStatesResult> {
        unimplemented!()
    }
    async fn export_signing_keys(
        &self,
        _options: &crate::providers::private_state::ExportSigningKeysOptions,
    ) -> Result<crate::providers::SigningKeyExport> {
        unimplemented!()
    }
    async fn import_signing_keys(
        &self,
        _export: &crate::providers::SigningKeyExport,
        _options: &crate::providers::private_state::ImportSigningKeysOptions,
    ) -> Result<crate::providers::private_state::ImportSigningKeysResult> {
        unimplemented!()
    }
}

/// Proving provider that panics if any preimage actually needs
/// proving — the offline tests we use it with build empty deploy
/// txs that contain no proof preimages, so the trait methods are
/// never reached. The presence of the impl is enough to satisfy the
/// `Transaction::prove` signature and to promote the type marker
/// from `ProofPreimageMarker` to `ProofMarker`.
struct NoopProver;
impl moonproof_ledger::transient_crypto::proofs::ProvingProvider for NoopProver {
    fn check(
        &self,
        _: &moonproof_ledger::transient_crypto::proofs::ProofPreimage,
    ) -> impl std::future::Future<Output = std::result::Result<Vec<Option<usize>>, anyhow::Error>>
    {
        std::future::ready(Err(anyhow::anyhow!(
            "NoopProver::check called — the test transaction unexpectedly contains a proof preimage"
        )))
    }
    fn prove(
        self,
        _: &moonproof_ledger::transient_crypto::proofs::ProofPreimage,
        _: Option<moonproof_ledger::transient_crypto::curve::Fr>,
    ) -> impl std::future::Future<
        Output = std::result::Result<
            moonproof_ledger::transient_crypto::proofs::Proof,
            anyhow::Error,
        >,
    > {
        std::future::ready(Err(anyhow::anyhow!(
            "NoopProver::prove called — the test transaction unexpectedly contains a proof preimage"
        )))
    }
    #[cfg(not(feature = "ledger8"))]
    fn resolver(&self) -> &impl moonproof_ledger::transient_crypto::proofs::Resolver {
        static EMPTY: std::sync::OnceLock<moonproof_prover::ContractKeyResolver> =
            std::sync::OnceLock::new();
        EMPTY.get_or_init(moonproof_prover::ContractKeyResolver::default)
    }

    fn split(&mut self) -> Self {
        NoopProver
    }
}

/// Proof provider for offline tests. Drives `Transaction::prove`
/// with [`NoopProver`] — works for any unproven tx whose proof
/// preimage list is empty (deploys of stateless contracts, the
/// maintenance-tx flows, etc.). Returns a real
/// `Transaction<Signature, ProofMarker, PedersenRandomness>` so the
/// downstream typed-phase pipeline accepts it.
#[derive(Debug)]
pub struct PassThroughProof;
#[async_trait]
impl ProofProvider for PassThroughProof {
    async fn prove_tx(
        &self,
        tx: crate::tx_phase::UnprovenTx,
        _: &ProveTxConfig,
    ) -> Result<crate::tx_phase::ProvenTx> {
        let unproven = tx.into_inner();
        let proven = moonproof_prover::prove_offthread(move || async move {
            let cost_model = &moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
            unproven.prove(NoopProver, cost_model).await
        })
        .await
        .map_err(|e| {
            crate::error::ContractRuntimeError::Proving(format!("PassThroughProof::prove_tx: {e}"))
        })?
        .map_err(|e| {
            crate::error::ContractRuntimeError::Proving(format!(
                "PassThroughProof::prove_tx: {e:?}"
            ))
        })?;
        Ok(crate::tx_phase::ProvenTx::new(proven))
    }
}

/// Wallet provider that seals the proven tx with a deterministic rng.
/// No coin balancing — for offline tests that don't carry zswap/dust
/// legs.
#[derive(Debug)]
pub struct PassThroughWallet;
#[async_trait]
impl WalletProvider for PassThroughWallet {
    async fn balance_tx(
        &self,
        tx: crate::tx_phase::ProvenTx,
        _: Option<i64>,
    ) -> Result<crate::tx_phase::FinalizedTx> {
        use rand::SeedableRng;
        let sealed = tx
            .into_inner()
            .seal(rand::rngs::StdRng::seed_from_u64(0xfeed_face));
        Ok(crate::tx_phase::FinalizedTx::new(sealed))
    }
    fn coin_public_key(&self) -> CoinPublicKey {
        CoinPublicKey([0; 32])
    }
    fn encryption_public_key(&self) -> EncPublicKey {
        EncPublicKey([0; 32])
    }
}

/// Midnight provider whose `submit_tx` returns a fixed transaction
/// id without doing any actual submission.
#[derive(Debug)]
pub struct StubMidnight;
#[async_trait]
impl MidnightProvider for StubMidnight {
    async fn submit_tx(&self, _: crate::tx_phase::FinalizedTx) -> Result<TransactionId> {
        Ok(TransactionId::new("0xtxid"))
    }
}

/// ZK-config provider whose every method panics. Used when the
/// pipeline under test never reaches the proof step.
#[derive(Debug)]
pub struct NoopZkConfig;
#[async_trait]
impl ZkConfigProvider for NoopZkConfig {
    async fn get_zkir(&self, _: &CircuitId) -> Result<Zkir> {
        unimplemented!("NoopZkConfig: get_zkir not used")
    }
    async fn get_prover_key(&self, _: &CircuitId) -> Result<ProverKey> {
        unimplemented!("NoopZkConfig: get_prover_key not used")
    }
    async fn get_verifier_key(&self, _: &CircuitId) -> Result<VerifierKey> {
        unimplemented!("NoopZkConfig: get_verifier_key not used")
    }
}

/// Convenience: bundle a `ContractProviders` with all the offline
/// stubs above. `signing_key` is the value `get_signing_key` will
/// return; `state` is the value `query_contract_state` will return;
/// `status` is what `watch_for_tx_data` reports.
///
/// Returns the bundle plus the `ScriptedPrivateState` so callers can
/// assert against the recorded `set_signing_key` calls.
#[must_use]
pub fn scripted_providers(
    signing_key: Option<SigningKey>,
    state: Option<ContractState<InMemoryDB>>,
    status: TxStatus,
) -> (ErasedProviders, Arc<ScriptedPrivateState>) {
    let ps = Arc::new(ScriptedPrivateState::with_signing_key(signing_key));
    let bundle = ErasedProviders::builder()
        .private_state(ps.clone())
        .public_data(Arc::new(ScriptedPublicData {
            state,
            status,
            zswap_bundle: None,
        }))
        .zk_config(Arc::new(NoopZkConfig))
        .proof(Arc::new(PassThroughProof))
        .wallet(Arc::new(PassThroughWallet))
        .midnight(Arc::new(StubMidnight))
        .build();
    (bundle, ps)
}

/// Like [`scripted_providers`] but also scripts
/// `query_zswap_and_contract_state` — required for the call-tx path —
/// and proves for real.
///
/// `zswap_bundle.contract_state` is what the call's circuit runs
/// against; the byte slots are typically empty (only consulted by the
/// fee-balancing path).
///
/// A call transaction always carries a proof preimage, so
/// [`PassThroughProof`] — which drives `Transaction::prove` with a
/// prover that refuses every preimage — cannot serve one. This wires
/// the same in-process prover the CLI and the live suites use, reading
/// the counter fixture's ZKIR and prover key off disk. Everything else
/// stays scripted: no indexer, no node, no chain.
///
/// Needs the SRS parameters the prover resolves through
/// `ProverEngine::from_env`, so callers stay `#[ignore]`d.
///
/// # Panics
///
/// If the prover engine cannot be initialised.
#[must_use]
pub fn scripted_providers_with_real_prover(
    signing_key: Option<SigningKey>,
    state: Option<ContractState<InMemoryDB>>,
    zswap_bundle: Option<ZSwapAndContractState>,
    status: TxStatus,
) -> (ErasedProviders, Arc<ScriptedPrivateState>) {
    let ps = Arc::new(ScriptedPrivateState::with_signing_key(signing_key));
    let zk_config = Arc::new(
        crate::providers::fs_zk_config::FileSystemZkConfigProvider::new(counter_fixture_root()),
    );
    let prover_engine = Arc::new(
        moonproof_prover::ProverEngine::from_env().expect("init ProverEngine for the call-tx path"),
    );
    let proof = Arc::new(
        crate::providers::in_process_proof::InProcessProofProvider::new(
            moonproof_prover::EngineProvingProvider::new(prover_engine),
        )
        .with_zk_config(zk_config.clone()),
    );
    let bundle = ErasedProviders::builder()
        .private_state(ps.clone())
        .public_data(Arc::new(ScriptedPublicData {
            state,
            status,
            zswap_bundle,
        }))
        .zk_config(zk_config)
        .proof(proof)
        .wallet(Arc::new(PassThroughWallet))
        .midnight(Arc::new(StubMidnight))
        .build();
    (bundle, ps)
}

/// Returns the path to the vendored counter fixture root —
/// `crates/test-fixtures/contracts/counter/`. Used by tests that load
/// real verifier keys / ZKIR bytes.
#[must_use]
pub fn counter_fixture_root() -> std::path::PathBuf {
    let mut p = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    p.pop();
    p.pop();
    p.push("crates/test-fixtures/contracts/counter");
    p
}

/// Load the counter fixture's verifier key bytes (tagged-serialized).
pub async fn counter_vk_bytes() -> VerifierKey {
    let zk =
        crate::providers::fs_zk_config::FileSystemZkConfigProvider::new(counter_fixture_root());
    zk.get_verifier_key(&CircuitId::new("increment"))
        .await
        .unwrap()
}

/// Path to the vendored counter `contract.mpir`.
#[must_use]
pub fn counter_ir_path() -> std::path::PathBuf {
    let mut p = counter_fixture_root();
    p.push("contract.mpir");
    p
}

/// Build an `IrExecutable<NoWitnesses>` for the counter fixture with
/// the vendored verifier key attached. Most in-source unit tests want
/// this exact shape — the only off-chain executor in the post-Phase-4
/// world.
pub async fn counter_ir_executable(
) -> moonproof_runtime::ir_executable::IrExecutable<moonproof_runtime::ir::witnesses::NoWitnesses> {
    let vk = counter_vk_bytes().await;
    moonproof_runtime::ir_executable::IrExecutable::from_path(
        counter_ir_path(),
        Arc::new(moonproof_runtime::ir::witnesses::NoWitnesses),
    )
    .expect("counter contract.mpir loads")
    .with_verifier_key("increment", vk)
}

/// The ledger's initial parameters, tagged-serialized the way the
/// indexer serves a block's `ledgerParameters`. Offline tests have no
/// block to read them from, so they name the initial ones explicitly.
pub(crate) fn initial_ledger_parameters_bytes() -> Vec<u8> {
    let mut bytes = Vec::new();
    moonproof_ledger::serialize::tagged_serialize(
        &moonproof_ledger::ledger::structure::INITIAL_PARAMETERS,
        &mut bytes,
    )
    .expect("initial ledger parameters serialize");
    bytes
}