use std::collections::HashMap;
use std::sync::Arc;
use moonproof_ledger::ledger::structure::{ProofPreimageMarker, Transaction};
use moonproof_ledger::signatures::Signature;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::transient_crypto::commitment::PedersenRandomness;
use moonproof_ledger::transient_crypto::proofs::ProvingKeyMaterial;
use moonproof_macros::async_trait;
use crate::error::Result;
use crate::providers::zk_config::ZkConfigProvider;
use crate::tx_phase::{ProvenTx, UnprovenTx};
#[derive(Debug, Clone, Default)]
pub struct ProveTxConfig {
pub timeout_ms: Option<u64>,
}
#[async_trait]
pub trait ProofProvider: Send + Sync + std::fmt::Debug {
async fn prove_tx(&self, tx: UnprovenTx, config: &ProveTxConfig) -> Result<ProvenTx>;
}
#[async_trait]
impl<T: ProofProvider + ?Sized> ProofProvider for std::sync::Arc<T> {
async fn prove_tx(&self, tx: UnprovenTx, config: &ProveTxConfig) -> Result<ProvenTx> {
(**self).prove_tx(tx, config).await
}
}
#[async_trait]
impl<T: ProofProvider + ?Sized> ProofProvider for Box<T> {
async fn prove_tx(&self, tx: UnprovenTx, config: &ProveTxConfig) -> Result<ProvenTx> {
(**self).prove_tx(tx, config).await
}
}
pub(crate) async fn collect_contract_key_materials(
tx: &Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
zk_configs: &[Arc<dyn ZkConfigProvider>],
) -> Result<HashMap<String, ProvingKeyMaterial>> {
if zk_configs.is_empty() {
return Ok(HashMap::new());
}
let locations = contract_call_key_locations(tx);
if locations.is_empty() {
return Ok(HashMap::new());
}
let sources: Vec<&dyn ZkConfigProvider> = zk_configs.iter().map(AsRef::as_ref).collect();
let resolved = futures::future::try_join_all(locations.into_iter().map(|location| {
let sources = &sources;
async move {
let material = crate::key_location::resolve_key_location(&location, sources).await?;
Ok::<_, crate::error::ContractRuntimeError>(material.map(|m| (location, m)))
}
}))
.await?;
let mut out = HashMap::with_capacity(resolved.len());
for pair in resolved.into_iter().flatten() {
out.insert(pair.0, pair.1);
}
Ok(out)
}
fn contract_call_key_locations(
tx: &Transaction<Signature, ProofPreimageMarker, PedersenRandomness, InMemoryDB>,
) -> Vec<String> {
use moonproof_ledger::ledger::structure::{
ContractAction, ProofPreimageVersioned, Transaction as LedgerTx,
};
let mut seen = std::collections::HashSet::<String>::new();
let mut out = Vec::new();
if let LedgerTx::Standard(stx) = tx {
for pair in stx.intents.iter() {
let (_seg, intent) = &*pair;
for action in intent.actions.iter_deref() {
if let ContractAction::Call(call) = action {
let ProofPreimageVersioned::V2(preimage) = &call.proof else {
continue;
};
let location = preimage.key_location.0.to_string();
if seen.insert(location.clone()) {
out.push(location);
}
}
}
}
}
out
}