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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! Contract handle + lifecycle entry points.
//!
//! Brings together:
//! - [`Contract`] — typed handle returned by either lifecycle path,
//!   exposing the per-circuit call interface + maintenance interfaces.
//! - [`deploy_contract`] / [`DeployOptions`] — submit a fresh
//!   deploy tx + wait for finalization, returning [`Contract::Deployed`].
//! - [`find_deployed_contract`] / [`FindDeployedContractOptions`] —
//!   attach to an already-deployed contract by address, verifying the
//!   on-chain operations table matches the local executable's verifier
//!   keys, returning [`Contract::Found`].
//! - [`verify_contract_state`] / [`verifier_keys_equal`] — vk-equality
//!   helpers used by `find_deployed_contract` and exposed for callers
//!   that want to validate a state without loading the full contract.
//!
//! Port of `@midnight-ntwrk/midnight-js-contracts/src/{deploy-contract,
//! find-deployed-contract}.ts`. The two TS files merge cleanly: deploy
//! and find produce the same `Contract<C>` shape on the JS side, and
//! `verifyContractState` is shared between them.

use std::sync::Arc;

use moonproof_ledger::coin_structure::coin::Info as ShieldedCoinInfo;
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::state::{ContractState, EntryPointBuf};
use moonproof_ledger::signatures::SigningKey;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_runtime::ir::witnesses::Witnesses;
use moonproof_runtime::ir_executable::IrExecutable;
use moonproof_runtime_ir::RuntimeValue;
use rand::{CryptoRng, Rng};

use crate::error::{ContractRuntimeError, ContractsError, Result};
use crate::providers::ErasedProviders;
use crate::submit_deploy_tx::submit_deploy_tx;
use crate::tx_interfaces::{
    CallOptions, CircuitMaintenanceTx, CircuitMaintenanceTxInterfaces, ContractCalls,
    ContractMaintenanceTx,
};
use crate::tx_phase::UnprovenTx;
use crate::types::{CircuitId, FinalizedTxData, PrivateStateId, VerifierKey};
pub use crate::unproven_deploy_tx::DeployOptions;
use crate::utils::zswap_utils::CompactZswapLocalState;

// =====================================================================
// Contract handle
// =====================================================================

/// A contract handle bound to providers + executable.
///
/// Two variants:
/// - [`Contract::Deployed`] — produced by [`deploy_contract`].
///   Carries the full deploy-time payload (initial private state,
///   initial zswap local state, the unproven tx still in hand,
///   shielded new-coins) on top of the resolvable shared fields.
/// - [`Contract::Found`] — produced by [`find_deployed_contract`].
///   Carries only what the on-chain state + locally-stored signing
///   key can re-derive. Deploy-time private payload is unavailable on
///   this path; pattern-match on [`Contract::Deployed`] to reach for
///   those fields.
///
/// Shared accessor methods cover the fields every consumer needs
/// (address, finalized tx, call / maintenance interfaces). Reach into
/// the `Deployed` variant directly when the deploy-only fields are
/// required.
// Both variants are inherently large deploy-state bundles that differ by
// a few deploy-only fields; the size gap is not a memory concern (a
// contract handle is never held in bulk) and boxing would churn the wide
// field access across consumers.
#[allow(clippy::large_enum_variant)]
pub enum Contract<W: Witnesses + 'static> {
    Deployed {
        contract_address: ContractAddress,
        initial_contract_state: ContractState<InMemoryDB>,
        signing_key: SigningKey,
        finalized_deploy_tx: FinalizedTxData,
        calls: ContractCalls<W>,
        circuit_maintenance_tx: CircuitMaintenanceTxInterfaces,
        contract_maintenance_tx: ContractMaintenanceTx,
        initial_private_state: RuntimeValue,
        initial_zswap_local_state: CompactZswapLocalState,
        unproven_tx: Option<UnprovenTx>,
        new_coins: Vec<ShieldedCoinInfo>,
    },
    Found {
        contract_address: ContractAddress,
        initial_contract_state: ContractState<InMemoryDB>,
        signing_key: SigningKey,
        finalized_deploy_tx: FinalizedTxData,
        calls: ContractCalls<W>,
        circuit_maintenance_tx: CircuitMaintenanceTxInterfaces,
        contract_maintenance_tx: ContractMaintenanceTx,
    },
}

impl<W: Witnesses + 'static> Contract<W> {
    /// Address the contract is bound to.
    #[inline]
    #[must_use]
    pub fn contract_address(&self) -> &ContractAddress {
        match self {
            Self::Deployed {
                contract_address, ..
            }
            | Self::Found {
                contract_address, ..
            } => contract_address,
        }
    }

    /// Initial on-chain `ContractState` recorded at deploy time.
    /// Same shape on both variants.
    #[inline]
    #[must_use]
    pub fn initial_contract_state(&self) -> &ContractState<InMemoryDB> {
        match self {
            Self::Deployed {
                initial_contract_state,
                ..
            }
            | Self::Found {
                initial_contract_state,
                ..
            } => initial_contract_state,
        }
    }

    /// Signing key bound to this contract — the maintenance authority
    /// the deployer registered (deploy variant) or the locally-stored
    /// key resolved during find (find variant).
    #[inline]
    #[must_use]
    pub fn signing_key(&self) -> &SigningKey {
        match self {
            Self::Deployed { signing_key, .. } | Self::Found { signing_key, .. } => signing_key,
        }
    }

    /// Finalized tx data of the deploy that produced this contract.
    /// On the deploy path: the tx the local submission produced. On
    /// the find path: the deploy tx the indexer surfaced via
    /// `watch_for_deploy_tx_data`.
    #[inline]
    #[must_use]
    pub fn finalized_deploy_tx(&self) -> &FinalizedTxData {
        match self {
            Self::Deployed {
                finalized_deploy_tx,
                ..
            }
            | Self::Found {
                finalized_deploy_tx,
                ..
            } => finalized_deploy_tx,
        }
    }

    /// Per-circuit call dispatcher bound to this contract's address +
    /// providers. Use [`Self::call`] for the common one-shot path; the
    /// dispatcher is exposed here for advanced flows that batch or
    /// interleave staged-builder steps (B1).
    #[inline]
    #[must_use]
    pub fn calls(&self) -> &ContractCalls<W> {
        match self {
            Self::Deployed { calls, .. } | Self::Found { calls, .. } => calls,
        }
    }

    /// Invoke `circuit_id` against this contract. Forwards to
    /// [`ContractCalls::call`] on the contract's bound dispatcher —
    /// `contract.call(rng, "increment", args, opts).await` is the
    /// idiomatic shape; reach for [`Self::calls`] when batched or
    /// staged use is needed.
    ///
    /// # Errors
    ///
    /// Propagates any error from the submit pipeline.
    pub async fn call<R>(
        &self,
        rng: &mut R,
        circuit_id: impl Into<CircuitId>,
        args: RuntimeValue,
        options: CallOptions,
    ) -> Result<crate::tx_model::FinalizedCallTxData>
    where
        R: Rng + CryptoRng,
    {
        self.calls().call(rng, circuit_id, args, options).await
    }

    /// Per-circuit verifier-key maintenance interfaces.
    #[inline]
    #[must_use]
    pub fn circuit_maintenance_tx(&self) -> &CircuitMaintenanceTxInterfaces {
        match self {
            Self::Deployed {
                circuit_maintenance_tx,
                ..
            }
            | Self::Found {
                circuit_maintenance_tx,
                ..
            } => circuit_maintenance_tx,
        }
    }

    /// Contract-level maintenance interface (replace authority).
    #[inline]
    #[must_use]
    pub fn contract_maintenance_tx(&self) -> &ContractMaintenanceTx {
        match self {
            Self::Deployed {
                contract_maintenance_tx,
                ..
            }
            | Self::Found {
                contract_maintenance_tx,
                ..
            } => contract_maintenance_tx,
        }
    }

    /// `true` when this handle was produced by [`deploy_contract`].
    /// Use as a quick discriminant before pattern-matching for the
    /// deploy-only fields.
    #[inline]
    #[must_use]
    pub const fn is_deployed(&self) -> bool {
        matches!(self, Self::Deployed { .. })
    }

    /// `true` when this handle was produced by [`find_deployed_contract`].
    #[inline]
    #[must_use]
    pub const fn is_found(&self) -> bool {
        matches!(self, Self::Found { .. })
    }
}

// Deploy-only fields (initial_private_state, initial_zswap_local_state,
// unproven_tx, new_coins) live exclusively on the `Deployed` variant.
// Pattern-match on `Contract::Deployed { .. }` to access them; the
// type system makes the unavailability on `Found` explicit at call
// sites rather than handing back `Option<&T>` shaped values that
// callers always have to unwrap.

// =====================================================================
// deploy_contract
// =====================================================================

/// Deploy a contract.
///
/// On success, returns a [`Contract::Deployed`] with the call +
/// maintenance interfaces pre-wired. On non-`SucceedEntirely` status,
/// returns [`crate::ContractsError::DeployTxFailed`] and **no local
/// state is persisted** (signing key is not stored; private state is
/// not stored).
///
/// `executable` is taken as an [`Arc`] so the returned `call_tx` can
/// retain a reference — future circuit calls go through the same
/// executable instance.
pub async fn deploy_contract<W, R>(
    rng: &mut R,
    executable: Arc<IrExecutable<W>>,
    providers: Arc<ErasedProviders>,
    options: DeployOptions,
) -> Result<Contract<W>>
where
    W: Witnesses + 'static,
    R: Rng + CryptoRng,
{
    let private_state_id = options.persistent_state.as_ref().map(|(id, _)| id.clone());

    let deploy_tx_data = submit_deploy_tx(rng, executable.as_ref(), &providers, options).await?;

    let crate::tx_model::FinalizedDeployTxData {
        public:
            crate::tx_model::FinalizedDeployTxPublicData {
                finalized,
                contract_address,
                initial_contract_state,
            },
        private:
            crate::tx_model::UnsubmittedDeployTxPrivateData {
                signing_key,
                initial_private_state,
                initial_zswap_local_state,
                unproven_tx,
                new_coins,
            },
    } = deploy_tx_data;

    // Wire the typed interfaces bound to this contract address. The
    // maintenance-interfaces factory iterates over the executable's
    // `provable_circuit_ids` — matches TS `getProvableCircuitIds()`.
    let providers_for_ifaces = providers;
    let calls = ContractCalls::<W>::new(
        providers_for_ifaces.clone(),
        executable.clone(),
        contract_address,
        private_state_id,
    );
    let circuit_maintenance_tx = CircuitMaintenanceTxInterfaces::new(
        executable.provable_circuit_ids().into_iter().map(|id| {
            let iface = CircuitMaintenanceTx::new(
                providers_for_ifaces.clone(),
                contract_address,
                id.clone(),
            );
            (id, iface)
        }),
    );
    let contract_maintenance_tx =
        ContractMaintenanceTx::new(providers_for_ifaces, contract_address);

    Ok(Contract::Deployed {
        contract_address,
        initial_contract_state,
        signing_key,
        finalized_deploy_tx: finalized,
        calls,
        circuit_maintenance_tx,
        contract_maintenance_tx,
        initial_private_state,
        initial_zswap_local_state,
        unproven_tx,
        new_coins,
    })
}

// =====================================================================
// find_deployed_contract + verify_contract_state
// =====================================================================

/// Two [`VerifierKey`]s are equal iff they have the same length and
/// the same bytes. Port of TS `verifierKeysEqual`.
#[must_use]
pub fn verifier_keys_equal(a: &VerifierKey, b: &VerifierKey) -> bool {
    a.as_bytes() == b.as_bytes()
}

/// Verify that a [`ContractState`] has each circuit's verifier key
/// installed and equal to the caller-supplied key. Port of TS
/// `verifyContractState`.
///
/// The on-chain `ContractOperation` stores the verifier key in a
/// tagged-serialized form. We re-tagged-serialize the caller's local
/// bytes and compare — equality at that level implies byte-level
/// equality at the wire level, which is what the ledger's
/// [`ContractOperation`](moonproof_ledger::onchain_runtime::state::ContractOperation)
/// uses internally to validate contract calls.
///
/// # Errors
///
/// [`ContractsError::ContractType`] listing every circuit that's
/// missing from the on-chain state OR has a mismatched VK.
pub fn verify_contract_state(
    verifier_keys: &[(CircuitId, VerifierKey)],
    contract_state: &ContractState<InMemoryDB>,
) -> Result<()> {
    let mut mismatched: Vec<CircuitId> = Vec::new();
    for (circuit_id, local_vk) in verifier_keys {
        let entry: EntryPointBuf = circuit_id.as_str().as_bytes().into();
        let Some(op) = contract_state.operations.get(&entry) else {
            mismatched.push(circuit_id.clone());
            continue;
        };

        // Local VK bytes are the tagged-serialized form compactc
        // emits. To compare against the ledger's typed VK, we
        // tagged-deserialize ours and re-serialize the on-chain
        // one, then byte-compare. This matches TS
        // `verifierKeysEqual(localVk, contractState.operation(circuitId).verifierKey)`
        // behaviour at the byte level.
        let local_parsed: std::result::Result<
            moonproof_ledger::transient_crypto::proofs::VerifierKey,
            _,
        > = moonproof_ledger::serialize::tagged_deserialize(&mut local_vk.as_bytes());
        let Ok(local_parsed) = local_parsed else {
            mismatched.push(circuit_id.clone());
            continue;
        };

        // Compare the operation's own verifier key, not the operation's
        // serialized bytes. `VerifierKey` has no `PartialEq`, so the
        // comparison still goes through the serialized form — but of the
        // key alone.
        //
        // Serializing the whole `ContractOperation` and testing that it
        // *ends with* the key only worked because ledger 8's operation
        // holds a single `Option<VerifierKey>` and so trails with it.
        // Ledger 9's is `{ v2, v3, ir }`, whose bytes end with the `ir`
        // field, and the suffix test can never match there. `latest()`
        // returns the key for the current proof stack on both
        // generations, which is exactly the one to check.
        let Some(on_chain_vk) = op.latest() else {
            mismatched.push(circuit_id.clone());
            continue;
        };
        let mut local_bytes = Vec::new();
        let mut on_chain_bytes = Vec::new();
        if moonproof_ledger::serialize::Serializable::serialize(&local_parsed, &mut local_bytes)
            .is_err()
        {
            mismatched.push(circuit_id.clone());
            continue;
        }
        if moonproof_ledger::serialize::Serializable::serialize(on_chain_vk, &mut on_chain_bytes)
            .is_err()
        {
            mismatched.push(circuit_id.clone());
            continue;
        }
        if local_bytes != on_chain_bytes {
            mismatched.push(circuit_id.clone());
        }
    }

    if mismatched.is_empty() {
        Ok(())
    } else {
        // Tagged-serialize the on-chain state for diagnostics in the
        // error payload — lets the caller see exactly what was on
        // chain when the mismatch triggered.
        let mut state_bytes = Vec::new();
        moonproof_ledger::serialize::tagged_serialize(contract_state, &mut state_bytes).ok();
        Err(ContractRuntimeError::Contracts(
            ContractsError::contract_type(state_bytes, mismatched),
        ))
    }
}

/// Configuration for [`find_deployed_contract`]. Port of TS
/// `FindDeployedContractOptions<C>`.
pub struct FindDeployedContractOptions {
    pub contract_address: ContractAddress,
    /// If `Some`, the provided key is stored under the contract
    /// address. If `None`, and the provider already has a key, the
    /// existing key is kept. If `None` AND no key is stored, a fresh
    /// key is sampled and stored.
    pub signing_key: Option<SigningKey>,
    /// If `Some`, the call is private-state-aware: subsequent calls
    /// load private state from this id. `None` for stateless
    /// contracts.
    pub private_state_id: Option<PrivateStateId>,
    /// If `Some`, the provided bytes overwrite whatever's stored at
    /// `private_state_id` (requires `private_state_id.is_some()`).
    /// If `None`, the existing private state at `private_state_id` is
    /// kept. Port of TS
    /// `FindDeployedContractOptionsStorePrivateState`.
    pub initial_private_state_bytes: Option<Vec<u8>>,
}

/// Look up a deployed contract by address, verify its type matches
/// the caller's executable, and return a [`Contract::Found`] handle.
/// Port of TS `findDeployedContract`.
///
/// `executable` is taken as an [`Arc`] so the returned `call_tx` can
/// retain a reference for subsequent circuit calls — matches the TS
/// pattern of embedding `compiledContract` in the callTx interface.
pub async fn find_deployed_contract<W, R>(
    rng: &mut R,
    executable: Arc<IrExecutable<W>>,
    providers: Arc<ErasedProviders>,
    options: FindDeployedContractOptions,
) -> Result<Contract<W>>
where
    W: Witnesses + 'static,
    R: Rng + CryptoRng,
{
    providers
        .private_state
        .set_contract_address(&options.contract_address)
        .await?;

    // Wait for the deploy-tx data to appear on chain. Indefinite wait
    // matches TS contract.
    let finalized = providers
        .public_data
        .watch_for_deploy_tx_data(&options.contract_address)
        .await?;

    // Load the initial contract state (as recorded at deploy time).
    let initial_contract_state = providers
        .public_data
        .query_deploy_contract_state(&options.contract_address)
        .await?
        .ok_or_else(|| {
            ContractRuntimeError::NotFound(format!(
                "No contract deployed at contract address {}",
                moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
            ))
        })?;

    // Load the current contract state (which may have advanced past
    // the deploy).
    let current_contract_state = providers
        .public_data
        .query_contract_state(&options.contract_address, None)
        .await?
        .ok_or_else(|| {
            ContractRuntimeError::NotFound(format!(
                "No contract deployed at contract address {}",
                moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
            ))
        })?;

    // Verify the on-chain state carries every circuit's vk. Use the
    // executable's embedded VKs when available; fall back to the
    // zk-config provider otherwise.
    let mut verifier_keys: Vec<(CircuitId, VerifierKey)> = Vec::new();
    for id in executable.provable_circuit_ids() {
        let vk = match executable.embedded_verifier_key(&id) {
            Some(vk) => vk,
            None => providers.zk_config.get_verifier_key(&id).await?,
        };
        verifier_keys.push((id, vk));
    }
    verify_contract_state(&verifier_keys, &current_contract_state)?;

    // Resolve / rotate the signing key. Order matches TS:
    // 1. If caller provided one → store + use it.
    // 2. Else existing stored key → use it.
    // 3. Else sample fresh + store.
    let signing_key = match options.signing_key {
        Some(k) => {
            providers
                .private_state
                .set_signing_key(&options.contract_address, k.clone())
                .await?;
            k
        }
        None => {
            if let Some(k) = providers
                .private_state
                .get_signing_key(&options.contract_address)
                .await?
            {
                k
            } else {
                let mut bytes = [0u8; 32];
                rng.fill_bytes(&mut bytes);
                let k = moonproof_ledger::signatures::schnorr_signing_key(&bytes)
                    .expect("32 random bytes parse into a SigningKey");
                providers
                    .private_state
                    .set_signing_key(&options.contract_address, k.clone())
                    .await?;
                k
            }
        }
    };

    // Persist initial_private_state_bytes if the caller supplied one
    // alongside a private_state_id.
    if let (Some(psi), Some(bytes)) = (
        options.private_state_id.as_ref(),
        options.initial_private_state_bytes.as_ref(),
    ) {
        providers.private_state.set(psi, bytes.clone()).await?;
    }

    // Build the call + maintenance interfaces — mirrors TS
    // `createContractCallsInterface` etc. at the end of
    // `findDeployedContract`.
    let calls = ContractCalls::<W>::new(
        providers.clone(),
        executable.clone(),
        options.contract_address,
        options.private_state_id.clone(),
    );
    let circuit_maintenance_tx = CircuitMaintenanceTxInterfaces::new(
        executable.provable_circuit_ids().into_iter().map(|id| {
            (
                id.clone(),
                CircuitMaintenanceTx::new(providers.clone(), options.contract_address, id),
            )
        }),
    );
    let contract_maintenance_tx =
        ContractMaintenanceTx::new(providers.clone(), options.contract_address);

    Ok(Contract::Found {
        contract_address: options.contract_address,
        initial_contract_state,
        signing_key,
        finalized_deploy_tx: finalized,
        calls,
        circuit_maintenance_tx,
        contract_maintenance_tx,
    })
}

// =====================================================================
// Tests
// =====================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::{counter_ir_executable, counter_vk_bytes, scripted_providers};
    use crate::types::{CircuitId, PrivateStateId, TxStatus, VerifierKey};
    use moonproof_ledger::onchain_runtime::state::{
        ContractMaintenanceAuthority, ContractOperation, StateValue,
    };
    use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
    use moonproof_runtime_ir::RuntimeValue as Value;
    use rand::SeedableRng;

    // --- deploy_contract ---------------------------------------------

    fn baseline_options() -> DeployOptions {
        DeployOptions {
            constructor_args: Value::Null,
            initial_private_state: Value::Null,
            signing_key: None,
            additional_coin_enc_public_key_mappings: None,
            current_time: moonproof_ledger::base_crypto::time::Timestamp::from_secs(0),
            network_id: "local-test".to_owned(),
            persistent_state: None,
            fee_balancing: None,
            register_circuits: None,
        }
    }

    /// ports: `deploy-contract.test.ts::should deploy contract without private state`
    #[tokio::test]
    async fn deploys_without_private_state_and_samples_signing_key_when_absent() {
        let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
        let executable = Arc::new(counter_ir_executable().await);
        let mut rng = rand::rngs::StdRng::from_seed([0xD0u8; 32]);
        let deployed = Box::pin(deploy_contract(
            &mut rng,
            executable.clone(),
            Arc::new(providers),
            baseline_options(),
        ))
        .await
        .unwrap();

        assert_eq!(
            deployed.finalized_deploy_tx().status,
            TxStatus::SucceedEntirely
        );
        assert!(deployed
            .circuit_maintenance_tx()
            .get(&CircuitId::new("increment"))
            .is_some());
        assert_eq!(
            deployed.contract_maintenance_tx().contract_address(),
            deployed.contract_address(),
        );
        assert_eq!(ps.set_signing_key_calls.lock().unwrap().len(), 1);
    }

    /// ports: `deploy-contract.test.ts::should deploy contract with provided signing key`
    #[tokio::test]
    async fn deploys_with_caller_supplied_signing_key() {
        let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
        let executable = Arc::new(counter_ir_executable().await);
        let provided = moonproof_ledger::signatures::schnorr_signing_key(&[0x77u8; 32]).unwrap();
        let mut opts = baseline_options();
        opts.signing_key = Some(provided.clone());
        let mut rng = rand::rngs::StdRng::from_seed([0xD1u8; 32]);
        let deployed = Box::pin(deploy_contract(
            &mut rng,
            executable.clone(),
            Arc::new(providers),
            opts,
        ))
        .await
        .unwrap();
        assert_eq!(
            deployed.signing_key().verifying_key(),
            provided.verifying_key(),
        );
        let calls = ps.set_signing_key_calls.lock().unwrap();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].1.verifying_key(), provided.verifying_key());
    }

    /// ports: `deploy-contract.test.ts::should deploy contract with private state`
    #[tokio::test]
    async fn deploys_with_private_state_persists_under_id() {
        let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
        let executable = Arc::new(counter_ir_executable().await);
        let mut opts = baseline_options();
        opts.persistent_state = Some((PrivateStateId::new("counter"), b"seeded".to_vec()));
        let mut rng = rand::rngs::StdRng::from_seed([0xD2u8; 32]);
        Box::pin(deploy_contract(
            &mut rng,
            executable.clone(),
            Arc::new(providers),
            opts,
        ))
        .await
        .unwrap();
        assert_eq!(ps.set_signing_key_calls.lock().unwrap().len(), 1);
    }

    /// ports: `deploy-contract.test.ts::should deploy contract with both custom signing key and private state`
    #[tokio::test]
    async fn deploys_with_both_custom_signing_key_and_private_state() {
        let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
        let executable = Arc::new(counter_ir_executable().await);
        let provided = moonproof_ledger::signatures::schnorr_signing_key(&[0xB7u8; 32]).unwrap();
        let mut opts = baseline_options();
        opts.signing_key = Some(provided.clone());
        opts.persistent_state = Some((PrivateStateId::new("counter"), b"seeded".to_vec()));
        let mut rng = rand::rngs::StdRng::from_seed([0xD3u8; 32]);
        let deployed = Box::pin(deploy_contract(
            &mut rng,
            executable,
            Arc::new(providers),
            opts,
        ))
        .await
        .unwrap();
        assert_eq!(
            deployed.signing_key().verifying_key(),
            provided.verifying_key(),
        );
        let calls = ps.set_signing_key_calls.lock().unwrap();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].1.verifying_key(), provided.verifying_key());
    }

    // --- verify_contract_state --------------------------------------

    async fn counter_vk() -> VerifierKey {
        counter_vk_bytes().await
    }

    fn contract_state_with_operation(op: ContractOperation) -> ContractState<InMemoryDB> {
        let entry: EntryPointBuf = "increment".as_bytes().into();
        ContractState::<InMemoryDB>::new(
            StateValue::Null,
            StorageHashMap::new().insert(entry, op),
            ContractMaintenanceAuthority::default(),
        )
    }

    #[test]
    fn verifier_keys_equal_byte_comparison() {
        let a = VerifierKey::new(vec![1, 2, 3]);
        let b = VerifierKey::new(vec![1, 2, 3]);
        let c = VerifierKey::new(vec![1, 2, 4]);
        assert!(verifier_keys_equal(&a, &b));
        assert!(!verifier_keys_equal(&a, &c));
    }

    /// ports: `find-deployed-contract.test.ts::should find deployed contract without private state`
    #[tokio::test]
    async fn verify_contract_state_accepts_matching_vk() {
        let vk = counter_vk().await;
        let parsed: moonproof_ledger::transient_crypto::proofs::VerifierKey =
            moonproof_ledger::serialize::tagged_deserialize(&mut vk.as_bytes()).unwrap();
        let op = moonproof_ledger::contract_operation(Some(parsed));
        let state = contract_state_with_operation(op);
        verify_contract_state(&[(CircuitId::new("increment"), vk)], &state)
            .expect("matching vk should be accepted");
    }

    /// ports: `find-deployed-contract.test.ts::should throw error when contract is not found`
    #[tokio::test]
    async fn verify_contract_state_rejects_when_circuit_missing_from_state() {
        let vk = counter_vk().await;
        let state = ContractState::<InMemoryDB>::new(
            StateValue::Null,
            StorageHashMap::new(),
            ContractMaintenanceAuthority::default(),
        );
        let err = verify_contract_state(&[(CircuitId::new("increment"), vk)], &state).unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(ContractsError::ContractType { .. })
        );
    }

    #[tokio::test]
    async fn verify_contract_state_rejects_when_operation_has_no_vk() {
        let vk = counter_vk().await;
        let op_no_vk = moonproof_ledger::contract_operation(None);
        let state = contract_state_with_operation(op_no_vk);
        let err = verify_contract_state(&[(CircuitId::new("increment"), vk)], &state).unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(ContractsError::ContractType { .. })
        );
    }

    #[tokio::test]
    async fn verify_contract_state_lists_every_mismatched_circuit() {
        let vk = counter_vk().await;
        let state = ContractState::<InMemoryDB>::new(
            StateValue::Null,
            StorageHashMap::new(),
            ContractMaintenanceAuthority::default(),
        );
        let err = verify_contract_state(
            &[
                (CircuitId::new("a"), vk.clone()),
                (CircuitId::new("b"), vk.clone()),
                (CircuitId::new("c"), vk),
            ],
            &state,
        )
        .unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains('a') && msg.contains('b') && msg.contains('c'),
            "{msg}"
        );
    }
}