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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! `DustState` — the dust sub-wallet state machine.
//!
//! Port of `wallet-sdk-dust-wallet`'s `CoreWallet`. Wraps the ledger's
//! [`DustLocalState`] (which already tracks generation info, commitments,
//! and per-UTXO `pending_until` ledger TTLs) with a thin wallet layer that
//! adds:
//!
//! - The wallet's [`DustPublicKey`] (so chain events can be filtered by
//!   ownership during replay).
//! - A `pending_dust` map of nullifier → spent UTXO, used to suppress
//!   spent-but-not-yet-confirmed coins from the available balance and to
//!   support [`DustState::revert_transaction`] when a submitted tx is
//!   rejected.
//! - [`SyncProgress`] / [`ProtocolVersion`] / [`NetworkId`] bookkeeping
//!   that mirrors every other moonproof sub-wallet.
//!
//! The state machine is **pure** — no I/O, no clocks. All time-sensitive
//! transitions (`apply_events_with_changes`, `process_ttls`) take an
//! explicit `Timestamp`. Tests therefore exercise the same code paths as
//! production sync.

use moonproof_ledger::base_crypto::time::{Duration, Timestamp};
use moonproof_ledger::ledger::dust::{
    DustLocalState, DustNullifier, DustParameters, DustPublicKey, DustSecretKey, DustStateChanges,
    QualifiedDustOutput,
};
use moonproof_ledger::ledger::events::Event;
use moonproof_ledger::ledger::structure::{BindingKind, ProofKind, SignatureKind, Transaction};
use moonproof_ledger::storage::Storable;

use crate::abstractions::{NetworkId, ProtocolVersion, SyncProgress};
use crate::dust::ledger_adapter::Db;
use crate::error::{Result, WalletError};

/// A dust UTXO the wallet has spent locally but the chain has not yet
/// confirmed (or rejected). Stored alongside its nullifier so we can match
/// it against the spends in a failed transaction without re-deriving the
/// nullifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PendingDustSpend {
    pub utxo: QualifiedDustOutput,
    pub nullifier: DustNullifier,
}

impl PendingDustSpend {
    #[inline]
    #[must_use]
    pub const fn new(utxo: QualifiedDustOutput, nullifier: DustNullifier) -> Self {
        Self { utxo, nullifier }
    }
}

/// State of one dust sub-wallet.
///
/// This is the moonproof analogue of the TS `CoreWallet` struct. Every
/// transition is a pure function `(state, event) -> state`; the chain-sync
/// loop owns the [`Timestamp`] / event source.
#[derive(Debug, Clone)]
pub struct DustState {
    /// The ledger's local view of dust state — Merkle trees of generation
    /// info & commitments, plus `dust_utxos` keyed by nullifier.
    local: DustLocalState<Db>,
    /// `From<DustSecretKey>` of the secret key that owns this wallet.
    public_key: DustPublicKey,
    /// Dust UTXOs we've spent locally but the chain hasn't confirmed.
    /// Stored as a `Vec` (rather than a hash-map) because
    /// [`DustNullifier`] doesn't implement `Hash` upstream, and the set
    /// is small enough that linear scans are not the bottleneck. Order
    /// is preserved (insertion order) so iteration is reproducible.
    /// Cleared by `apply_events_with_changes` once the underlying UTXO
    /// leaves [`DustLocalState::utxos`].
    pending_dust: Vec<PendingDustSpend>,
    network_id: NetworkId,
    progress: SyncProgress,
    protocol_version: ProtocolVersion,
}

impl DustState {
    /// Build a state that wraps an existing [`DustLocalState`] (e.g. a
    /// snapshot loaded from persistence) and the wallet's secret key.
    #[must_use]
    pub fn init(
        local: DustLocalState<Db>,
        secret_key: &DustSecretKey,
        network_id: NetworkId,
    ) -> Self {
        Self::empty(local, DustPublicKey::from(secret_key.clone()), network_id)
    }

    /// Build an empty state with the given parameters and the secret key's
    /// public key. The dust parameters typically come from the live
    /// network's ledger params.
    #[must_use]
    pub fn init_empty(
        params: DustParameters,
        secret_key: &DustSecretKey,
        network_id: NetworkId,
    ) -> Self {
        Self::empty(
            DustLocalState::new(params),
            DustPublicKey::from(secret_key.clone()),
            network_id,
        )
    }

    /// Lower-level constructor — caller supplies the public key directly.
    /// Useful when the secret key isn't available (e.g. read-only wallets).
    #[must_use]
    pub fn empty(
        local: DustLocalState<Db>,
        public_key: DustPublicKey,
        network_id: NetworkId,
    ) -> Self {
        Self {
            local,
            public_key,
            pending_dust: Vec::new(),
            network_id,
            progress: SyncProgress::default(),
            protocol_version: ProtocolVersion::MIN_SUPPORTED,
        }
    }

    /// Re-hydrate a state from externally-persisted parts. Mirrors the TS
    /// `CoreWallet.restore` constructor.
    #[must_use]
    pub fn restore(
        local: DustLocalState<Db>,
        public_key: DustPublicKey,
        pending_dust: impl IntoIterator<Item = PendingDustSpend>,
        progress: SyncProgress,
        protocol_version: ProtocolVersion,
        network_id: NetworkId,
    ) -> Self {
        Self {
            local,
            public_key,
            pending_dust: pending_dust.into_iter().collect(),
            network_id,
            progress,
            protocol_version,
        }
    }

    // --- Read accessors ---------------------------------------------------

    #[inline]
    #[must_use]
    pub fn local(&self) -> &DustLocalState<Db> {
        &self.local
    }

    #[inline]
    #[must_use]
    pub fn public_key(&self) -> DustPublicKey {
        self.public_key
    }

    #[inline]
    #[must_use]
    pub fn network_id(&self) -> &NetworkId {
        &self.network_id
    }

    #[inline]
    #[must_use]
    pub fn progress(&self) -> SyncProgress {
        self.progress
    }

    #[inline]
    #[must_use]
    pub fn protocol_version(&self) -> ProtocolVersion {
        self.protocol_version
    }

    #[inline]
    #[must_use]
    pub fn parameters(&self) -> DustParameters {
        self.local.params
    }

    /// Iterate over the locally-pending spends in insertion order.
    #[inline]
    pub fn pending(&self) -> impl ExactSizeIterator<Item = &PendingDustSpend> {
        self.pending_dust.iter()
    }

    #[inline]
    #[must_use]
    pub fn pending_len(&self) -> usize {
        self.pending_dust.len()
    }

    /// True if this nullifier corresponds to a locally-pending spend.
    #[inline]
    #[must_use]
    pub fn is_pending(&self, nullifier: &DustNullifier) -> bool {
        self.pending_dust.iter().any(|p| p.nullifier == *nullifier)
    }

    /// Sync time tracked by the underlying [`DustLocalState`] — the ctime
    /// of the last block whose events were applied.
    #[inline]
    #[must_use]
    pub fn sync_time(&self) -> Timestamp {
        self.local.sync_time
    }

    // --- Replace mode setters --------------------------------------------

    /// Mutate the [`SyncProgress`] in place by merging the supplied fields.
    /// `None` fields are kept as-is — matches TS `CoreWallet.updateProgress`.
    #[must_use]
    pub fn update_progress(mut self, update: SyncProgressUpdate) -> Self {
        if let Some(v) = update.applied_index {
            self.progress.applied_index = v;
        }
        if let Some(v) = update.highest_relevant_wallet_index {
            self.progress.highest_relevant_wallet_index = v;
        }
        if let Some(v) = update.highest_index {
            self.progress.highest_index = v;
        }
        if let Some(v) = update.highest_relevant_index {
            self.progress.highest_relevant_index = v;
        }
        if let Some(v) = update.is_connected {
            self.progress.is_connected = v;
        }
        self
    }

    /// Set the protocol version reported by the chain. Mostly cosmetic on
    /// the wallet side; sub-wallets surface it for client-version gating.
    #[must_use]
    pub fn with_protocol_version(mut self, v: ProtocolVersion) -> Self {
        self.protocol_version = v;
        self
    }

    // --- Event replay ----------------------------------------------------

    /// Replay a batch of ledger events into the state and return the
    /// resulting changes (matched-by-`source` list of received/spent UTXOs).
    /// Mirrors TS `CoreWallet.applyEventsWithChanges`.
    ///
    /// Steps in order:
    /// 1. `local.replay_events_with_changes(secret_key, events)` — applies
    ///    every event to the underlying ledger state, capturing per-tx
    ///    changes.
    /// 2. `process_ttls(current_time)` — advances per-UTXO grace-period
    ///    timers and drops UTXOs whose dust value has decayed to zero.
    /// 3. Filter `pending_dust` to drop entries whose underlying UTXO is
    ///    no longer in the local state's available set (chain confirmed
    ///    the spend).
    pub fn apply_events_with_changes<'a>(
        mut self,
        secret_key: &DustSecretKey,
        events: impl IntoIterator<Item = &'a Event<Db>>,
        current_time: Timestamp,
    ) -> Result<(Self, Vec<DustStateChanges>)> {
        let with_changes = self
            .local
            .replay_events_with_changes(secret_key, events)
            .map_err(|e| WalletError::DustReplay(e.to_string()))?;
        let updated = with_changes.result.process_ttls(current_time);

        // Collect the nonces still tracked in the local state's available
        // (non-pending_until) UTXOs. Anything in our local pending_dust
        // whose nonce is no longer present has been confirmed by the
        // chain. We materialize into a Vec because Fr doesn't compose
        // with IndexSet's Hash bound on every code path here.
        let available_nonces: Vec<_> = updated.utxos().map(|u| u.nonce).collect();

        self.local = updated;
        self.pending_dust
            .retain(|p| available_nonces.iter().any(|n| n == &p.utxo.nonce));

        Ok((self, with_changes.changes))
    }

    /// Convenience: replay events but discard per-tx [`DustStateChanges`].
    pub fn apply_events<'a>(
        self,
        secret_key: &DustSecretKey,
        events: impl IntoIterator<Item = &'a Event<Db>>,
        current_time: Timestamp,
    ) -> Result<Self> {
        let (s, _) = self.apply_events_with_changes(secret_key, events, current_time)?;
        Ok(s)
    }

    // --- Local spend bookkeeping -----------------------------------------

    /// Spend the given dust coins through the underlying [`DustLocalState`]
    /// and append each resulting [`UnprovenDustSpend`] to a returned
    /// vector (in input order). The wallet's `pending_dust` is updated to
    /// suppress these coins from the available set until the chain
    /// confirms or rejects the spend.
    ///
    /// Mirrors TS `CoreWallet.spendCoins`.
    pub fn spend_coins(
        mut self,
        secret_key: &DustSecretKey,
        coins: &[CoinWithFee],
        current_time: Timestamp,
    ) -> Result<(Vec<UnprovenDustSpend>, Self)> {
        let mut spends = Vec::with_capacity(coins.len());
        for coin in coins {
            let (next, spend) = self
                .local
                .spend(secret_key, &coin.utxo, coin.fee, current_time)
                .map_err(|e| WalletError::DustSpend(e.to_string()))?;
            self.pending_dust
                .push(PendingDustSpend::new(coin.utxo, spend.old_nullifier));
            self.local = next;
            spends.push(spend);
        }
        Ok((spends, self))
    }

    // --- Failure / rollback ----------------------------------------------

    /// Apply the chain's "failed" verdict for a transaction whose dust
    /// spends originated from this wallet. Looks at every dust spend in
    /// the transaction; for each that matches an entry in `pending_dust`,
    /// advances the underlying [`DustLocalState`]'s grace period past the
    /// spend's `ctime` and drops the entry from `pending_dust`.
    ///
    /// Mirrors TS `CoreWallet.applyFailed`. Used directly by
    /// [`DustState::revert_transaction`].
    #[must_use]
    pub fn apply_failed<S, P, B>(mut self, tx: &Transaction<S, P, B, Db>) -> Self
    where
        S: SignatureKind<Db>,
        P: ProofKind<Db>,
        B: BindingKind<S, P, Db> + Storable<Db>,
    {
        let standard = match tx {
            Transaction::Standard(s) => s,
            Transaction::ClaimRewards(_) => return self,
        };
        let grace = self.local.params.dust_grace_period;
        let mut removed: Vec<DustNullifier> = Vec::new();
        for intent in standard.intents.values() {
            let Some(da) = intent.dust_actions.as_ref() else {
                continue;
            };
            let spend_time: Timestamp = da.ctime;
            let advanced_to = advance_past_grace(spend_time, grace);
            for spend in da.spends.iter_deref() {
                if self
                    .pending_dust
                    .iter()
                    .any(|p| p.nullifier == spend.old_nullifier)
                {
                    self.local = self.local.process_ttls(advanced_to);
                    removed.push(spend.old_nullifier);
                }
            }
        }
        if !removed.is_empty() {
            self.pending_dust
                .retain(|p| !removed.iter().any(|n| n == &p.nullifier));
        }
        self
    }

    /// Alias for [`apply_failed`]. Matches TS `CoreWallet.revertTransaction`.
    #[inline]
    #[must_use]
    pub fn revert_transaction<S, P, B>(self, tx: &Transaction<S, P, B, Db>) -> Self
    where
        S: SignatureKind<Db>,
        P: ProofKind<Db>,
        B: BindingKind<S, P, Db> + Storable<Db>,
    {
        self.apply_failed(tx)
    }
}

// --- Supporting types --------------------------------------------------

/// Optional fields for [`DustState::update_progress`]. Set only the values
/// you want to change; `None` leaves the existing field untouched.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SyncProgressUpdate {
    pub applied_index: Option<u64>,
    pub highest_relevant_wallet_index: Option<u64>,
    pub highest_index: Option<u64>,
    pub highest_relevant_index: Option<u64>,
    pub is_connected: Option<bool>,
}

impl SyncProgressUpdate {
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self {
            applied_index: None,
            highest_relevant_wallet_index: None,
            highest_index: None,
            highest_relevant_index: None,
            is_connected: None,
        }
    }

    #[inline]
    #[must_use]
    pub const fn with_applied_index(mut self, v: u64) -> Self {
        self.applied_index = Some(v);
        self
    }

    #[inline]
    #[must_use]
    pub const fn with_highest_relevant_wallet_index(mut self, v: u64) -> Self {
        self.highest_relevant_wallet_index = Some(v);
        self
    }

    #[inline]
    #[must_use]
    pub const fn with_is_connected(mut self, v: bool) -> Self {
        self.is_connected = Some(v);
        self
    }
}

/// A dust coin paired with the fee value to draw from it. Used to feed
/// [`DustState::spend_coins`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CoinWithFee {
    pub utxo: QualifiedDustOutput,
    pub fee: u128,
}

impl CoinWithFee {
    #[inline]
    #[must_use]
    pub const fn new(utxo: QualifiedDustOutput, fee: u128) -> Self {
        Self { utxo, fee }
    }
}

/// Alias for the unsigned-proof shape of a dust spend produced by
/// [`DustLocalState::spend`] — the form a wallet builds before it has run
/// the spend through a real proving provider.
pub type UnprovenDustSpend = moonproof_ledger::ledger::dust::DustSpend<
    moonproof_ledger::ledger::structure::ProofPreimageMarker,
    Db,
>;

/// Add `grace` seconds onto a `ctime` to clear `pending_until` markers that
/// were set with `ctime + grace`. Saturates at the timestamp ceiling.
///
/// Pulled out so `apply_failed` reads cleanly: we want the grace timer to
/// expire, not to advance the entire chain clock.
#[inline]
fn advance_past_grace(ctime: Timestamp, grace: Duration) -> Timestamp {
    ctime + grace
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_ledger::base_crypto::time::Duration;
    use moonproof_ledger::ledger::dust::DustParameters;

    fn test_params() -> DustParameters {
        DustParameters {
            night_dust_ratio: 1_000,
            generation_decay_rate: 1,
            dust_grace_period: Duration::from_secs(60),
        }
    }

    fn test_secret_key() -> DustSecretKey {
        // Deterministic 32-byte seed — fine for tests.
        let seed = [0x42u8; 32];
        DustSecretKey::derive_secret_key(&seed)
    }

    #[test]
    fn init_empty_starts_with_zero_pending_and_min_protocol() {
        let sk = test_secret_key();
        let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed);
        assert_eq!(s.pending_len(), 0);
        assert_eq!(s.protocol_version(), ProtocolVersion::MIN_SUPPORTED);
        assert_eq!(s.network_id(), &NetworkId::Undeployed);
        assert_eq!(s.local().params.night_dust_ratio, 1_000);
        assert!(!s.progress().is_connected);
        assert_eq!(s.progress().applied_index, 0);
    }

    #[test]
    fn public_key_matches_secret_key_derivation() {
        let sk = test_secret_key();
        let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed);
        assert_eq!(s.public_key(), DustPublicKey::from(sk.clone()));
    }

    #[test]
    fn update_progress_merges_supplied_fields_only() {
        let sk = test_secret_key();
        let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed).update_progress(
            SyncProgressUpdate::new()
                .with_applied_index(42)
                .with_is_connected(true),
        );
        assert_eq!(s.progress().applied_index, 42);
        assert!(s.progress().is_connected);
        // Other fields untouched.
        assert_eq!(s.progress().highest_index, 0);
        assert_eq!(s.progress().highest_relevant_index, 0);
    }

    #[test]
    fn empty_event_replay_is_a_noop_with_no_changes() {
        let sk = test_secret_key();
        let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed);
        let (s2, changes) = s
            .apply_events_with_changes(&sk, std::iter::empty(), Timestamp::from_secs(100))
            .expect("empty replay never errors");
        assert!(changes.is_empty());
        assert_eq!(s2.pending_len(), 0);
    }

    #[test]
    fn restore_round_trips_pending_entries() {
        // Pending entries can be reconstructed without any chain interaction —
        // we only need a nullifier and a UTXO descriptor to repopulate.
        let sk = test_secret_key();
        let pk = DustPublicKey::from(sk.clone());
        let local = DustLocalState::new(test_params());
        // Build a synthetic pending spend just to test the round-trip.
        // Empty pending list also exercises restore for the no-op case.
        let restored = DustState::restore(
            local,
            pk,
            std::iter::empty(),
            SyncProgress {
                applied_index: 7,
                is_connected: true,
                ..Default::default()
            },
            ProtocolVersion(3),
            NetworkId::TestNet,
        );
        assert_eq!(restored.progress().applied_index, 7);
        assert!(restored.progress().is_connected);
        assert_eq!(restored.protocol_version(), ProtocolVersion(3));
        assert_eq!(restored.network_id(), &NetworkId::TestNet);
        assert_eq!(restored.pending_len(), 0);
    }

    #[test]
    fn parameters_proxy_reflects_local_state_params() {
        let sk = test_secret_key();
        let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed);
        assert_eq!(s.parameters().night_dust_ratio, 1_000);
        assert_eq!(s.parameters().generation_decay_rate, 1);
        assert_eq!(s.parameters().dust_grace_period.as_seconds(), 60);
    }

    #[test]
    fn revert_transaction_on_claim_rewards_is_a_noop() {
        // ClaimRewards txs have no dust_actions so the revert path is a
        // no-op. Just exercise the type to make sure Signaturish/Proofish
        // bounds satisfy.
        let sk = test_secret_key();
        let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed);
        // We can't easily construct a ClaimRewards tx without a lot of
        // ceremony; ensure the apply_failed signature compiles for our
        // canonical dust-action-bearing intent shape via a unit test in
        // ledger_adapter.rs once that lands. For now: pending_len after
        // construction is 0, no panic from the no-op accessors.
        assert_eq!(s.pending_len(), 0);
    }
}