moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Transaction-history storage — port of
//! `@midnight-ntwrk/wallet-sdk-abstractions/TransactionHistoryStorage`.
//!
//! The SDK splits history into three layers (shielded / unshielded /
//! dust), each written to its own per-sub-wallet `TransactionHistoryService`.
//! The moonproof port collapses them into one `TransactionHistoryEntry`
//! type with optional `shielded` / `unshielded` / `dust` sections, so a
//! single store backs every layer. Lace and other GUIs traverse the
//! list once and project the relevant section per view.
//!
//! Two impls live here:
//!
//! - [`InMemoryTransactionHistoryStorage`] — `IndexMap`-backed,
//!   ordered by insertion. Default for tests + ephemeral CLIs.
//! - On-disk impls (e.g. `moonproof-runtime`'s redb-backed store) live
//!   in the runtime crate so this crate doesn't pick up storage deps.
//!
//! # `upsert` semantics
//!
//! Each entry is keyed by its `hash`. Re-inserting an entry with the
//! same hash merges field-by-field — newer entries replace any
//! `Some(...)` field, never silently downgrade to `None`. This matches
//! TS `InMemoryTransactionHistoryStorage`'s default merge: the chain
//! reports tx data in pieces (a `proposed` event arrives before
//! `confirmed`; identifiers fan in over multiple blocks for partial
//! successes), and we want every later piece to layer onto the entry
//! the wallet already knows about.

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};

/// Hex-encoded transaction hash. Same shape as the indexer reports.
pub type TransactionHash = String;

/// Outcome the chain reported for a transaction. Mirrors TS
/// `TransactionHistoryStatus` literals.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransactionHistoryStatus {
    Success,
    Failure,
    PartialSuccess,
}

/// One transaction-history record.
///
/// `shielded` / `unshielded` / `dust` are opaque JSON values so the
/// per-sub-wallet `TransactionHistoryService` ports can write whatever
/// schema they need without dragging the storage layer behind every
/// schema change. Concrete schemas live in each sub-wallet module.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionHistoryEntry {
    /// Hex-encoded ledger transaction hash. Primary key.
    pub hash: TransactionHash,
    /// Protocol version under which the transaction was applied.
    /// Newtype-wrapped via [`ProtocolVersion`] for forward-compat
    /// branding; serializes as a bare number so on-disk JSON is
    /// unchanged from the prior `u32` shape.
    pub protocol_version: ProtocolVersion,
    pub status: TransactionHistoryStatus,
    /// Per-segment identifiers for partial-success cases. `None` when
    /// the chain reported a single segment.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub identifiers: Option<Vec<String>>,
    /// Block timestamp (UNIX millis) if known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timestamp_ms: Option<i64>,
    /// Fees the transaction paid, in the smallest on-chain unit.
    /// `None` when the chain hasn't reported them yet (pre-confirm
    /// rows have a fee estimate, but final fees come post-block).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fees: Option<u128>,
    /// Optional shielded section. Wallet-defined schema, transparent
    /// to the storage layer.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shielded: Option<serde_json::Value>,
    /// Optional unshielded section.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unshielded: Option<serde_json::Value>,
    /// Optional dust section.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dust: Option<serde_json::Value>,
    /// Catch-all for forward compatibility — any field a future
    /// schema introduces lands here on read so we don't lose data on
    /// round-trip through an older binary.
    #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
    pub extra: serde_json::Value,
}

impl TransactionHistoryEntry {
    /// Merge `incoming` into `self`. Newer `Some(_)` fields replace
    /// existing values; `None` fields leave existing data alone.
    /// `extra` objects are merged shallowly (incoming keys win on
    /// conflict). Mirrors TS's default `(existing, incoming) => ({
    /// ...existing, ...incoming })` shape but field-aware so we don't
    /// blow away the chain-reported `fees` with a later
    /// `fees: undefined` payload.
    pub fn merge(&mut self, incoming: Self) {
        // hash + protocol_version + status are always taken from the
        // newer entry — they're identity fields.
        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;
            }
            _ => {}
        }
    }
}

/// Storage interface for transaction-history entries keyed by `hash`.
/// Async because real impls do disk I/O; the in-memory variant is
/// trivially synchronous but keeps the trait signature aligned.
#[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<()>;
    /// Serialize all entries as a UTF-8 JSON array. Convenience for
    /// callers who want a single-blob backup; equivalent to
    /// `serde_json::to_string(&store.get_all().await?)`.
    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
    }
}

/// In-memory `IndexMap`-backed [`TransactionHistoryStorage`].
///
/// Cheap to clone (`Arc` over the inner state). Insertion order
/// matches TS `InMemoryTransactionHistoryStorage.getAll()` — newest
/// entries appear last unless an upsert hits an existing key.
#[derive(Debug, Clone, Default)]
pub struct InMemoryTransactionHistoryStorage {
    inner: Arc<RwLock<IndexMap<TransactionHash, TransactionHistoryEntry>>>,
}

impl InMemoryTransactionHistoryStorage {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Restore from a previously [`TransactionHistoryStorage::serialize`]d
    /// JSON blob. Used to load a backup without going through the disk
    /// path.
    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(())
    }
}

/// Event emitted by [`WatchedTransactionHistoryStorage`] on every
/// mutation. Subscribers project the change into their own UI /
/// notification surface — pair with [`TransactionHistoryStorage::get_all`]
/// for a full snapshot when initialising.
#[derive(Debug, Clone)]
pub enum TxHistoryEvent {
    /// New entry inserted, or existing entry merged with new fields.
    Upserted(Box<TransactionHistoryEntry>),
    /// Entry removed by hash.
    Removed(TransactionHash),
    /// All entries cleared.
    Cleared,
}

/// Wraps any [`TransactionHistoryStorage`] and broadcasts a
/// [`TxHistoryEvent`] on every write. Mirror of TS
/// `TransactionHistoryService` observables — UIs subscribe once and
/// react to upserts / removes / clears without polling `get_all`.
///
/// Built on the shared [`moonproof_utils::EventBus`] so the
/// broadcast plumbing is single-sourced across moonproof's storage
/// wrappers (this + [`crate::pending_tx::WatchedPendingTransactionsStorage`]).
///
/// Cheap to clone (`Arc`-shared inner state). Subscribers via
/// [`WatchedTransactionHistoryStorage::subscribe`] each receive every
/// event from the moment they subscribe forward; pair with
/// [`TransactionHistoryStorage::get_all`] on startup for the initial
/// snapshot.
#[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> {
    /// Wrap `inner` with a broadcast channel of default capacity.
    pub fn new(inner: S) -> Self {
        Self {
            inner: Arc::new(inner),
            events: EventBus::new(),
        }
    }

    /// Wrap `inner` with an explicit channel capacity.
    pub fn with_capacity(inner: S, capacity: usize) -> Self {
        Self {
            inner: Arc::new(inner),
            events: EventBus::with_capacity(capacity),
        }
    }

    /// Subscribe to mutation events. Each receiver sees every event
    /// from the moment of subscription; misses on slow consumers
    /// surface as `RecvError::Lagged`.
    pub fn subscribe(&self) -> broadcast::Receiver<TxHistoryEvent> {
        self.events.subscribe()
    }

    /// Number of currently active subscribers — useful for tests +
    /// for skipping notification work when nobody is listening.
    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(())
    }
}

/// No-op [`TransactionHistoryStorage`]. `upsert` succeeds, every read
/// returns empty. Drop-in for callers that opt out of history without
/// caring about Option<...>.
#[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);
        // intentionally omit fees on the incoming side — must not
        // wipe the existing value
        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());
    }
}