1use std::sync::Arc;
22
23use moonproof_ledger::coin_structure::coin::Info as ShieldedCoinInfo;
24use moonproof_ledger::coin_structure::contract::ContractAddress;
25use moonproof_ledger::onchain_runtime::state::{ContractState, EntryPointBuf};
26use moonproof_ledger::signatures::SigningKey;
27use moonproof_ledger::storage::db::InMemoryDB;
28use moonproof_runtime::ir::witnesses::Witnesses;
29use moonproof_runtime::ir_executable::IrExecutable;
30use moonproof_runtime_ir::RuntimeValue;
31use rand::{CryptoRng, Rng};
32
33use crate::error::{ContractRuntimeError, ContractsError, Result};
34use crate::providers::ErasedProviders;
35use crate::submit_deploy_tx::submit_deploy_tx;
36use crate::tx_interfaces::{
37 CallOptions, CircuitMaintenanceTx, CircuitMaintenanceTxInterfaces, ContractCalls,
38 ContractMaintenanceTx,
39};
40use crate::tx_phase::UnprovenTx;
41use crate::types::{CircuitId, FinalizedTxData, PrivateStateId, VerifierKey};
42pub use crate::unproven_deploy_tx::DeployOptions;
43use crate::utils::zswap_utils::CompactZswapLocalState;
44
45#[allow(clippy::large_enum_variant)]
71pub enum Contract<W: Witnesses + 'static> {
72 Deployed {
73 contract_address: ContractAddress,
74 initial_contract_state: ContractState<InMemoryDB>,
75 signing_key: SigningKey,
76 finalized_deploy_tx: FinalizedTxData,
77 calls: ContractCalls<W>,
78 circuit_maintenance_tx: CircuitMaintenanceTxInterfaces,
79 contract_maintenance_tx: ContractMaintenanceTx,
80 initial_private_state: RuntimeValue,
81 initial_zswap_local_state: CompactZswapLocalState,
82 unproven_tx: Option<UnprovenTx>,
83 new_coins: Vec<ShieldedCoinInfo>,
84 },
85 Found {
86 contract_address: ContractAddress,
87 initial_contract_state: ContractState<InMemoryDB>,
88 signing_key: SigningKey,
89 finalized_deploy_tx: FinalizedTxData,
90 calls: ContractCalls<W>,
91 circuit_maintenance_tx: CircuitMaintenanceTxInterfaces,
92 contract_maintenance_tx: ContractMaintenanceTx,
93 },
94}
95
96impl<W: Witnesses + 'static> Contract<W> {
97 #[inline]
99 #[must_use]
100 pub fn contract_address(&self) -> &ContractAddress {
101 match self {
102 Self::Deployed {
103 contract_address, ..
104 }
105 | Self::Found {
106 contract_address, ..
107 } => contract_address,
108 }
109 }
110
111 #[inline]
114 #[must_use]
115 pub fn initial_contract_state(&self) -> &ContractState<InMemoryDB> {
116 match self {
117 Self::Deployed {
118 initial_contract_state,
119 ..
120 }
121 | Self::Found {
122 initial_contract_state,
123 ..
124 } => initial_contract_state,
125 }
126 }
127
128 #[inline]
132 #[must_use]
133 pub fn signing_key(&self) -> &SigningKey {
134 match self {
135 Self::Deployed { signing_key, .. } | Self::Found { signing_key, .. } => signing_key,
136 }
137 }
138
139 #[inline]
144 #[must_use]
145 pub fn finalized_deploy_tx(&self) -> &FinalizedTxData {
146 match self {
147 Self::Deployed {
148 finalized_deploy_tx,
149 ..
150 }
151 | Self::Found {
152 finalized_deploy_tx,
153 ..
154 } => finalized_deploy_tx,
155 }
156 }
157
158 #[inline]
163 #[must_use]
164 pub fn calls(&self) -> &ContractCalls<W> {
165 match self {
166 Self::Deployed { calls, .. } | Self::Found { calls, .. } => calls,
167 }
168 }
169
170 pub async fn call<R>(
180 &self,
181 rng: &mut R,
182 circuit_id: impl Into<CircuitId>,
183 args: RuntimeValue,
184 options: CallOptions,
185 ) -> Result<crate::tx_model::FinalizedCallTxData>
186 where
187 R: Rng + CryptoRng,
188 {
189 self.calls().call(rng, circuit_id, args, options).await
190 }
191
192 #[inline]
194 #[must_use]
195 pub fn circuit_maintenance_tx(&self) -> &CircuitMaintenanceTxInterfaces {
196 match self {
197 Self::Deployed {
198 circuit_maintenance_tx,
199 ..
200 }
201 | Self::Found {
202 circuit_maintenance_tx,
203 ..
204 } => circuit_maintenance_tx,
205 }
206 }
207
208 #[inline]
210 #[must_use]
211 pub fn contract_maintenance_tx(&self) -> &ContractMaintenanceTx {
212 match self {
213 Self::Deployed {
214 contract_maintenance_tx,
215 ..
216 }
217 | Self::Found {
218 contract_maintenance_tx,
219 ..
220 } => contract_maintenance_tx,
221 }
222 }
223
224 #[inline]
228 #[must_use]
229 pub const fn is_deployed(&self) -> bool {
230 matches!(self, Self::Deployed { .. })
231 }
232
233 #[inline]
235 #[must_use]
236 pub const fn is_found(&self) -> bool {
237 matches!(self, Self::Found { .. })
238 }
239}
240
241pub async fn deploy_contract<W, R>(
264 rng: &mut R,
265 executable: Arc<IrExecutable<W>>,
266 providers: Arc<ErasedProviders>,
267 options: DeployOptions,
268) -> Result<Contract<W>>
269where
270 W: Witnesses + 'static,
271 R: Rng + CryptoRng,
272{
273 let private_state_id = options.persistent_state.as_ref().map(|(id, _)| id.clone());
274
275 let deploy_tx_data = submit_deploy_tx(rng, executable.as_ref(), &providers, options).await?;
276
277 let crate::tx_model::FinalizedDeployTxData {
278 public:
279 crate::tx_model::FinalizedDeployTxPublicData {
280 finalized,
281 contract_address,
282 initial_contract_state,
283 },
284 private:
285 crate::tx_model::UnsubmittedDeployTxPrivateData {
286 signing_key,
287 initial_private_state,
288 initial_zswap_local_state,
289 unproven_tx,
290 new_coins,
291 },
292 } = deploy_tx_data;
293
294 let providers_for_ifaces = providers;
298 let calls = ContractCalls::<W>::new(
299 providers_for_ifaces.clone(),
300 executable.clone(),
301 contract_address,
302 private_state_id,
303 );
304 let circuit_maintenance_tx = CircuitMaintenanceTxInterfaces::new(
305 executable.provable_circuit_ids().into_iter().map(|id| {
306 let iface = CircuitMaintenanceTx::new(
307 providers_for_ifaces.clone(),
308 contract_address,
309 id.clone(),
310 );
311 (id, iface)
312 }),
313 );
314 let contract_maintenance_tx =
315 ContractMaintenanceTx::new(providers_for_ifaces, contract_address);
316
317 Ok(Contract::Deployed {
318 contract_address,
319 initial_contract_state,
320 signing_key,
321 finalized_deploy_tx: finalized,
322 calls,
323 circuit_maintenance_tx,
324 contract_maintenance_tx,
325 initial_private_state,
326 initial_zswap_local_state,
327 unproven_tx,
328 new_coins,
329 })
330}
331
332#[must_use]
339pub fn verifier_keys_equal(a: &VerifierKey, b: &VerifierKey) -> bool {
340 a.as_bytes() == b.as_bytes()
341}
342
343pub fn verify_contract_state(
359 verifier_keys: &[(CircuitId, VerifierKey)],
360 contract_state: &ContractState<InMemoryDB>,
361) -> Result<()> {
362 let mut mismatched: Vec<CircuitId> = Vec::new();
363 for (circuit_id, local_vk) in verifier_keys {
364 let entry: EntryPointBuf = circuit_id.as_str().as_bytes().into();
365 let Some(op) = contract_state.operations.get(&entry) else {
366 mismatched.push(circuit_id.clone());
367 continue;
368 };
369
370 let local_parsed: std::result::Result<
377 moonproof_ledger::transient_crypto::proofs::VerifierKey,
378 _,
379 > = moonproof_ledger::serialize::tagged_deserialize(&mut local_vk.as_bytes());
380 let Ok(local_parsed) = local_parsed else {
381 mismatched.push(circuit_id.clone());
382 continue;
383 };
384
385 let Some(on_chain_vk) = op.latest() else {
398 mismatched.push(circuit_id.clone());
399 continue;
400 };
401 let mut local_bytes = Vec::new();
402 let mut on_chain_bytes = Vec::new();
403 if moonproof_ledger::serialize::Serializable::serialize(&local_parsed, &mut local_bytes)
404 .is_err()
405 {
406 mismatched.push(circuit_id.clone());
407 continue;
408 }
409 if moonproof_ledger::serialize::Serializable::serialize(on_chain_vk, &mut on_chain_bytes)
410 .is_err()
411 {
412 mismatched.push(circuit_id.clone());
413 continue;
414 }
415 if local_bytes != on_chain_bytes {
416 mismatched.push(circuit_id.clone());
417 }
418 }
419
420 if mismatched.is_empty() {
421 Ok(())
422 } else {
423 let mut state_bytes = Vec::new();
427 moonproof_ledger::serialize::tagged_serialize(contract_state, &mut state_bytes).ok();
428 Err(ContractRuntimeError::Contracts(
429 ContractsError::contract_type(state_bytes, mismatched),
430 ))
431 }
432}
433
434pub struct FindDeployedContractOptions {
437 pub contract_address: ContractAddress,
438 pub signing_key: Option<SigningKey>,
443 pub private_state_id: Option<PrivateStateId>,
447 pub initial_private_state_bytes: Option<Vec<u8>>,
453}
454
455pub async fn find_deployed_contract<W, R>(
463 rng: &mut R,
464 executable: Arc<IrExecutable<W>>,
465 providers: Arc<ErasedProviders>,
466 options: FindDeployedContractOptions,
467) -> Result<Contract<W>>
468where
469 W: Witnesses + 'static,
470 R: Rng + CryptoRng,
471{
472 providers
473 .private_state
474 .set_contract_address(&options.contract_address)
475 .await?;
476
477 let finalized = providers
480 .public_data
481 .watch_for_deploy_tx_data(&options.contract_address)
482 .await?;
483
484 let initial_contract_state = providers
486 .public_data
487 .query_deploy_contract_state(&options.contract_address)
488 .await?
489 .ok_or_else(|| {
490 ContractRuntimeError::NotFound(format!(
491 "No contract deployed at contract address {}",
492 moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
493 ))
494 })?;
495
496 let current_contract_state = providers
499 .public_data
500 .query_contract_state(&options.contract_address, None)
501 .await?
502 .ok_or_else(|| {
503 ContractRuntimeError::NotFound(format!(
504 "No contract deployed at contract address {}",
505 moonproof_runtime::state::contract_address_to_hex(&options.contract_address),
506 ))
507 })?;
508
509 let mut verifier_keys: Vec<(CircuitId, VerifierKey)> = Vec::new();
513 for id in executable.provable_circuit_ids() {
514 let vk = match executable.embedded_verifier_key(&id) {
515 Some(vk) => vk,
516 None => providers.zk_config.get_verifier_key(&id).await?,
517 };
518 verifier_keys.push((id, vk));
519 }
520 verify_contract_state(&verifier_keys, ¤t_contract_state)?;
521
522 let signing_key = match options.signing_key {
527 Some(k) => {
528 providers
529 .private_state
530 .set_signing_key(&options.contract_address, k.clone())
531 .await?;
532 k
533 }
534 None => {
535 if let Some(k) = providers
536 .private_state
537 .get_signing_key(&options.contract_address)
538 .await?
539 {
540 k
541 } else {
542 let mut bytes = [0u8; 32];
543 rng.fill_bytes(&mut bytes);
544 let k = moonproof_ledger::signatures::schnorr_signing_key(&bytes)
545 .expect("32 random bytes parse into a SigningKey");
546 providers
547 .private_state
548 .set_signing_key(&options.contract_address, k.clone())
549 .await?;
550 k
551 }
552 }
553 };
554
555 if let (Some(psi), Some(bytes)) = (
558 options.private_state_id.as_ref(),
559 options.initial_private_state_bytes.as_ref(),
560 ) {
561 providers.private_state.set(psi, bytes.clone()).await?;
562 }
563
564 let calls = ContractCalls::<W>::new(
568 providers.clone(),
569 executable.clone(),
570 options.contract_address,
571 options.private_state_id.clone(),
572 );
573 let circuit_maintenance_tx = CircuitMaintenanceTxInterfaces::new(
574 executable.provable_circuit_ids().into_iter().map(|id| {
575 (
576 id.clone(),
577 CircuitMaintenanceTx::new(providers.clone(), options.contract_address, id),
578 )
579 }),
580 );
581 let contract_maintenance_tx =
582 ContractMaintenanceTx::new(providers.clone(), options.contract_address);
583
584 Ok(Contract::Found {
585 contract_address: options.contract_address,
586 initial_contract_state,
587 signing_key,
588 finalized_deploy_tx: finalized,
589 calls,
590 circuit_maintenance_tx,
591 contract_maintenance_tx,
592 })
593}
594
595#[cfg(test)]
600mod tests {
601 use super::*;
602 use crate::test_helpers::{counter_ir_executable, counter_vk_bytes, scripted_providers};
603 use crate::types::{CircuitId, PrivateStateId, TxStatus, VerifierKey};
604 use moonproof_ledger::onchain_runtime::state::{
605 ContractMaintenanceAuthority, ContractOperation, StateValue,
606 };
607 use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
608 use moonproof_runtime_ir::RuntimeValue as Value;
609 use rand::SeedableRng;
610
611 fn baseline_options() -> DeployOptions {
614 DeployOptions {
615 constructor_args: Value::Null,
616 initial_private_state: Value::Null,
617 signing_key: None,
618 additional_coin_enc_public_key_mappings: None,
619 current_time: moonproof_ledger::base_crypto::time::Timestamp::from_secs(0),
620 network_id: "local-test".to_owned(),
621 persistent_state: None,
622 fee_balancing: None,
623 register_circuits: None,
624 }
625 }
626
627 #[tokio::test]
629 async fn deploys_without_private_state_and_samples_signing_key_when_absent() {
630 let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
631 let executable = Arc::new(counter_ir_executable().await);
632 let mut rng = rand::rngs::StdRng::from_seed([0xD0u8; 32]);
633 let deployed = Box::pin(deploy_contract(
634 &mut rng,
635 executable.clone(),
636 Arc::new(providers),
637 baseline_options(),
638 ))
639 .await
640 .unwrap();
641
642 assert_eq!(
643 deployed.finalized_deploy_tx().status,
644 TxStatus::SucceedEntirely
645 );
646 assert!(deployed
647 .circuit_maintenance_tx()
648 .get(&CircuitId::new("increment"))
649 .is_some());
650 assert_eq!(
651 deployed.contract_maintenance_tx().contract_address(),
652 deployed.contract_address(),
653 );
654 assert_eq!(ps.set_signing_key_calls.lock().unwrap().len(), 1);
655 }
656
657 #[tokio::test]
659 async fn deploys_with_caller_supplied_signing_key() {
660 let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
661 let executable = Arc::new(counter_ir_executable().await);
662 let provided = moonproof_ledger::signatures::schnorr_signing_key(&[0x77u8; 32]).unwrap();
663 let mut opts = baseline_options();
664 opts.signing_key = Some(provided.clone());
665 let mut rng = rand::rngs::StdRng::from_seed([0xD1u8; 32]);
666 let deployed = Box::pin(deploy_contract(
667 &mut rng,
668 executable.clone(),
669 Arc::new(providers),
670 opts,
671 ))
672 .await
673 .unwrap();
674 assert_eq!(
675 deployed.signing_key().verifying_key(),
676 provided.verifying_key(),
677 );
678 let calls = ps.set_signing_key_calls.lock().unwrap();
679 assert_eq!(calls.len(), 1);
680 assert_eq!(calls[0].1.verifying_key(), provided.verifying_key());
681 }
682
683 #[tokio::test]
685 async fn deploys_with_private_state_persists_under_id() {
686 let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
687 let executable = Arc::new(counter_ir_executable().await);
688 let mut opts = baseline_options();
689 opts.persistent_state = Some((PrivateStateId::new("counter"), b"seeded".to_vec()));
690 let mut rng = rand::rngs::StdRng::from_seed([0xD2u8; 32]);
691 Box::pin(deploy_contract(
692 &mut rng,
693 executable.clone(),
694 Arc::new(providers),
695 opts,
696 ))
697 .await
698 .unwrap();
699 assert_eq!(ps.set_signing_key_calls.lock().unwrap().len(), 1);
700 }
701
702 #[tokio::test]
704 async fn deploys_with_both_custom_signing_key_and_private_state() {
705 let (providers, ps) = scripted_providers(None, None, TxStatus::SucceedEntirely);
706 let executable = Arc::new(counter_ir_executable().await);
707 let provided = moonproof_ledger::signatures::schnorr_signing_key(&[0xB7u8; 32]).unwrap();
708 let mut opts = baseline_options();
709 opts.signing_key = Some(provided.clone());
710 opts.persistent_state = Some((PrivateStateId::new("counter"), b"seeded".to_vec()));
711 let mut rng = rand::rngs::StdRng::from_seed([0xD3u8; 32]);
712 let deployed = Box::pin(deploy_contract(
713 &mut rng,
714 executable,
715 Arc::new(providers),
716 opts,
717 ))
718 .await
719 .unwrap();
720 assert_eq!(
721 deployed.signing_key().verifying_key(),
722 provided.verifying_key(),
723 );
724 let calls = ps.set_signing_key_calls.lock().unwrap();
725 assert_eq!(calls.len(), 1);
726 assert_eq!(calls[0].1.verifying_key(), provided.verifying_key());
727 }
728
729 async fn counter_vk() -> VerifierKey {
732 counter_vk_bytes().await
733 }
734
735 fn contract_state_with_operation(op: ContractOperation) -> ContractState<InMemoryDB> {
736 let entry: EntryPointBuf = "increment".as_bytes().into();
737 ContractState::<InMemoryDB>::new(
738 StateValue::Null,
739 StorageHashMap::new().insert(entry, op),
740 ContractMaintenanceAuthority::default(),
741 )
742 }
743
744 #[test]
745 fn verifier_keys_equal_byte_comparison() {
746 let a = VerifierKey::new(vec![1, 2, 3]);
747 let b = VerifierKey::new(vec![1, 2, 3]);
748 let c = VerifierKey::new(vec![1, 2, 4]);
749 assert!(verifier_keys_equal(&a, &b));
750 assert!(!verifier_keys_equal(&a, &c));
751 }
752
753 #[tokio::test]
755 async fn verify_contract_state_accepts_matching_vk() {
756 let vk = counter_vk().await;
757 let parsed: moonproof_ledger::transient_crypto::proofs::VerifierKey =
758 moonproof_ledger::serialize::tagged_deserialize(&mut vk.as_bytes()).unwrap();
759 let op = moonproof_ledger::contract_operation(Some(parsed));
760 let state = contract_state_with_operation(op);
761 verify_contract_state(&[(CircuitId::new("increment"), vk)], &state)
762 .expect("matching vk should be accepted");
763 }
764
765 #[tokio::test]
767 async fn verify_contract_state_rejects_when_circuit_missing_from_state() {
768 let vk = counter_vk().await;
769 let state = ContractState::<InMemoryDB>::new(
770 StateValue::Null,
771 StorageHashMap::new(),
772 ContractMaintenanceAuthority::default(),
773 );
774 let err = verify_contract_state(&[(CircuitId::new("increment"), vk)], &state).unwrap_err();
775 matches!(
776 err,
777 ContractRuntimeError::Contracts(ContractsError::ContractType { .. })
778 );
779 }
780
781 #[tokio::test]
782 async fn verify_contract_state_rejects_when_operation_has_no_vk() {
783 let vk = counter_vk().await;
784 let op_no_vk = moonproof_ledger::contract_operation(None);
785 let state = contract_state_with_operation(op_no_vk);
786 let err = verify_contract_state(&[(CircuitId::new("increment"), vk)], &state).unwrap_err();
787 matches!(
788 err,
789 ContractRuntimeError::Contracts(ContractsError::ContractType { .. })
790 );
791 }
792
793 #[tokio::test]
794 async fn verify_contract_state_lists_every_mismatched_circuit() {
795 let vk = counter_vk().await;
796 let state = ContractState::<InMemoryDB>::new(
797 StateValue::Null,
798 StorageHashMap::new(),
799 ContractMaintenanceAuthority::default(),
800 );
801 let err = verify_contract_state(
802 &[
803 (CircuitId::new("a"), vk.clone()),
804 (CircuitId::new("b"), vk.clone()),
805 (CircuitId::new("c"), vk),
806 ],
807 &state,
808 )
809 .unwrap_err();
810 let msg = format!("{err}");
811 assert!(
812 msg.contains('a') && msg.contains('b') && msg.contains('c'),
813 "{msg}"
814 );
815 }
816}