use std::sync::Arc;
use indexmap::IndexMap;
use moonproof_macros::async_trait;
use moonproof_utils::EventBus;
use serde::{Deserialize, Serialize};
use tokio::sync::{broadcast, RwLock};
use crate::error::{Result, WalletError};
use crate::tx_history::TransactionHash;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct SegmentResult {
pub id: u16,
pub success: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PendingTransactionStatus {
Success,
Failure,
PartialSuccess,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PendingTransactionEntry {
pub hash: TransactionHash,
pub creation_time_ms: i64,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub segment_ids: Vec<u16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ttl_secs: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub raw_tx_hex: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub result: Option<PendingTransactionResult>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PendingTransactionResult {
pub status: PendingTransactionStatus,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub segments: Vec<SegmentResult>,
}
impl PendingTransactionEntry {
#[inline]
#[must_use]
pub fn is_pending(&self) -> bool {
self.result.is_none()
}
#[must_use]
pub fn is_failed(&self) -> bool {
matches!(
self.result.as_ref().map(|r| r.status),
Some(PendingTransactionStatus::Failure | PendingTransactionStatus::PartialSuccess)
)
}
#[must_use]
pub fn ttl_expired(&self, now_unix_secs: i64) -> bool {
let Some(ttl) = self.ttl_secs else {
return false;
};
let creation_secs = self.creation_time_ms / 1000;
now_unix_secs > creation_secs + ttl
}
}
#[async_trait]
pub trait PendingTransactionsStorage: Send + Sync + std::fmt::Debug {
async fn upsert(&self, entry: PendingTransactionEntry) -> Result<()>;
async fn mark_result(&self, hash: &str, result: PendingTransactionResult) -> Result<()>;
async fn get(&self, hash: &str) -> Result<Option<PendingTransactionEntry>>;
async fn get_all(&self) -> Result<Vec<PendingTransactionEntry>>;
async fn get_pending(&self) -> Result<Vec<PendingTransactionEntry>> {
let all = self.get_all().await?;
Ok(all
.into_iter()
.filter(super::PendingTransactionEntry::is_pending)
.collect())
}
async fn get_failed(&self) -> Result<Vec<PendingTransactionEntry>> {
let all = self.get_all().await?;
Ok(all
.into_iter()
.filter(super::PendingTransactionEntry::is_failed)
.collect())
}
async fn remove(&self, hash: &str) -> Result<()>;
async fn clear(&self) -> Result<()>;
}
#[async_trait]
impl<T: PendingTransactionsStorage + ?Sized> PendingTransactionsStorage for Arc<T> {
async fn upsert(&self, entry: PendingTransactionEntry) -> Result<()> {
(**self).upsert(entry).await
}
async fn mark_result(&self, hash: &str, result: PendingTransactionResult) -> Result<()> {
(**self).mark_result(hash, result).await
}
async fn get(&self, hash: &str) -> Result<Option<PendingTransactionEntry>> {
(**self).get(hash).await
}
async fn get_all(&self) -> Result<Vec<PendingTransactionEntry>> {
(**self).get_all().await
}
async fn remove(&self, hash: &str) -> Result<()> {
(**self).remove(hash).await
}
async fn clear(&self) -> Result<()> {
(**self).clear().await
}
}
#[derive(Debug, Clone, Default)]
pub struct InMemoryPendingTransactionsStorage {
inner: Arc<RwLock<IndexMap<TransactionHash, PendingTransactionEntry>>>,
}
impl InMemoryPendingTransactionsStorage {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
#[async_trait]
impl PendingTransactionsStorage for InMemoryPendingTransactionsStorage {
async fn upsert(&self, entry: PendingTransactionEntry) -> Result<()> {
self.inner.write().await.insert(entry.hash.clone(), entry);
Ok(())
}
async fn mark_result(&self, hash: &str, result: PendingTransactionResult) -> Result<()> {
let mut map = self.inner.write().await;
if let Some(existing) = map.get_mut(hash) {
existing.result = Some(result);
}
Ok(())
}
async fn get(&self, hash: &str) -> Result<Option<PendingTransactionEntry>> {
Ok(self.inner.read().await.get(hash).cloned())
}
async fn get_all(&self) -> Result<Vec<PendingTransactionEntry>> {
Ok(self.inner.read().await.values().cloned().collect())
}
async fn remove(&self, hash: &str) -> Result<()> {
self.inner.write().await.shift_remove(hash);
Ok(())
}
async fn clear(&self) -> Result<()> {
self.inner.write().await.clear();
Ok(())
}
}
#[derive(Debug, Clone)]
pub enum PendingTxEvent {
Upserted(PendingTransactionEntry),
ResultRecorded {
hash: TransactionHash,
result: PendingTransactionResult,
},
Removed(TransactionHash),
Cleared,
}
#[derive(Debug)]
pub struct WatchedPendingTransactionsStorage<S>
where
S: PendingTransactionsStorage,
{
inner: Arc<S>,
events: EventBus<PendingTxEvent>,
}
impl<S: PendingTransactionsStorage> Clone for WatchedPendingTransactionsStorage<S> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
events: self.events.clone(),
}
}
}
impl<S: PendingTransactionsStorage> WatchedPendingTransactionsStorage<S> {
pub fn new(inner: S) -> Self {
Self {
inner: Arc::new(inner),
events: EventBus::new(),
}
}
pub fn with_capacity(inner: S, capacity: usize) -> Self {
Self {
inner: Arc::new(inner),
events: EventBus::with_capacity(capacity),
}
}
pub fn subscribe(&self) -> broadcast::Receiver<PendingTxEvent> {
self.events.subscribe()
}
pub fn subscriber_count(&self) -> usize {
self.events.subscriber_count()
}
}
#[async_trait]
impl<S: PendingTransactionsStorage> PendingTransactionsStorage
for WatchedPendingTransactionsStorage<S>
{
async fn upsert(&self, entry: PendingTransactionEntry) -> Result<()> {
self.inner.upsert(entry.clone()).await?;
self.events.publish(PendingTxEvent::Upserted(entry));
Ok(())
}
async fn mark_result(&self, hash: &str, result: PendingTransactionResult) -> Result<()> {
self.inner.mark_result(hash, result.clone()).await?;
self.events.publish(PendingTxEvent::ResultRecorded {
hash: hash.to_owned(),
result,
});
Ok(())
}
async fn get(&self, hash: &str) -> Result<Option<PendingTransactionEntry>> {
self.inner.get(hash).await
}
async fn get_all(&self) -> Result<Vec<PendingTransactionEntry>> {
self.inner.get_all().await
}
async fn remove(&self, hash: &str) -> Result<()> {
self.inner.remove(hash).await?;
self.events
.publish(PendingTxEvent::Removed(hash.to_owned()));
Ok(())
}
async fn clear(&self) -> Result<()> {
self.inner.clear().await?;
self.events.publish(PendingTxEvent::Cleared);
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub struct NoOpPendingTransactionsStorage;
#[async_trait]
impl PendingTransactionsStorage for NoOpPendingTransactionsStorage {
async fn upsert(&self, _entry: PendingTransactionEntry) -> Result<()> {
Ok(())
}
async fn mark_result(&self, _hash: &str, _result: PendingTransactionResult) -> Result<()> {
Ok(())
}
async fn get(&self, _hash: &str) -> Result<Option<PendingTransactionEntry>> {
Ok(None)
}
async fn get_all(&self) -> Result<Vec<PendingTransactionEntry>> {
Ok(Vec::new())
}
async fn remove(&self, _hash: &str) -> Result<()> {
Ok(())
}
async fn clear(&self) -> Result<()> {
Ok(())
}
}
#[doc(hidden)]
pub fn _force_link() -> Option<WalletError> {
None
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(hash: &str) -> PendingTransactionEntry {
PendingTransactionEntry {
hash: hash.to_owned(),
creation_time_ms: 1_700_000_000_000,
segment_ids: vec![0, 1],
ttl_secs: Some(3600),
raw_tx_hex: None,
result: None,
}
}
#[tokio::test]
async fn watched_pending_broadcasts_upsert() {
let watched =
WatchedPendingTransactionsStorage::new(InMemoryPendingTransactionsStorage::new());
let mut rx = watched.subscribe();
watched.upsert(entry("aa")).await.unwrap();
match rx.recv().await.unwrap() {
PendingTxEvent::Upserted(e) => assert_eq!(e.hash, "aa"),
other => panic!("expected upsert event, got {other:?}"),
}
}
#[tokio::test]
async fn watched_pending_broadcasts_mark_result_remove_clear() {
let watched =
WatchedPendingTransactionsStorage::new(InMemoryPendingTransactionsStorage::new());
watched.upsert(entry("aa")).await.unwrap();
let mut rx = watched.subscribe();
watched
.mark_result(
"aa",
PendingTransactionResult {
status: PendingTransactionStatus::Success,
segments: Vec::new(),
},
)
.await
.unwrap();
match rx.recv().await.unwrap() {
PendingTxEvent::ResultRecorded { hash, .. } => assert_eq!(hash, "aa"),
other => panic!("expected result event, got {other:?}"),
}
watched.remove("aa").await.unwrap();
match rx.recv().await.unwrap() {
PendingTxEvent::Removed(h) => assert_eq!(h, "aa"),
other => panic!("expected remove event, got {other:?}"),
}
watched.clear().await.unwrap();
assert!(matches!(rx.recv().await.unwrap(), PendingTxEvent::Cleared));
}
#[tokio::test]
async fn upsert_inserts_entry() {
let store = InMemoryPendingTransactionsStorage::new();
store.upsert(entry("aa")).await.unwrap();
let got = store.get("aa").await.unwrap().unwrap();
assert!(got.is_pending());
}
#[tokio::test]
async fn mark_result_attaches_result() {
let store = InMemoryPendingTransactionsStorage::new();
store.upsert(entry("aa")).await.unwrap();
store
.mark_result(
"aa",
PendingTransactionResult {
status: PendingTransactionStatus::Success,
segments: vec![],
},
)
.await
.unwrap();
let got = store.get("aa").await.unwrap().unwrap();
assert!(!got.is_pending());
assert_eq!(
got.result.as_ref().map(|r| r.status),
Some(PendingTransactionStatus::Success)
);
}
#[tokio::test]
async fn mark_result_on_unknown_hash_is_noop() {
let store = InMemoryPendingTransactionsStorage::new();
store
.mark_result(
"missing",
PendingTransactionResult {
status: PendingTransactionStatus::Failure,
segments: vec![],
},
)
.await
.unwrap();
assert!(store.get("missing").await.unwrap().is_none());
}
#[tokio::test]
async fn get_pending_filters_out_finalised() {
let store = InMemoryPendingTransactionsStorage::new();
store.upsert(entry("aa")).await.unwrap();
store.upsert(entry("bb")).await.unwrap();
store
.mark_result(
"aa",
PendingTransactionResult {
status: PendingTransactionStatus::Success,
segments: vec![],
},
)
.await
.unwrap();
let pending = store.get_pending().await.unwrap();
assert_eq!(pending.len(), 1);
assert_eq!(pending[0].hash, "bb");
}
#[tokio::test]
async fn get_failed_lists_partial_and_full_failures() {
let store = InMemoryPendingTransactionsStorage::new();
store.upsert(entry("aa")).await.unwrap();
store.upsert(entry("bb")).await.unwrap();
store.upsert(entry("cc")).await.unwrap();
store
.mark_result(
"aa",
PendingTransactionResult {
status: PendingTransactionStatus::Success,
segments: vec![],
},
)
.await
.unwrap();
store
.mark_result(
"bb",
PendingTransactionResult {
status: PendingTransactionStatus::Failure,
segments: vec![],
},
)
.await
.unwrap();
store
.mark_result(
"cc",
PendingTransactionResult {
status: PendingTransactionStatus::PartialSuccess,
segments: vec![SegmentResult {
id: 0,
success: true,
}],
},
)
.await
.unwrap();
let failed = store.get_failed().await.unwrap();
let hashes: Vec<&str> = failed.iter().map(|e| e.hash.as_str()).collect();
assert!(hashes.contains(&"bb"));
assert!(hashes.contains(&"cc"));
assert!(!hashes.contains(&"aa"));
}
#[test]
fn ttl_expired_returns_false_when_ttl_unset() {
let mut e = entry("aa");
e.ttl_secs = None;
assert!(!e.ttl_expired(99_999_999_999));
}
#[test]
fn ttl_expired_compares_unix_seconds_correctly() {
let e = entry("aa"); assert!(!e.ttl_expired(1_700_000_500));
assert!(e.ttl_expired(1_700_010_000));
}
}