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::abstractions::ProtocolVersion;
use crate::error::{Result, WalletError};
pub type TransactionHash = String;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionHistoryStatus {
Success,
Failure,
PartialSuccess,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionHistoryEntry {
pub hash: TransactionHash,
pub protocol_version: ProtocolVersion,
pub status: TransactionHistoryStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub identifiers: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timestamp_ms: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fees: Option<u128>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub shielded: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unshielded: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dust: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
pub extra: serde_json::Value,
}
impl TransactionHistoryEntry {
pub fn merge(&mut self, incoming: Self) {
debug_assert_eq!(self.hash, incoming.hash);
self.protocol_version = incoming.protocol_version;
self.status = incoming.status;
if incoming.identifiers.is_some() {
self.identifiers = incoming.identifiers;
}
if incoming.timestamp_ms.is_some() {
self.timestamp_ms = incoming.timestamp_ms;
}
if incoming.fees.is_some() {
self.fees = incoming.fees;
}
if incoming.shielded.is_some() {
self.shielded = incoming.shielded;
}
if incoming.unshielded.is_some() {
self.unshielded = incoming.unshielded;
}
if incoming.dust.is_some() {
self.dust = incoming.dust;
}
match (&mut self.extra, incoming.extra) {
(serde_json::Value::Object(existing_map), serde_json::Value::Object(incoming_map)) => {
for (k, v) in incoming_map {
existing_map.insert(k, v);
}
}
(slot, incoming) if !incoming.is_null() => {
*slot = incoming;
}
_ => {}
}
}
}
#[async_trait]
pub trait TransactionHistoryStorage: Send + Sync + std::fmt::Debug {
async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()>;
async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>>;
async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>>;
async fn remove(&self, hash: &str) -> Result<()>;
async fn clear(&self) -> Result<()>;
async fn serialize(&self) -> Result<String> {
let all = self.get_all().await?;
serde_json::to_string(&all)
.map_err(|e| WalletError::Serialization(format!("encode tx history: {e}")))
}
}
#[async_trait]
impl<T: TransactionHistoryStorage + ?Sized> TransactionHistoryStorage for Arc<T> {
async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()> {
(**self).upsert(entry).await
}
async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>> {
(**self).get(hash).await
}
async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
(**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 InMemoryTransactionHistoryStorage {
inner: Arc<RwLock<IndexMap<TransactionHash, TransactionHistoryEntry>>>,
}
impl InMemoryTransactionHistoryStorage {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn restore(serialized: &str) -> Result<Self> {
let entries: Vec<TransactionHistoryEntry> = serde_json::from_str(serialized)
.map_err(|e| WalletError::Serialization(format!("decode tx history: {e}")))?;
let mut map = IndexMap::with_capacity(entries.len());
for e in entries {
map.insert(e.hash.clone(), e);
}
Ok(Self {
inner: Arc::new(RwLock::new(map)),
})
}
}
#[async_trait]
impl TransactionHistoryStorage for InMemoryTransactionHistoryStorage {
async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()> {
let mut map = self.inner.write().await;
match map.get_mut(&entry.hash) {
Some(existing) => existing.merge(entry),
None => {
map.insert(entry.hash.clone(), entry);
}
}
Ok(())
}
async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>> {
Ok(self.inner.read().await.get(hash).cloned())
}
async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
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 TxHistoryEvent {
Upserted(Box<TransactionHistoryEntry>),
Removed(TransactionHash),
Cleared,
}
#[derive(Debug)]
pub struct WatchedTransactionHistoryStorage<S>
where
S: TransactionHistoryStorage,
{
inner: Arc<S>,
events: EventBus<TxHistoryEvent>,
}
impl<S: TransactionHistoryStorage> Clone for WatchedTransactionHistoryStorage<S> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
events: self.events.clone(),
}
}
}
impl<S: TransactionHistoryStorage> WatchedTransactionHistoryStorage<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<TxHistoryEvent> {
self.events.subscribe()
}
pub fn subscriber_count(&self) -> usize {
self.events.subscriber_count()
}
}
#[async_trait]
impl<S: TransactionHistoryStorage> TransactionHistoryStorage
for WatchedTransactionHistoryStorage<S>
{
async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()> {
self.inner.upsert(entry.clone()).await?;
self.events
.publish(TxHistoryEvent::Upserted(Box::new(entry)));
Ok(())
}
async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>> {
self.inner.get(hash).await
}
async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
self.inner.get_all().await
}
async fn remove(&self, hash: &str) -> Result<()> {
self.inner.remove(hash).await?;
self.events
.publish(TxHistoryEvent::Removed(hash.to_owned()));
Ok(())
}
async fn clear(&self) -> Result<()> {
self.inner.clear().await?;
self.events.publish(TxHistoryEvent::Cleared);
Ok(())
}
}
#[derive(Debug, Clone, Default)]
pub struct NoOpTransactionHistoryStorage;
#[async_trait]
impl TransactionHistoryStorage for NoOpTransactionHistoryStorage {
async fn upsert(&self, _entry: TransactionHistoryEntry) -> Result<()> {
Ok(())
}
async fn get(&self, _hash: &str) -> Result<Option<TransactionHistoryEntry>> {
Ok(None)
}
async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
Ok(Vec::new())
}
async fn remove(&self, _hash: &str) -> Result<()> {
Ok(())
}
async fn clear(&self) -> Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(hash: &str, status: TransactionHistoryStatus) -> TransactionHistoryEntry {
TransactionHistoryEntry {
hash: hash.to_owned(),
protocol_version: ProtocolVersion(8),
status,
identifiers: None,
timestamp_ms: None,
fees: None,
shielded: None,
unshielded: None,
dust: None,
extra: serde_json::Value::Null,
}
}
fn matches_upsert_event(ev: &TxHistoryEvent, hash: &str) -> bool {
matches!(ev, TxHistoryEvent::Upserted(e) if e.hash == hash)
}
fn matches_remove_event(ev: &TxHistoryEvent, hash: &str) -> bool {
matches!(ev, TxHistoryEvent::Removed(h) if h == hash)
}
#[tokio::test]
async fn watched_storage_broadcasts_upsert() {
let watched =
WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
let mut rx = watched.subscribe();
watched
.upsert(entry("aa", TransactionHistoryStatus::Success))
.await
.unwrap();
let ev = rx.recv().await.unwrap();
assert!(matches_upsert_event(&ev, "aa"));
}
#[tokio::test]
async fn watched_storage_broadcasts_remove_and_clear() {
let watched =
WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
watched
.upsert(entry("aa", TransactionHistoryStatus::Success))
.await
.unwrap();
let mut rx = watched.subscribe();
watched.remove("aa").await.unwrap();
let ev = rx.recv().await.unwrap();
assert!(matches_remove_event(&ev, "aa"));
watched.clear().await.unwrap();
let ev = rx.recv().await.unwrap();
assert!(matches!(ev, TxHistoryEvent::Cleared));
}
#[tokio::test]
async fn watched_storage_get_all_passes_through() {
let watched =
WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
watched
.upsert(entry("aa", TransactionHistoryStatus::Success))
.await
.unwrap();
watched
.upsert(entry("bb", TransactionHistoryStatus::Failure))
.await
.unwrap();
let all = watched.get_all().await.unwrap();
assert_eq!(all.len(), 2);
}
#[tokio::test]
async fn watched_storage_subscriber_count_tracks_receivers() {
let watched =
WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
assert_eq!(watched.subscriber_count(), 0);
let _rx1 = watched.subscribe();
let _rx2 = watched.subscribe();
assert_eq!(watched.subscriber_count(), 2);
}
#[tokio::test]
async fn upsert_inserts_new_entry() {
let store = InMemoryTransactionHistoryStorage::new();
store
.upsert(entry("aa", TransactionHistoryStatus::Success))
.await
.unwrap();
let got = store.get("aa").await.unwrap().unwrap();
assert_eq!(got.status, TransactionHistoryStatus::Success);
}
#[tokio::test]
async fn upsert_merges_existing_entry_field_aware() {
let store = InMemoryTransactionHistoryStorage::new();
let mut a = entry("aa", TransactionHistoryStatus::Success);
a.fees = Some(100);
store.upsert(a).await.unwrap();
let mut b = entry("aa", TransactionHistoryStatus::Success);
b.timestamp_ms = Some(1234);
store.upsert(b).await.unwrap();
let got = store.get("aa").await.unwrap().unwrap();
assert_eq!(got.fees, Some(100));
assert_eq!(got.timestamp_ms, Some(1234));
}
#[tokio::test]
async fn get_all_preserves_insertion_order() {
let store = InMemoryTransactionHistoryStorage::new();
store
.upsert(entry("aa", TransactionHistoryStatus::Success))
.await
.unwrap();
store
.upsert(entry("bb", TransactionHistoryStatus::Failure))
.await
.unwrap();
store
.upsert(entry("cc", TransactionHistoryStatus::PartialSuccess))
.await
.unwrap();
let all = store.get_all().await.unwrap();
let hashes: Vec<&str> = all.iter().map(|e| e.hash.as_str()).collect();
assert_eq!(hashes, vec!["aa", "bb", "cc"]);
}
#[tokio::test]
async fn remove_drops_entry_only() {
let store = InMemoryTransactionHistoryStorage::new();
store
.upsert(entry("aa", TransactionHistoryStatus::Success))
.await
.unwrap();
store
.upsert(entry("bb", TransactionHistoryStatus::Success))
.await
.unwrap();
store.remove("aa").await.unwrap();
assert!(store.get("aa").await.unwrap().is_none());
assert!(store.get("bb").await.unwrap().is_some());
}
#[tokio::test]
async fn serialize_and_restore_round_trip() {
let store = InMemoryTransactionHistoryStorage::new();
let mut a = entry("aa", TransactionHistoryStatus::Success);
a.fees = Some(7);
store.upsert(a).await.unwrap();
store
.upsert(entry("bb", TransactionHistoryStatus::Failure))
.await
.unwrap();
let json = store.serialize().await.unwrap();
let restored = InMemoryTransactionHistoryStorage::restore(&json).unwrap();
let all = restored.get_all().await.unwrap();
assert_eq!(all.len(), 2);
assert_eq!(all[0].hash, "aa");
assert_eq!(all[0].fees, Some(7));
}
#[tokio::test]
async fn noop_returns_empty_for_every_query() {
let store = NoOpTransactionHistoryStorage;
store
.upsert(entry("aa", TransactionHistoryStatus::Success))
.await
.unwrap();
assert!(store.get("aa").await.unwrap().is_none());
assert!(store.get_all().await.unwrap().is_empty());
}
}