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;
#[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> {
#[inline]
#[must_use]
pub fn contract_address(&self) -> &ContractAddress {
match self {
Self::Deployed {
contract_address, ..
}
| Self::Found {
contract_address, ..
} => contract_address,
}
}
#[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,
}
}
#[inline]
#[must_use]
pub fn signing_key(&self) -> &SigningKey {
match self {
Self::Deployed { signing_key, .. } | Self::Found { signing_key, .. } => signing_key,
}
}
#[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,
}
}
#[inline]
#[must_use]
pub fn calls(&self) -> &ContractCalls<W> {
match self {
Self::Deployed { calls, .. } | Self::Found { calls, .. } => calls,
}
}
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
}
#[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,
}
}
#[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,
}
}
#[inline]
#[must_use]
pub const fn is_deployed(&self) -> bool {
matches!(self, Self::Deployed { .. })
}
#[inline]
#[must_use]
pub const fn is_found(&self) -> bool {
matches!(self, Self::Found { .. })
}
}
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;
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,
})
}
#[must_use]
pub fn verifier_keys_equal(a: &VerifierKey, b: &VerifierKey) -> bool {
a.as_bytes() == b.as_bytes()
}
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;
};
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;
};
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 {
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),
))
}
}
pub struct FindDeployedContractOptions {
pub contract_address: ContractAddress,
pub signing_key: Option<SigningKey>,
pub private_state_id: Option<PrivateStateId>,
pub initial_private_state_bytes: Option<Vec<u8>>,
}
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?;
let finalized = providers
.public_data
.watch_for_deploy_tx_data(&options.contract_address)
.await?;
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),
))
})?;
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),
))
})?;
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, ¤t_contract_state)?;
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
}
}
};
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?;
}
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,
})
}
#[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;
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,
}
}
#[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);
}
#[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());
}
#[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);
}
#[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());
}
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));
}
#[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");
}
#[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}"
);
}
}