Skip to main content

moonproof_wallet/
tx_history.rs

1//! Transaction-history storage — port of
2//! `@midnight-ntwrk/wallet-sdk-abstractions/TransactionHistoryStorage`.
3//!
4//! The SDK splits history into three layers (shielded / unshielded /
5//! dust), each written to its own per-sub-wallet `TransactionHistoryService`.
6//! The moonproof port collapses them into one `TransactionHistoryEntry`
7//! type with optional `shielded` / `unshielded` / `dust` sections, so a
8//! single store backs every layer. Lace and other GUIs traverse the
9//! list once and project the relevant section per view.
10//!
11//! Two impls live here:
12//!
13//! - [`InMemoryTransactionHistoryStorage`] — `IndexMap`-backed,
14//!   ordered by insertion. Default for tests + ephemeral CLIs.
15//! - On-disk impls (e.g. `moonproof-runtime`'s redb-backed store) live
16//!   in the runtime crate so this crate doesn't pick up storage deps.
17//!
18//! # `upsert` semantics
19//!
20//! Each entry is keyed by its `hash`. Re-inserting an entry with the
21//! same hash merges field-by-field — newer entries replace any
22//! `Some(...)` field, never silently downgrade to `None`. This matches
23//! TS `InMemoryTransactionHistoryStorage`'s default merge: the chain
24//! reports tx data in pieces (a `proposed` event arrives before
25//! `confirmed`; identifiers fan in over multiple blocks for partial
26//! successes), and we want every later piece to layer onto the entry
27//! the wallet already knows about.
28
29use std::sync::Arc;
30
31use indexmap::IndexMap;
32use moonproof_macros::async_trait;
33use moonproof_utils::EventBus;
34use serde::{Deserialize, Serialize};
35use tokio::sync::{broadcast, RwLock};
36
37use crate::abstractions::ProtocolVersion;
38use crate::error::{Result, WalletError};
39
40/// Hex-encoded transaction hash. Same shape as the indexer reports.
41pub type TransactionHash = String;
42
43/// Outcome the chain reported for a transaction. Mirrors TS
44/// `TransactionHistoryStatus` literals.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
46#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
47pub enum TransactionHistoryStatus {
48    Success,
49    Failure,
50    PartialSuccess,
51}
52
53/// One transaction-history record.
54///
55/// `shielded` / `unshielded` / `dust` are opaque JSON values so the
56/// per-sub-wallet `TransactionHistoryService` ports can write whatever
57/// schema they need without dragging the storage layer behind every
58/// schema change. Concrete schemas live in each sub-wallet module.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct TransactionHistoryEntry {
61    /// Hex-encoded ledger transaction hash. Primary key.
62    pub hash: TransactionHash,
63    /// Protocol version under which the transaction was applied.
64    /// Newtype-wrapped via [`ProtocolVersion`] for forward-compat
65    /// branding; serializes as a bare number so on-disk JSON is
66    /// unchanged from the prior `u32` shape.
67    pub protocol_version: ProtocolVersion,
68    pub status: TransactionHistoryStatus,
69    /// Per-segment identifiers for partial-success cases. `None` when
70    /// the chain reported a single segment.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub identifiers: Option<Vec<String>>,
73    /// Block timestamp (UNIX millis) if known.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub timestamp_ms: Option<i64>,
76    /// Fees the transaction paid, in the smallest on-chain unit.
77    /// `None` when the chain hasn't reported them yet (pre-confirm
78    /// rows have a fee estimate, but final fees come post-block).
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub fees: Option<u128>,
81    /// Optional shielded section. Wallet-defined schema, transparent
82    /// to the storage layer.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub shielded: Option<serde_json::Value>,
85    /// Optional unshielded section.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub unshielded: Option<serde_json::Value>,
88    /// Optional dust section.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub dust: Option<serde_json::Value>,
91    /// Catch-all for forward compatibility — any field a future
92    /// schema introduces lands here on read so we don't lose data on
93    /// round-trip through an older binary.
94    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
95    pub extra: serde_json::Value,
96}
97
98impl TransactionHistoryEntry {
99    /// Merge `incoming` into `self`. Newer `Some(_)` fields replace
100    /// existing values; `None` fields leave existing data alone.
101    /// `extra` objects are merged shallowly (incoming keys win on
102    /// conflict). Mirrors TS's default `(existing, incoming) => ({
103    /// ...existing, ...incoming })` shape but field-aware so we don't
104    /// blow away the chain-reported `fees` with a later
105    /// `fees: undefined` payload.
106    pub fn merge(&mut self, incoming: Self) {
107        // hash + protocol_version + status are always taken from the
108        // newer entry — they're identity fields.
109        debug_assert_eq!(self.hash, incoming.hash);
110        self.protocol_version = incoming.protocol_version;
111        self.status = incoming.status;
112        if incoming.identifiers.is_some() {
113            self.identifiers = incoming.identifiers;
114        }
115        if incoming.timestamp_ms.is_some() {
116            self.timestamp_ms = incoming.timestamp_ms;
117        }
118        if incoming.fees.is_some() {
119            self.fees = incoming.fees;
120        }
121        if incoming.shielded.is_some() {
122            self.shielded = incoming.shielded;
123        }
124        if incoming.unshielded.is_some() {
125            self.unshielded = incoming.unshielded;
126        }
127        if incoming.dust.is_some() {
128            self.dust = incoming.dust;
129        }
130        match (&mut self.extra, incoming.extra) {
131            (serde_json::Value::Object(existing_map), serde_json::Value::Object(incoming_map)) => {
132                for (k, v) in incoming_map {
133                    existing_map.insert(k, v);
134                }
135            }
136            (slot, incoming) if !incoming.is_null() => {
137                *slot = incoming;
138            }
139            _ => {}
140        }
141    }
142}
143
144/// Storage interface for transaction-history entries keyed by `hash`.
145/// Async because real impls do disk I/O; the in-memory variant is
146/// trivially synchronous but keeps the trait signature aligned.
147#[async_trait]
148pub trait TransactionHistoryStorage: Send + Sync + std::fmt::Debug {
149    async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()>;
150    async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>>;
151    async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>>;
152    async fn remove(&self, hash: &str) -> Result<()>;
153    async fn clear(&self) -> Result<()>;
154    /// Serialize all entries as a UTF-8 JSON array. Convenience for
155    /// callers who want a single-blob backup; equivalent to
156    /// `serde_json::to_string(&store.get_all().await?)`.
157    async fn serialize(&self) -> Result<String> {
158        let all = self.get_all().await?;
159        serde_json::to_string(&all)
160            .map_err(|e| WalletError::Serialization(format!("encode tx history: {e}")))
161    }
162}
163
164#[async_trait]
165impl<T: TransactionHistoryStorage + ?Sized> TransactionHistoryStorage for Arc<T> {
166    async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()> {
167        (**self).upsert(entry).await
168    }
169    async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>> {
170        (**self).get(hash).await
171    }
172    async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
173        (**self).get_all().await
174    }
175    async fn remove(&self, hash: &str) -> Result<()> {
176        (**self).remove(hash).await
177    }
178    async fn clear(&self) -> Result<()> {
179        (**self).clear().await
180    }
181}
182
183/// In-memory `IndexMap`-backed [`TransactionHistoryStorage`].
184///
185/// Cheap to clone (`Arc` over the inner state). Insertion order
186/// matches TS `InMemoryTransactionHistoryStorage.getAll()` — newest
187/// entries appear last unless an upsert hits an existing key.
188#[derive(Debug, Clone, Default)]
189pub struct InMemoryTransactionHistoryStorage {
190    inner: Arc<RwLock<IndexMap<TransactionHash, TransactionHistoryEntry>>>,
191}
192
193impl InMemoryTransactionHistoryStorage {
194    #[must_use]
195    pub fn new() -> Self {
196        Self::default()
197    }
198
199    /// Restore from a previously [`TransactionHistoryStorage::serialize`]d
200    /// JSON blob. Used to load a backup without going through the disk
201    /// path.
202    pub fn restore(serialized: &str) -> Result<Self> {
203        let entries: Vec<TransactionHistoryEntry> = serde_json::from_str(serialized)
204            .map_err(|e| WalletError::Serialization(format!("decode tx history: {e}")))?;
205        let mut map = IndexMap::with_capacity(entries.len());
206        for e in entries {
207            map.insert(e.hash.clone(), e);
208        }
209        Ok(Self {
210            inner: Arc::new(RwLock::new(map)),
211        })
212    }
213}
214
215#[async_trait]
216impl TransactionHistoryStorage for InMemoryTransactionHistoryStorage {
217    async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()> {
218        let mut map = self.inner.write().await;
219        match map.get_mut(&entry.hash) {
220            Some(existing) => existing.merge(entry),
221            None => {
222                map.insert(entry.hash.clone(), entry);
223            }
224        }
225        Ok(())
226    }
227
228    async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>> {
229        Ok(self.inner.read().await.get(hash).cloned())
230    }
231
232    async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
233        Ok(self.inner.read().await.values().cloned().collect())
234    }
235
236    async fn remove(&self, hash: &str) -> Result<()> {
237        self.inner.write().await.shift_remove(hash);
238        Ok(())
239    }
240
241    async fn clear(&self) -> Result<()> {
242        self.inner.write().await.clear();
243        Ok(())
244    }
245}
246
247/// Event emitted by [`WatchedTransactionHistoryStorage`] on every
248/// mutation. Subscribers project the change into their own UI /
249/// notification surface — pair with [`TransactionHistoryStorage::get_all`]
250/// for a full snapshot when initialising.
251#[derive(Debug, Clone)]
252pub enum TxHistoryEvent {
253    /// New entry inserted, or existing entry merged with new fields.
254    Upserted(Box<TransactionHistoryEntry>),
255    /// Entry removed by hash.
256    Removed(TransactionHash),
257    /// All entries cleared.
258    Cleared,
259}
260
261/// Wraps any [`TransactionHistoryStorage`] and broadcasts a
262/// [`TxHistoryEvent`] on every write. Mirror of TS
263/// `TransactionHistoryService` observables — UIs subscribe once and
264/// react to upserts / removes / clears without polling `get_all`.
265///
266/// Built on the shared [`moonproof_utils::EventBus`] so the
267/// broadcast plumbing is single-sourced across moonproof's storage
268/// wrappers (this + [`crate::pending_tx::WatchedPendingTransactionsStorage`]).
269///
270/// Cheap to clone (`Arc`-shared inner state). Subscribers via
271/// [`WatchedTransactionHistoryStorage::subscribe`] each receive every
272/// event from the moment they subscribe forward; pair with
273/// [`TransactionHistoryStorage::get_all`] on startup for the initial
274/// snapshot.
275#[derive(Debug)]
276pub struct WatchedTransactionHistoryStorage<S>
277where
278    S: TransactionHistoryStorage,
279{
280    inner: Arc<S>,
281    events: EventBus<TxHistoryEvent>,
282}
283
284impl<S: TransactionHistoryStorage> Clone for WatchedTransactionHistoryStorage<S> {
285    fn clone(&self) -> Self {
286        Self {
287            inner: Arc::clone(&self.inner),
288            events: self.events.clone(),
289        }
290    }
291}
292
293impl<S: TransactionHistoryStorage> WatchedTransactionHistoryStorage<S> {
294    /// Wrap `inner` with a broadcast channel of default capacity.
295    pub fn new(inner: S) -> Self {
296        Self {
297            inner: Arc::new(inner),
298            events: EventBus::new(),
299        }
300    }
301
302    /// Wrap `inner` with an explicit channel capacity.
303    pub fn with_capacity(inner: S, capacity: usize) -> Self {
304        Self {
305            inner: Arc::new(inner),
306            events: EventBus::with_capacity(capacity),
307        }
308    }
309
310    /// Subscribe to mutation events. Each receiver sees every event
311    /// from the moment of subscription; misses on slow consumers
312    /// surface as `RecvError::Lagged`.
313    pub fn subscribe(&self) -> broadcast::Receiver<TxHistoryEvent> {
314        self.events.subscribe()
315    }
316
317    /// Number of currently active subscribers — useful for tests +
318    /// for skipping notification work when nobody is listening.
319    pub fn subscriber_count(&self) -> usize {
320        self.events.subscriber_count()
321    }
322}
323
324#[async_trait]
325impl<S: TransactionHistoryStorage> TransactionHistoryStorage
326    for WatchedTransactionHistoryStorage<S>
327{
328    async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()> {
329        self.inner.upsert(entry.clone()).await?;
330        self.events
331            .publish(TxHistoryEvent::Upserted(Box::new(entry)));
332        Ok(())
333    }
334
335    async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>> {
336        self.inner.get(hash).await
337    }
338
339    async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
340        self.inner.get_all().await
341    }
342
343    async fn remove(&self, hash: &str) -> Result<()> {
344        self.inner.remove(hash).await?;
345        self.events
346            .publish(TxHistoryEvent::Removed(hash.to_owned()));
347        Ok(())
348    }
349
350    async fn clear(&self) -> Result<()> {
351        self.inner.clear().await?;
352        self.events.publish(TxHistoryEvent::Cleared);
353        Ok(())
354    }
355}
356
357/// No-op [`TransactionHistoryStorage`]. `upsert` succeeds, every read
358/// returns empty. Drop-in for callers that opt out of history without
359/// caring about Option<...>.
360#[derive(Debug, Clone, Default)]
361pub struct NoOpTransactionHistoryStorage;
362
363#[async_trait]
364impl TransactionHistoryStorage for NoOpTransactionHistoryStorage {
365    async fn upsert(&self, _entry: TransactionHistoryEntry) -> Result<()> {
366        Ok(())
367    }
368    async fn get(&self, _hash: &str) -> Result<Option<TransactionHistoryEntry>> {
369        Ok(None)
370    }
371    async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
372        Ok(Vec::new())
373    }
374    async fn remove(&self, _hash: &str) -> Result<()> {
375        Ok(())
376    }
377    async fn clear(&self) -> Result<()> {
378        Ok(())
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    fn entry(hash: &str, status: TransactionHistoryStatus) -> TransactionHistoryEntry {
387        TransactionHistoryEntry {
388            hash: hash.to_owned(),
389            protocol_version: ProtocolVersion(8),
390            status,
391            identifiers: None,
392            timestamp_ms: None,
393            fees: None,
394            shielded: None,
395            unshielded: None,
396            dust: None,
397            extra: serde_json::Value::Null,
398        }
399    }
400
401    fn matches_upsert_event(ev: &TxHistoryEvent, hash: &str) -> bool {
402        matches!(ev, TxHistoryEvent::Upserted(e) if e.hash == hash)
403    }
404
405    fn matches_remove_event(ev: &TxHistoryEvent, hash: &str) -> bool {
406        matches!(ev, TxHistoryEvent::Removed(h) if h == hash)
407    }
408
409    #[tokio::test]
410    async fn watched_storage_broadcasts_upsert() {
411        let watched =
412            WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
413        let mut rx = watched.subscribe();
414        watched
415            .upsert(entry("aa", TransactionHistoryStatus::Success))
416            .await
417            .unwrap();
418        let ev = rx.recv().await.unwrap();
419        assert!(matches_upsert_event(&ev, "aa"));
420    }
421
422    #[tokio::test]
423    async fn watched_storage_broadcasts_remove_and_clear() {
424        let watched =
425            WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
426        watched
427            .upsert(entry("aa", TransactionHistoryStatus::Success))
428            .await
429            .unwrap();
430        let mut rx = watched.subscribe();
431        watched.remove("aa").await.unwrap();
432        let ev = rx.recv().await.unwrap();
433        assert!(matches_remove_event(&ev, "aa"));
434        watched.clear().await.unwrap();
435        let ev = rx.recv().await.unwrap();
436        assert!(matches!(ev, TxHistoryEvent::Cleared));
437    }
438
439    #[tokio::test]
440    async fn watched_storage_get_all_passes_through() {
441        let watched =
442            WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
443        watched
444            .upsert(entry("aa", TransactionHistoryStatus::Success))
445            .await
446            .unwrap();
447        watched
448            .upsert(entry("bb", TransactionHistoryStatus::Failure))
449            .await
450            .unwrap();
451        let all = watched.get_all().await.unwrap();
452        assert_eq!(all.len(), 2);
453    }
454
455    #[tokio::test]
456    async fn watched_storage_subscriber_count_tracks_receivers() {
457        let watched =
458            WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
459        assert_eq!(watched.subscriber_count(), 0);
460        let _rx1 = watched.subscribe();
461        let _rx2 = watched.subscribe();
462        assert_eq!(watched.subscriber_count(), 2);
463    }
464
465    #[tokio::test]
466    async fn upsert_inserts_new_entry() {
467        let store = InMemoryTransactionHistoryStorage::new();
468        store
469            .upsert(entry("aa", TransactionHistoryStatus::Success))
470            .await
471            .unwrap();
472        let got = store.get("aa").await.unwrap().unwrap();
473        assert_eq!(got.status, TransactionHistoryStatus::Success);
474    }
475
476    #[tokio::test]
477    async fn upsert_merges_existing_entry_field_aware() {
478        let store = InMemoryTransactionHistoryStorage::new();
479        let mut a = entry("aa", TransactionHistoryStatus::Success);
480        a.fees = Some(100);
481        store.upsert(a).await.unwrap();
482        let mut b = entry("aa", TransactionHistoryStatus::Success);
483        b.timestamp_ms = Some(1234);
484        // intentionally omit fees on the incoming side — must not
485        // wipe the existing value
486        store.upsert(b).await.unwrap();
487        let got = store.get("aa").await.unwrap().unwrap();
488        assert_eq!(got.fees, Some(100));
489        assert_eq!(got.timestamp_ms, Some(1234));
490    }
491
492    #[tokio::test]
493    async fn get_all_preserves_insertion_order() {
494        let store = InMemoryTransactionHistoryStorage::new();
495        store
496            .upsert(entry("aa", TransactionHistoryStatus::Success))
497            .await
498            .unwrap();
499        store
500            .upsert(entry("bb", TransactionHistoryStatus::Failure))
501            .await
502            .unwrap();
503        store
504            .upsert(entry("cc", TransactionHistoryStatus::PartialSuccess))
505            .await
506            .unwrap();
507        let all = store.get_all().await.unwrap();
508        let hashes: Vec<&str> = all.iter().map(|e| e.hash.as_str()).collect();
509        assert_eq!(hashes, vec!["aa", "bb", "cc"]);
510    }
511
512    #[tokio::test]
513    async fn remove_drops_entry_only() {
514        let store = InMemoryTransactionHistoryStorage::new();
515        store
516            .upsert(entry("aa", TransactionHistoryStatus::Success))
517            .await
518            .unwrap();
519        store
520            .upsert(entry("bb", TransactionHistoryStatus::Success))
521            .await
522            .unwrap();
523        store.remove("aa").await.unwrap();
524        assert!(store.get("aa").await.unwrap().is_none());
525        assert!(store.get("bb").await.unwrap().is_some());
526    }
527
528    #[tokio::test]
529    async fn serialize_and_restore_round_trip() {
530        let store = InMemoryTransactionHistoryStorage::new();
531        let mut a = entry("aa", TransactionHistoryStatus::Success);
532        a.fees = Some(7);
533        store.upsert(a).await.unwrap();
534        store
535            .upsert(entry("bb", TransactionHistoryStatus::Failure))
536            .await
537            .unwrap();
538        let json = store.serialize().await.unwrap();
539        let restored = InMemoryTransactionHistoryStorage::restore(&json).unwrap();
540        let all = restored.get_all().await.unwrap();
541        assert_eq!(all.len(), 2);
542        assert_eq!(all[0].hash, "aa");
543        assert_eq!(all[0].fees, Some(7));
544    }
545
546    #[tokio::test]
547    async fn noop_returns_empty_for_every_query() {
548        let store = NoOpTransactionHistoryStorage;
549        store
550            .upsert(entry("aa", TransactionHistoryStatus::Success))
551            .await
552            .unwrap();
553        assert!(store.get("aa").await.unwrap().is_none());
554        assert!(store.get_all().await.unwrap().is_empty());
555    }
556}