use std::sync::Arc;
use std::time::Duration as StdDuration;
use anyhow::{anyhow, Context, Result};
use moonproof_indexer_client::HttpIndexerClient;
use moonproof_ledger::ledger::dust::DustSecretKey;
use moonproof_node_client::SubmissionStage;
use tokio::sync::{Mutex, RwLock};
use crate::connector::{
self, Configuration, DesiredInput, DesiredOutput, DustBalance, HistoryEntry, MakeIntentOptions,
SignDataOptions, WalletAddresses,
};
use crate::facade::{
balance_sealed_recipe, balance_unbound_recipe, build_transfer_recipe, ended_transaction_result,
init_swap, serialize_finalized, sign_recipe, FacadeState, FinalizedTransaction,
FinalizedTransactionRecipe, ProvenTransaction, SubmissionEnd, SubmissionWatch, SwapOptions,
TransferOptions, TransferSigningKeys, UnprovenTransaction, UnprovenTransactionRecipe,
};
use crate::pending_tx::{
InMemoryPendingTransactionsStorage, PendingTransactionEntry, PendingTransactionResult,
PendingTransactionStatus, PendingTransactionsStorage,
};
use crate::signing::SignedDataOutput;
use crate::tx_history::{
InMemoryTransactionHistoryStorage, TransactionHistoryEntry, TransactionHistoryStatus,
TransactionHistoryStorage,
};
use crate::{Wallet, WalletError};
use super::{
drain_wallet_sync, finalize_with_backend, sync_wallet_fresh, ttl_from, ProvingBackend,
WalletSession, TRANSACTION_TTL_SECS,
};
const FOLLOW_LIMIT: StdDuration = StdDuration::from_secs(2 * TRANSACTION_TTL_SECS);
pub async fn seal_unbound(
facade: FacadeState,
base: ProvenTransaction,
wallet: &Wallet,
pay_fees: bool,
backend: &ProvingBackend,
) -> Result<(FacadeState, FinalizedTransaction)> {
let zswap = wallet.zswap_secret_keys();
let dust = wallet.dust_secret_key();
let options = balancing_options(&facade, pay_fees);
let (recipe, booked) = balance_unbound_recipe(
&mut rand::rngs::OsRng,
facade,
base,
&signing_keys(wallet, &zswap, &dust),
&options,
)
.map_err(anyhow::Error::new)?;
let leg = prove_leg(recipe.balancing.clone(), backend).await?;
let sealed = recipe.complete(leg).map_err(anyhow::Error::new)?;
Ok((booked, sealed))
}
pub async fn pay_sealed(
facade: FacadeState,
original: FinalizedTransaction,
wallet: &Wallet,
pay_fees: bool,
backend: &ProvingBackend,
) -> Result<(FacadeState, FinalizedTransaction)> {
let zswap = wallet.zswap_secret_keys();
let dust = wallet.dust_secret_key();
let options = balancing_options(&facade, pay_fees);
let (recipe, booked) = balance_sealed_recipe(
&mut rand::rngs::OsRng,
facade,
original,
&signing_keys(wallet, &zswap, &dust),
&options,
)
.map_err(anyhow::Error::new)?;
let leg = prove_leg(recipe.balancing.clone(), backend).await?;
let paid = recipe.complete(leg).map_err(anyhow::Error::new)?;
Ok((booked, paid))
}
fn balancing_options(facade: &FacadeState, pay_fees: bool) -> TransferOptions {
let now = facade.chain_tip_ts();
TransferOptions {
ttl: ttl_from(now),
current_time: now,
pay_fees,
}
}
fn signing_keys<'a>(
wallet: &'a Wallet,
zswap: &'a moonproof_ledger::zswap::keys::SecretKeys,
dust: &'a DustSecretKey,
) -> TransferSigningKeys<'a> {
TransferSigningKeys {
shielded_secret_keys: zswap,
dust_secret_key: dust,
night_signing_key: &wallet.signing_key,
night_verifying_key: &wallet.verifying_key,
sender_owner: wallet.owner_bytes(),
}
}
async fn prove_leg(
leg: Option<UnprovenTransaction>,
backend: &ProvingBackend,
) -> Result<Option<FinalizedTransaction>> {
let Some(transaction) = leg else {
return Ok(None);
};
let proven = finalize_with_backend(UnprovenTransactionRecipe { transaction }, backend)
.await
.context("prove the balancing leg")?;
Ok(Some(proven.transaction))
}
pub fn sealed_bytes(transaction: FinalizedTransaction) -> Result<Vec<u8>> {
serialize_finalized(&FinalizedTransactionRecipe { transaction }).map_err(anyhow::Error::new)
}
pub struct ConnectedWallet {
session: WalletSession,
backend: ProvingBackend,
facade: RwLock<FacadeState>,
spend: Mutex<()>,
pending: InMemoryPendingTransactionsStorage,
history: InMemoryTransactionHistoryStorage,
}
impl ConnectedWallet {
pub async fn open(session: WalletSession, backend: ProvingBackend) -> Result<Arc<Self>> {
let facade = Box::pin(sync_wallet_fresh(&session)).await?;
Ok(Arc::new(Self {
session,
backend,
facade: RwLock::new(facade),
spend: Mutex::new(()),
pending: InMemoryPendingTransactionsStorage::new(),
history: InMemoryTransactionHistoryStorage::new(),
}))
}
pub async fn sync(&self) -> Result<()> {
let prior = self.facade.read().await.clone();
let (_, drained) = Box::pin(drain_wallet_sync(&self.session, Some(prior))).await?;
let _spend = self.spend.lock().await;
let current = self.facade.read().await.clone();
let folded = drained.fold_into(current, &self.session.wallet)?;
*self.facade.write().await = folded;
Ok(())
}
pub async fn facade(&self) -> FacadeState {
self.facade.read().await.clone()
}
#[must_use]
pub const fn session(&self) -> &WalletSession {
&self.session
}
#[must_use]
pub fn configuration(&self) -> Configuration {
let prover = match &self.backend {
ProvingBackend::InProcess => None,
ProvingBackend::HttpServer { base_url } => Some(base_url.clone()),
};
Configuration::of(&self.session.network, prover)
}
pub fn addresses(&self) -> crate::Result<WalletAddresses> {
connector::addresses(&self.session.wallet)
}
pub async fn shielded_balances(&self) -> std::collections::BTreeMap<String, u128> {
connector::shielded_balances(
&*self.facade.read().await,
&self.session.wallet.zswap_secret_keys(),
)
}
pub async fn unshielded_balances(
&self,
) -> crate::Result<std::collections::BTreeMap<String, u128>> {
connector::unshielded_balances(&*self.facade.read().await)
}
pub async fn dust_balance(&self) -> DustBalance {
let facade = self.facade.read().await;
connector::dust_balance(&facade, facade.chain_tip_ts())
}
pub async fn tx_history(&self, page: u32, page_size: u32) -> crate::Result<Vec<HistoryEntry>> {
let pending = self.pending.get_all().await?;
let history = self.history.get_all().await?;
Ok(connector::history_page(&pending, &history, page, page_size))
}
pub fn sign_data(
&self,
data: &str,
options: &SignDataOptions,
) -> crate::Result<SignedDataOutput> {
connector::sign_data(&self.session.wallet.signing_key, data, options)
}
fn keys<'a>(
&'a self,
zswap: &'a moonproof_ledger::zswap::keys::SecretKeys,
dust: &'a DustSecretKey,
) -> TransferSigningKeys<'a> {
signing_keys(&self.session.wallet, zswap, dust)
}
async fn prove_and_book(
&self,
recipe: UnprovenTransactionRecipe,
booked: FacadeState,
) -> Result<Vec<u8>> {
let signed = sign_recipe(
recipe,
&self.session.wallet.signing_key,
&mut rand::rngs::OsRng,
)
.map_err(anyhow::Error::new)?;
let finalized = finalize_with_backend(signed, &self.backend).await?;
let bytes = serialize_finalized(&finalized).map_err(anyhow::Error::new)?;
*self.facade.write().await = booked;
Ok(bytes)
}
pub async fn make_transfer(
&self,
outputs: &[DesiredOutput],
pay_fees: bool,
) -> Result<Vec<u8>> {
if outputs.is_empty() {
return Err(anyhow::Error::new(WalletError::InvalidAmount(
"makeTransfer needs a desired output".to_owned(),
)));
}
let transfers = connector::transfer_outputs(outputs, &self.session.network.network_id)?;
let _spend = self.spend.lock().await;
let synced = self.facade.read().await.clone();
let zswap = self.session.wallet.zswap_secret_keys();
let dust = self.session.wallet.dust_secret_key();
let now = synced.chain_tip_ts();
let (recipe, booked) = build_transfer_recipe(
&mut rand::rngs::OsRng,
synced,
&transfers,
&self.keys(&zswap, &dust),
&TransferOptions {
ttl: ttl_from(now),
current_time: now,
pay_fees,
},
)?;
self.prove_and_book(recipe, booked).await
}
pub async fn make_intent(
&self,
inputs: &[DesiredInput],
outputs: &[DesiredOutput],
options: MakeIntentOptions,
) -> Result<Vec<u8>> {
let inputs = connector::swap_inputs(inputs)?;
let outputs = connector::transfer_outputs(outputs, &self.session.network.network_id)?;
let segment = options.intent_id.resolve(&mut rand::rngs::OsRng);
let _spend = self.spend.lock().await;
let synced = self.facade.read().await.clone();
let zswap = self.session.wallet.zswap_secret_keys();
let dust = self.session.wallet.dust_secret_key();
let now = synced.chain_tip_ts();
let (recipe, booked) = init_swap(
&mut rand::rngs::OsRng,
synced,
&inputs,
&outputs,
&self.keys(&zswap, &dust),
&SwapOptions {
ttl: ttl_from(now),
current_time: now,
pay_fees: options.pay_fees,
},
segment,
)?;
self.prove_and_book(recipe, booked).await
}
pub async fn balance_unsealed(
&self,
base: ProvenTransaction,
pay_fees: bool,
) -> Result<Vec<u8>> {
let _spend = self.spend.lock().await;
let facade = self.facade.read().await.clone();
let (booked, sealed) = Box::pin(seal_unbound(
facade,
base,
&self.session.wallet,
pay_fees,
&self.backend,
))
.await?;
let bytes = sealed_bytes(sealed)?;
*self.facade.write().await = booked;
Ok(bytes)
}
pub async fn balance_sealed(
&self,
original: FinalizedTransaction,
pay_fees: bool,
) -> Result<Vec<u8>> {
let _spend = self.spend.lock().await;
let facade = self.facade.read().await.clone();
let (booked, paid) = Box::pin(pay_sealed(
facade,
original,
&self.session.wallet,
pay_fees,
&self.backend,
))
.await?;
let bytes = sealed_bytes(paid)?;
*self.facade.write().await = booked;
Ok(bytes)
}
pub async fn submit_transaction(self: &Arc<Self>, bytes: Vec<u8>) -> Result<()> {
let tx = moonproof_ledger::serialize::tagged_deserialize::<FinalizedTransaction>(
bytes.as_slice(),
)
.map_err(|e| {
anyhow::Error::new(WalletError::Serialization(format!("not a sealed tx: {e}")))
})?;
let mut watch = SubmissionWatch::submit(self.session.node.as_ref(), bytes.clone()).await;
let submitted = watch.wait_for(SubmissionStage::Submitted).await;
if watch.settled() == Some(SubmissionEnd::Excluded) {
let _spend = self.spend.lock().await;
let current = self.facade.read().await.clone();
let released = current.revert_transaction(&tx);
*self.facade.write().await = released;
return submitted.map(|_| ()).map_err(anyhow::Error::new);
}
let event = submitted.map_err(anyhow::Error::new)?;
let protocol_version = self.facade.read().await.protocol_version();
let segment_ids = match &tx {
moonproof_ledger::ledger::structure::Transaction::Standard(stx) => {
let mut ids: Vec<u16> = stx.intents.keys().collect();
ids.sort_unstable();
ids
}
moonproof_ledger::ledger::structure::Transaction::ClaimRewards(_) => Vec::new(),
};
let submitted_at_ms = moonproof_utils::rt::SystemTime::now()
.duration_since(moonproof_utils::rt::UNIX_EPOCH)
.map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX));
let tx_hash = event.tx_hash().to_owned();
self.pending
.upsert(PendingTransactionEntry {
hash: tx_hash.clone(),
creation_time_ms: submitted_at_ms,
segment_ids: segment_ids.clone(),
ttl_secs: i64::try_from(TRANSACTION_TTL_SECS).ok(),
raw_tx_hex: Some(hex::encode(&bytes)),
result: None,
})
.await?;
let wallet = Arc::downgrade(self);
moonproof_utils::rt::spawn(async move {
let end = watch.end().await;
let Some(this) = wallet.upgrade() else {
return;
};
let outcome = Submission {
tx_hash,
submitted_at_ms,
segment_ids,
protocol_version,
};
if let Err(e) = this.settle(&tx, end, outcome).await {
tracing::warn!(error = %e, "following a dApp submission failed");
}
});
Ok(())
}
async fn settle(
&self,
tx: &FinalizedTransaction,
end: SubmissionEnd,
submission: Submission,
) -> Result<()> {
let indexer = HttpIndexerClient::new(&self.session.network.indexer_http)
.map_err(|e| anyhow!("indexer url: {e}"))?;
let result = ended_transaction_result(&indexer, tx, end, FOLLOW_LIMIT)
.await
.ok_or_else(|| {
anyhow!(
"no result for {} within the follow limit",
submission.tx_hash
)
})?;
self.record_outcome(submission, &result).await?;
if result.status != PendingTransactionStatus::Success {
let _spend = self.spend.lock().await;
let current = self.facade.read().await.clone();
*self.facade.write().await = current.release_ended(tx, &result);
}
Ok(())
}
async fn record_outcome(
&self,
submission: Submission,
result: &PendingTransactionResult,
) -> Result<()> {
let execution = connector::execution_status(&submission.segment_ids, result);
self.history
.upsert(TransactionHistoryEntry {
hash: submission.tx_hash.clone(),
protocol_version: submission.protocol_version,
status: match result.status {
PendingTransactionStatus::Success => TransactionHistoryStatus::Success,
PendingTransactionStatus::PartialSuccess => {
TransactionHistoryStatus::PartialSuccess
}
PendingTransactionStatus::Failure => TransactionHistoryStatus::Failure,
},
identifiers: None,
timestamp_ms: Some(submission.submitted_at_ms),
fees: None,
shielded: None,
unshielded: None,
dust: None,
extra: serde_json::json!({ connector::EXECUTION_STATUS_KEY: execution }),
})
.await?;
self.pending
.mark_result(&submission.tx_hash, result.clone())
.await?;
Ok(())
}
}
struct Submission {
tx_hash: String,
submitted_at_ms: i64,
segment_ids: Vec<u16>,
protocol_version: crate::abstractions::ProtocolVersion,
}