moonproof-wallet 0.2.2

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
//! [`FacadeState`] — the combined view over the three sub-wallets.
//!
//! Port of the state-tracking half of the TS `WalletFacade` /
//! `FacadeState` pair in
//! `@midnight-ntwrk/wallet-sdk-facade/src/index.ts`. Moonproof drops the
//! `RxJS` observables and the transaction-history service (both deferred —
//! see HANDOVER "Next up" §2/§4); what stays is a plain read-only
//! snapshot the caller holds by value.
//!
//! # What lives here
//!
//! - [`FacadeState`] — a bundle of [`ShieldedState`], [`UnshieldedState`],
//!   [`DustState`] plus a wallet-wide [`SyncProgress`].
//! - [`FacadeSyncProgress`] — the aggregate view that's the min of the
//!   three sub-wallets' applied indexes (that's the point at which all
//!   three are definitely caught up) together with the aggregate
//!   `is_connected = AND across all three`. Mirrors TS
//!   `FacadeState.isSynced = shielded.isStrictlyComplete &&
//!   dust.isStrictlyComplete && unshielded.isStrictlyComplete`.
//!
//! # What does NOT live here
//!
//! - Pending transactions tracker — belongs to a future
//!   `moonproof-pending-transactions` module alongside the runtime loop.
//! - Transaction history storage — same story, future addition.
//! - Per-sub-wallet sync loops — those are the [`crate::facade::sync`]
//!   fan-in driver's job.

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::structure::{LedgerParameters, INITIAL_PARAMETERS};

use crate::abstractions::{NetworkId, ProtocolVersion, SyncProgress};
use crate::dust::DustState;
use crate::shielded::ShieldedState;
use crate::unshielded::UnshieldedState;

/// Aggregate [`SyncProgress`] for all three sub-wallets.
///
/// - `applied_index` = **min** across sub-wallets; represents the tip
///   the facade can safely claim is consistent across all of them.
/// - `highest_index` / `highest_relevant_index` =
///   **max** across sub-wallets; indexes are per-table (transactions vs.
///   dust events vs. shielded events) so they can't be meaningfully
///   summed, but the max gives a useful "furthest observed" signal.
/// - `is_connected` = **AND** across sub-wallets; the facade is
///   connected iff every sub-wallet is.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FacadeSyncProgress {
    pub shielded: SyncProgress,
    pub unshielded: SyncProgress,
    pub dust: SyncProgress,
}

impl FacadeSyncProgress {
    /// Combined connectivity. `true` iff every sub-wallet is connected.
    #[inline]
    #[must_use]
    pub fn is_connected(&self) -> bool {
        self.shielded.is_connected && self.unshielded.is_connected && self.dust.is_connected
    }

    /// `true` iff every sub-wallet is strictly complete
    /// (`applied_index == highest_relevant_wallet_index`) and every
    /// sub-wallet is connected. Mirrors TS `FacadeState.isSynced`.
    #[inline]
    #[must_use]
    pub fn is_strictly_complete(&self) -> bool {
        self.shielded.is_strictly_complete()
            && self.unshielded.is_strictly_complete()
            && self.dust.is_strictly_complete()
    }

    /// Every sub-wallet is complete within `max_gap` of its highest
    /// relevant wallet index AND every sub-wallet is connected.
    #[inline]
    #[must_use]
    pub fn is_complete_within(&self, max_gap: u64) -> bool {
        self.shielded.is_complete_within(max_gap)
            && self.unshielded.is_complete_within(max_gap)
            && self.dust.is_complete_within(max_gap)
    }

    /// Convenience: complete within the default gap
    /// ([`SyncProgress::DEFAULT_MAX_GAP`]) across every sub-wallet.
    #[inline]
    #[must_use]
    pub fn is_complete(&self) -> bool {
        self.is_complete_within(SyncProgress::DEFAULT_MAX_GAP)
    }

    /// Lowest `applied_index` across sub-wallets — the point up to which
    /// every sub-wallet has caught up. Useful for "watermark" semantics
    /// where the caller wants to know "is it safe to reference event N?"
    #[inline]
    #[must_use]
    pub fn min_applied_index(&self) -> u64 {
        self.shielded
            .applied_index
            .min(self.unshielded.applied_index)
            .min(self.dust.applied_index)
    }

    /// Maximum `highest_index` across sub-wallets. Cross-table indexes
    /// aren't directly comparable (a shielded index ≠ an unshielded one)
    /// so this is a diagnostic signal, not a precondition.
    #[inline]
    #[must_use]
    pub fn max_highest_index(&self) -> u64 {
        self.shielded
            .highest_index
            .max(self.unshielded.highest_index)
            .max(self.dust.highest_index)
    }
}

/// The wallet-wide state bundle.
///
/// [`FacadeState`] composes the three sub-wallet states and the
/// cross-cutting [`NetworkId`] / [`ProtocolVersion`]. Each sub-wallet
/// state is owned by value so transitions can be expressed as pure
/// `(state, input) -> state` functions — matches the patterns already
/// established in each sub-wallet.
///
/// `unshielded_progress` is tracked here rather than on
/// [`UnshieldedState`] because the unshielded sub-wallet's state machine
/// is intentionally progress-agnostic (see `unshielded/state.rs`); the
/// facade is the natural home for the cross-wallet view.
#[derive(Debug, Clone)]
pub struct FacadeState {
    pub shielded: ShieldedState,
    pub unshielded: UnshieldedState,
    pub dust: DustState,
    network_id: NetworkId,
    protocol_version: ProtocolVersion,
    unshielded_progress: SyncProgress,
    /// Chain-tip timestamp at the last sync. This is the indexer's
    /// reported chain time, set explicitly via
    /// [`FacadeState::with_chain_tip_ts`] after the sync driver has
    /// folded all subscription batches. Distinct from
    /// [`DustState::sync_time`] (which is the ctime of the last
    /// **applied dust event**) — those diverge when no dust events
    /// have arrived since the last block.
    chain_tip_ts: Timestamp,
    /// Ledger parameters of the block at [`Self::chain_tip_ts`], set
    /// with it by the sync driver. Fees are priced against them; until
    /// the first sync they are the ledger's initial parameters, which
    /// only suit offline construction.
    ledger_parameters: LedgerParameters,
}

impl FacadeState {
    /// Construct a facade over three seeded sub-wallet states. The
    /// sub-wallet states must already have been initialized with the
    /// same [`NetworkId`] as passed here — we don't re-assert, but the
    /// accessors return the facade's copy as the single source of
    /// truth.
    #[must_use]
    pub fn new(
        shielded: ShieldedState,
        unshielded: UnshieldedState,
        dust: DustState,
        network_id: NetworkId,
    ) -> Self {
        Self {
            shielded,
            unshielded,
            dust,
            network_id,
            protocol_version: ProtocolVersion::MIN_SUPPORTED,
            unshielded_progress: SyncProgress::default(),
            chain_tip_ts: Timestamp::from_secs(0),
            ledger_parameters: INITIAL_PARAMETERS,
        }
    }

    /// Chain-tip timestamp from the last sync. Returns `Timestamp::from_secs(0)`
    /// when this state has never been synced against a live indexer.
    #[inline]
    #[must_use]
    pub fn chain_tip_ts(&self) -> Timestamp {
        self.chain_tip_ts
    }

    /// Replace the chain-tip timestamp. Set by the sync driver after
    /// fetching `chain_parameters.chain_time_secs`.
    #[must_use]
    pub fn with_chain_tip_ts(mut self, ts: Timestamp) -> Self {
        self.chain_tip_ts = ts;
        self
    }

    /// Ledger parameters of the block at [`Self::chain_tip_ts`].
    #[inline]
    #[must_use]
    pub fn ledger_parameters(&self) -> &LedgerParameters {
        &self.ledger_parameters
    }

    /// Replace the ledger parameters. Set by the sync driver together
    /// with [`Self::with_chain_tip_ts`], from the same block.
    #[must_use]
    pub fn with_ledger_parameters(mut self, ledger_parameters: LedgerParameters) -> Self {
        self.ledger_parameters = ledger_parameters;
        self
    }

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

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

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

    /// The aggregated progress view across the three sub-wallets plus
    /// the facade-owned unshielded progress.
    #[inline]
    #[must_use]
    pub fn progress(&self) -> FacadeSyncProgress {
        FacadeSyncProgress {
            shielded: self.shielded.progress(),
            unshielded: self.unshielded_progress,
            dust: self.dust.progress(),
        }
    }

    /// The facade-owned unshielded [`SyncProgress`]. Exposed so callers
    /// can query the unshielded sub-wallet's progress without reaching
    /// into [`FacadeState::progress`].
    #[inline]
    #[must_use]
    pub fn unshielded_progress(&self) -> SyncProgress {
        self.unshielded_progress
    }

    /// Convenience alias for
    /// [`FacadeSyncProgress::is_strictly_complete`]. Mirrors TS
    /// `FacadeState.isSynced`.
    #[inline]
    #[must_use]
    pub fn is_synced(&self) -> bool {
        self.progress().is_strictly_complete()
    }

    // --- Mutators ---------------------------------------------------------

    /// Replace the protocol version and return the updated state.
    #[must_use]
    pub fn with_protocol_version(mut self, v: ProtocolVersion) -> Self {
        self.protocol_version = v;
        self.shielded = self.shielded.with_protocol_version(v);
        self.dust = self.dust.with_protocol_version(v);
        self
    }

    /// Update the facade-owned unshielded progress (the sub-wallet
    /// state itself doesn't carry a progress field). Consumed / returned
    /// by value to match the rest of the wallet's transition style.
    #[must_use]
    pub fn with_unshielded_progress(mut self, progress: SyncProgress) -> Self {
        self.unshielded_progress = progress;
        self
    }

    /// Replace the shielded sub-state and return the updated facade.
    #[must_use]
    pub fn with_shielded(mut self, shielded: ShieldedState) -> Self {
        self.shielded = shielded;
        self
    }

    /// Replace the unshielded sub-state and return the updated facade.
    #[must_use]
    pub fn with_unshielded(mut self, unshielded: UnshieldedState) -> Self {
        self.unshielded = unshielded;
        self
    }

    /// Replace the dust sub-state and return the updated facade.
    #[must_use]
    pub fn with_dust(mut self, dust: DustState) -> Self {
        self.dust = dust;
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_ledger::base_crypto::time::Duration;
    use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
    use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};

    fn zswap_keys() -> ZswapSecretKeys {
        ZswapSecretKeys::from(ZswapSeed::from([0x01u8; 32]))
    }

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

    fn dust_sk() -> DustSecretKey {
        DustSecretKey::derive_secret_key(&[0x02u8; 32])
    }

    fn empty_facade() -> FacadeState {
        let sh = ShieldedState::init_empty(&zswap_keys(), NetworkId::Undeployed);
        let un = UnshieldedState::empty();
        let du = DustState::init_empty(dust_params(), &dust_sk(), NetworkId::Undeployed);
        FacadeState::new(sh, un, du, NetworkId::Undeployed)
    }

    #[test]
    fn fresh_facade_is_not_synced_and_not_connected() {
        let f = empty_facade();
        let p = f.progress();
        assert!(!p.is_connected());
        assert!(!p.is_strictly_complete());
        assert!(!f.is_synced());
        assert_eq!(f.network_id(), &NetworkId::Undeployed);
        assert_eq!(f.protocol_version(), ProtocolVersion::MIN_SUPPORTED);
    }

    #[test]
    fn is_synced_requires_all_three_sub_wallets_strictly_complete() {
        // Flip each sub-wallet to strictly complete one at a time and
        // assert the aggregate only flips when all three are ready.
        let f = empty_facade();

        // Neither shielded nor dust is connected — not synced.
        assert!(!f.is_synced());

        // Shielded strictly complete, connected. Others still unsynced.
        let sh =
            f.shielded
                .clone()
                .with_progress_update(Some(10), Some(10), None, None, Some(true));
        let f = f.with_shielded(sh);
        assert!(!f.is_synced());

        // Unshielded synced too — still not enough.
        let un_sync = SyncProgress {
            applied_index: 7,
            highest_relevant_wallet_index: 7,
            is_connected: true,
            ..Default::default()
        };
        let f = f.with_unshielded_progress(un_sync);
        assert!(!f.is_synced());

        // All three synced.
        let dust_sync = crate::dust::SyncProgressUpdate::new()
            .with_applied_index(5)
            .with_highest_relevant_wallet_index(5)
            .with_is_connected(true);
        let du = f.dust.clone().update_progress(dust_sync);
        let f = f.with_dust(du);
        assert!(f.is_synced());
        assert!(f.progress().is_connected());
    }

    #[test]
    fn aggregate_min_and_max_indexes_cross_sub_wallets() {
        let f = empty_facade();
        let f = f.with_unshielded_progress(SyncProgress {
            applied_index: 3,
            highest_index: 100,
            is_connected: true,
            ..Default::default()
        });
        let sh =
            f.shielded
                .clone()
                .with_progress_update(Some(12), None, Some(200), None, Some(true));
        let f = f.with_shielded(sh);
        let du = f.dust.clone().update_progress(
            crate::dust::SyncProgressUpdate::new()
                .with_applied_index(7)
                .with_is_connected(true),
        );
        let f = f.with_dust(du);
        let p = f.progress();
        // min applied: 3 (unshielded)
        assert_eq!(p.min_applied_index(), 3);
        // max highest: 200 (shielded)
        assert_eq!(p.max_highest_index(), 200);
        // is_connected across all three
        assert!(p.is_connected());
    }

    #[test]
    fn with_protocol_version_propagates_to_sub_wallets() {
        let f = empty_facade().with_protocol_version(ProtocolVersion(9));
        assert_eq!(f.protocol_version(), ProtocolVersion(9));
        // The shielded and dust sub-wallets receive the update (the
        // unshielded sub-wallet doesn't carry a protocol version —
        // facade owns it for that wallet).
        assert_eq!(f.shielded.protocol_version(), ProtocolVersion(9));
        assert_eq!(f.dust.protocol_version(), ProtocolVersion(9));
    }

    #[test]
    fn is_complete_within_default_gap_accepts_small_lag() {
        let almost_sync = SyncProgress {
            applied_index: 98,
            highest_relevant_wallet_index: 100,
            is_connected: true,
            ..Default::default()
        };
        let f = empty_facade().with_unshielded_progress(almost_sync);
        let sh =
            f.shielded
                .clone()
                .with_progress_update(Some(99), Some(100), None, None, Some(true));
        let f = f.with_shielded(sh);
        let du = f.dust.clone().update_progress(
            crate::dust::SyncProgressUpdate::new()
                .with_applied_index(100)
                .with_highest_relevant_wallet_index(100)
                .with_is_connected(true),
        );
        let f = f.with_dust(du);
        let p = f.progress();
        assert!(!p.is_strictly_complete(), "lag blocks strict completion");
        assert!(p.is_complete_within(5));
        assert!(p.is_complete());
    }

    #[test]
    fn unshielded_progress_is_readable_alongside_aggregate() {
        let f = empty_facade().with_unshielded_progress(SyncProgress {
            applied_index: 42,
            is_connected: true,
            ..Default::default()
        });
        assert_eq!(f.unshielded_progress().applied_index, 42);
        assert_eq!(f.progress().unshielded.applied_index, 42);
    }

    #[test]
    fn with_shielded_and_with_unshielded_replace_in_place() {
        let f = empty_facade();
        let replaced_sh =
            f.shielded
                .clone()
                .with_progress_update(Some(55), None, None, None, Some(true));
        let f = f.with_shielded(replaced_sh);
        assert_eq!(f.shielded.progress().applied_index, 55);

        // Replace the unshielded state with a new empty one.
        let f = f.with_unshielded(UnshieldedState::empty());
        assert_eq!(f.unshielded.available_len(), 0);
    }

    #[test]
    fn default_facade_sync_progress_is_unconnected_and_zero() {
        let p = FacadeSyncProgress::default();
        assert!(!p.is_connected());
        assert!(!p.is_strictly_complete());
        assert_eq!(p.min_applied_index(), 0);
        assert_eq!(p.max_highest_index(), 0);
    }
}