#![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,
};
#[must_use]
pub fn dummy_address() -> ContractAddress {
ContractAddress(HashOutput([0x77u8; 32]))
}
#[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,
},
)
}
#[derive(Debug)]
pub struct ScriptedPublicData {
pub state: Option<ContractState<InMemoryDB>>,
pub status: TxStatus,
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")
}
}
#[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!()
}
}
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
}
}
#[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))
}
}
#[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])
}
}
#[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"))
}
}
#[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")
}
}
#[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)
}
#[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)
}
#[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
}
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()
}
#[must_use]
pub fn counter_ir_path() -> std::path::PathBuf {
let mut p = counter_fixture_root();
p.push("contract.mpir");
p
}
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)
}
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
}