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
//! Port of
//! `@midnight-ntwrk/midnight-js-contracts/src/submit-insert-vk-tx.ts`.
//!
//! Builds and submits a transaction that installs a new verifier key
//! for `circuit_id` at the deployed contract at `contract_address`.
//!
//! # Pre-conditions (ported from TS `assertDefined` / `assertUndefined`)
//!
//! - A contract state MUST exist on-chain at `contract_address`.
//! - The circuit MUST NOT already have a verifier key set — insert is
//!   for new circuits; replacing an existing key is the
//!   `replaceContractOperation` path (not yet ported).
//! - A signing key for `contract_address` MUST be stored locally in
//!   the private-state provider — that's the current maintenance
//!   authority.

use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::ledger::structure::SingleUpdate;
use moonproof_ledger::serialize::tagged_deserialize;
use rand::{CryptoRng, Rng};

use crate::error::{ContractRuntimeError, ContractsError, Result};
use crate::fee_balancing::FeeBalancingConfig;
use crate::maintenance::{build_unproven_maintenance_tx, MaintenanceTxOptions};
#[cfg(test)]
use crate::providers::ErasedProviders;
use crate::providers::{PrivateStateProvider, Providers, PublicDataProvider};
use crate::submit_tx::{submit_tx, SubmitTxOptions};
use crate::types::{CircuitId, FinalizedTxData, VerifierKey};

/// Options for [`submit_insert_verifier_key_tx`].
pub struct SubmitInsertVerifierKeyTxOptions {
    pub contract_address: ContractAddress,
    pub circuit_id: CircuitId,
    pub new_vk: VerifierKey,
    pub current_time: moonproof_ledger::base_crypto::time::Timestamp,
    pub network_id: String,
    pub fee_balancing: Option<FeeBalancingConfig>,
}

/// Options for [`submit_insert_verifier_keys_tx`] — install several
/// circuits' verifier keys in a single maintenance transaction.
pub struct SubmitInsertVerifierKeysTxOptions {
    pub contract_address: ContractAddress,
    /// The circuits to install, each with its tagged-serialized
    /// verifier key. Order is preserved in the on-chain
    /// [`MaintenanceUpdate`]; every id must be absent on-chain.
    pub circuits: Vec<(CircuitId, VerifierKey)>,
    pub current_time: moonproof_ledger::base_crypto::time::Timestamp,
    pub network_id: String,
    pub fee_balancing: Option<FeeBalancingConfig>,
}

/// Construct + submit an insert-verifier-key transaction. Port of TS
/// `submitInsertVerifierKeyTx`. Thin wrapper over
/// [`submit_insert_verifier_keys_tx`] for the single-circuit case.
pub async fn submit_insert_verifier_key_tx<R, C>(
    rng: &mut R,
    providers: &C,
    options: SubmitInsertVerifierKeyTxOptions,
) -> Result<FinalizedTxData>
where
    R: Rng + CryptoRng,
    C: Providers + ?Sized,
{
    submit_insert_verifier_keys_tx(
        rng,
        providers,
        SubmitInsertVerifierKeysTxOptions {
            contract_address: options.contract_address,
            circuits: vec![(options.circuit_id, options.new_vk)],
            current_time: options.current_time,
            network_id: options.network_id,
            fee_balancing: options.fee_balancing,
        },
    )
    .await
}

/// Construct + submit a maintenance transaction that installs verifier
/// keys for several circuits at once. One signed
/// [`MaintenanceUpdate`](moonproof_ledger::ledger::structure::MaintenanceUpdate)
/// carrying one [`SingleUpdate::VerifierKeyInsert`] per circuit, so the
/// authority counter advances by exactly one and the whole batch lands
/// (or fails) atomically.
///
/// Batching is what keeps an incremental deploy cheap: a contract whose
/// full verifier-key set overflows the ledger's per-tx byte limit is
/// split into batches that each fit, and each batch is one of these
/// transactions. See
/// [`deploy_contract_incremental`](crate::deploy_contract_incremental).
///
/// # Pre-conditions
///
/// - A contract state MUST exist on-chain at `contract_address`.
/// - `circuits` MUST be non-empty.
/// - Every circuit MUST be absent on-chain — insert is for new circuits
///   only.
/// - A signing key for `contract_address` MUST be stored locally (the
///   current maintenance authority).
pub async fn submit_insert_verifier_keys_tx<R, C>(
    rng: &mut R,
    providers: &C,
    options: SubmitInsertVerifierKeysTxOptions,
) -> Result<FinalizedTxData>
where
    R: Rng + CryptoRng,
    C: Providers + ?Sized,
{
    if options.circuits.is_empty() {
        return Err(ContractRuntimeError::Provider {
            provider: "submit_insert_verifier_keys_tx",
            message: "no circuits supplied — nothing to insert".to_owned(),
        });
    }

    // Pre-condition: contract state exists on-chain.
    let on_chain_state = providers
        .public_data()
        .query_contract_state(&options.contract_address, None)
        .await?
        .ok_or_else(|| {
            ContractRuntimeError::NotFound(format!(
                "No contract state found on chain for contract address {}",
                moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
            ))
        })?;

    // Build one VerifierKeyInsert update per circuit, validating each
    // before we sign anything. A duplicate-insert or a malformed VK
    // anywhere in the batch aborts the whole tx with a clear error.
    let mut updates = Vec::with_capacity(options.circuits.len());
    let mut circuit_ids = Vec::with_capacity(options.circuits.len());
    for (circuit_id, new_vk) in &options.circuits {
        let entry: moonproof_ledger::onchain_runtime::state::EntryPointBuf =
            circuit_id.as_str().as_bytes().into();

        // Pre-condition: circuit NOT already present — insert is for
        // new circuits only. Duplicate-insertion would fail the
        // ledger's apply step anyway, but we catch it locally for a
        // cleaner error.
        if on_chain_state.operations.get(&entry).is_some() {
            return Err(ContractRuntimeError::Provider {
                provider: "submit_insert_verifier_keys_tx",
                message: format!(
                    "Circuit '{}' is already defined for contract at address {} — use \
                     replace-verifier-key, not insert",
                    circuit_id.as_str(),
                    moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
                ),
            });
        }

        let ledger_vk: moonproof_ledger::transient_crypto::proofs::VerifierKey =
            tagged_deserialize(&mut new_vk.as_bytes()).map_err(|e| {
                ContractRuntimeError::Deserialize {
                    context: "submit_insert_verifier_keys_tx::tagged_deserialize(VerifierKey)",
                    source: e,
                }
            })?;
        updates.push(SingleUpdate::VerifierKeyInsert(
            entry,
            moonproof_ledger::versioned_verifier_key(ledger_vk),
        ));
        circuit_ids.push(circuit_id.clone());
    }

    // Pre-condition: signing key available locally.
    let signing_key = providers
        .private_state()
        .get_signing_key(&options.contract_address)
        .await?
        .ok_or_else(|| ContractRuntimeError::Provider {
            provider: "submit_insert_verifier_keys_tx",
            message: format!(
                "Signing key for contract address {} not found — the caller is not \
                 the maintenance authority for this contract",
                moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
            ),
        })?;

    // Build + sign the unproven maintenance tx carrying the whole batch.
    let unproven_tx = build_unproven_maintenance_tx(
        rng,
        MaintenanceTxOptions {
            contract_address: options.contract_address,
            on_chain_state: &on_chain_state,
            signing_key: &signing_key,
            updates,
            current_time: options.current_time,
            network_id: options.network_id,
            fee_balancing: options.fee_balancing,
        },
    )?;

    // Drive the standard prove→balance→submit pipeline.
    let submit_opts = SubmitTxOptions {
        unproven_tx,
        circuit_ids: Some(circuit_ids),
        prove_config: crate::providers::ProveTxConfig::default(),
        ttl_ms: None,
    };
    let finalized = submit_tx(providers, submit_opts).await?;
    if !finalized.status.is_success() {
        return Err(ContractRuntimeError::Contracts(
            ContractsError::insert_verifier_key_tx_failed(finalized),
        ));
    }
    Ok(finalized)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::{
        contract_state_with_committee, counter_vk_bytes, dummy_address, scripted_providers,
    };
    use crate::types::TxStatus;
    use moonproof_ledger::base_crypto::time::Timestamp;
    use moonproof_ledger::signatures::SigningKey;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    fn providers(
        signing_key: Option<SigningKey>,
        state: Option<
            moonproof_ledger::onchain_runtime::state::ContractState<
                moonproof_ledger::storage::db::InMemoryDB,
            >,
        >,
        status: TxStatus,
    ) -> ErasedProviders {
        scripted_providers(signing_key, state, status).0
    }

    /// ports: `submit-insert-vk-tx.test.ts::should successfully submit insert verifier key transaction`
    #[tokio::test]
    async fn happy_path_returns_finalized_tx_data() {
        let sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x33u8; 32]).unwrap();
        let state = contract_state_with_committee(&sk, "increment", /*circuit_present*/ false);
        let providers = providers(Some(sk.clone()), Some(state), TxStatus::SucceedEntirely);
        let new_vk = counter_vk_bytes().await;
        let mut rng = StdRng::seed_from_u64(0x100);
        let finalized = submit_insert_verifier_key_tx(
            &mut rng,
            &providers,
            SubmitInsertVerifierKeyTxOptions {
                contract_address: dummy_address(),
                circuit_id: CircuitId::new("brand-new-circuit"),
                new_vk,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap();
        assert_eq!(finalized.status, TxStatus::SucceedEntirely);
    }

    /// Batched insert: several new circuits in one maintenance tx.
    #[tokio::test]
    async fn plural_inserts_multiple_circuits_in_one_tx() {
        let sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x33u8; 32]).unwrap();
        let state = contract_state_with_committee(&sk, "increment", /*circuit_present*/ false);
        let providers = providers(Some(sk.clone()), Some(state), TxStatus::SucceedEntirely);
        let vk = counter_vk_bytes().await;
        let mut rng = StdRng::seed_from_u64(0x200);
        let finalized = submit_insert_verifier_keys_tx(
            &mut rng,
            &providers,
            SubmitInsertVerifierKeysTxOptions {
                contract_address: dummy_address(),
                circuits: vec![
                    (CircuitId::new("alpha"), vk.clone()),
                    (CircuitId::new("beta"), vk.clone()),
                    (CircuitId::new("gamma"), vk),
                ],
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap();
        assert_eq!(finalized.status, TxStatus::SucceedEntirely);
    }

    /// Empty batch is a caller error, caught before any tx is built.
    #[tokio::test]
    async fn plural_empty_batch_rejected() {
        let sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x33u8; 32]).unwrap();
        let state = contract_state_with_committee(&sk, "increment", /*circuit_present*/ false);
        let providers = providers(Some(sk.clone()), Some(state), TxStatus::SucceedEntirely);
        let mut rng = StdRng::seed_from_u64(0x201);
        let err = submit_insert_verifier_keys_tx(
            &mut rng,
            &providers,
            SubmitInsertVerifierKeysTxOptions {
                contract_address: dummy_address(),
                circuits: Vec::new(),
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap_err();
        assert!(format!("{err}").contains("nothing to insert"), "{err}");
    }

    /// A duplicate anywhere in the batch aborts the whole insert.
    #[tokio::test]
    async fn plural_rejects_batch_with_already_present_circuit() {
        let sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x33u8; 32]).unwrap();
        let state = contract_state_with_committee(&sk, "increment", /*circuit_present*/ true);
        let providers = providers(Some(sk.clone()), Some(state), TxStatus::SucceedEntirely);
        let vk = counter_vk_bytes().await;
        let mut rng = StdRng::seed_from_u64(0x202);
        let err = submit_insert_verifier_keys_tx(
            &mut rng,
            &providers,
            SubmitInsertVerifierKeysTxOptions {
                contract_address: dummy_address(),
                circuits: vec![
                    (CircuitId::new("brand-new"), vk.clone()),
                    (CircuitId::new("increment"), vk),
                ],
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap_err();
        assert!(format!("{err}").contains("already defined"), "{err}");
    }

    /// ports: `submit-insert-vk-tx.test.ts::should throw InsertVerifierKeyTxFailedError when transaction fails`
    #[tokio::test]
    async fn submit_failure_returns_insert_verifier_key_tx_failed() {
        let sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x33u8; 32]).unwrap();
        let state = contract_state_with_committee(&sk, "increment", /*circuit_present*/ false);
        let providers = providers(Some(sk.clone()), Some(state), TxStatus::FailEntirely);
        let new_vk = counter_vk_bytes().await;
        let mut rng = StdRng::seed_from_u64(0x100);
        let err = submit_insert_verifier_key_tx(
            &mut rng,
            &providers,
            SubmitInsertVerifierKeyTxOptions {
                contract_address: dummy_address(),
                circuit_id: CircuitId::new("brand-new-circuit"),
                new_vk,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(ContractsError::InsertVerifierKeyTxFailed { .. })
        );
        assert!(format!("{err}").contains("InsertVerifierKeyTxFailedError"));
    }

    /// Pre-condition coverage exercising the "circuit already
    /// present → reject before submission" branch the TS port doesn't
    /// test directly but the Rust port surfaces for cleaner diagnostics
    /// (the underlying ledger `apply` would fail anyway).
    #[tokio::test]
    async fn pre_condition_existing_circuit_rejects_before_submission() {
        let sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x33u8; 32]).unwrap();
        let state = contract_state_with_committee(&sk, "increment", /*circuit_present*/ true);
        let providers = providers(Some(sk.clone()), Some(state), TxStatus::SucceedEntirely);
        let new_vk = counter_vk_bytes().await;
        let mut rng = StdRng::seed_from_u64(0x100);
        let err = submit_insert_verifier_key_tx(
            &mut rng,
            &providers,
            SubmitInsertVerifierKeyTxOptions {
                contract_address: dummy_address(),
                // The circuit fixture pre-populates "increment".
                circuit_id: CircuitId::new("increment"),
                new_vk,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("already defined"), "{msg}");
    }

    /// Pre-condition coverage: missing on-chain state.
    #[tokio::test]
    async fn pre_condition_missing_on_chain_state_returns_not_found() {
        let sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x33u8; 32]).unwrap();
        let providers = providers(Some(sk.clone()), None, TxStatus::SucceedEntirely);
        let new_vk = counter_vk_bytes().await;
        let mut rng = StdRng::seed_from_u64(0x100);
        let err = submit_insert_verifier_key_tx(
            &mut rng,
            &providers,
            SubmitInsertVerifierKeyTxOptions {
                contract_address: dummy_address(),
                circuit_id: CircuitId::new("brand-new-circuit"),
                new_vk,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap_err();
        matches!(err, ContractRuntimeError::NotFound(_));
    }

    /// Pre-condition coverage: missing local signing key.
    #[tokio::test]
    async fn pre_condition_missing_signing_key_returns_provider_error() {
        let sk = moonproof_ledger::signatures::schnorr_signing_key(&[0x33u8; 32]).unwrap();
        let state = contract_state_with_committee(&sk, "increment", /*circuit_present*/ false);
        let providers = providers(None, Some(state), TxStatus::SucceedEntirely);
        let new_vk = counter_vk_bytes().await;
        let mut rng = StdRng::seed_from_u64(0x100);
        let err = submit_insert_verifier_key_tx(
            &mut rng,
            &providers,
            SubmitInsertVerifierKeyTxOptions {
                contract_address: dummy_address(),
                circuit_id: CircuitId::new("brand-new-circuit"),
                new_vk,
                current_time: Timestamp::from_secs(0),
                network_id: "local-test".into(),
                fee_balancing: None,
            },
        )
        .await
        .unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("Signing key"), "{msg}");
        assert!(msg.contains("not found"), "{msg}");
    }
}