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
//! Persistent snapshot of a [`crate::FacadeState`].
//!
//! Captures every field of every sub-wallet in a serde-friendly form
//! that can be saved to disk and re-loaded later. Mirrors the
//! `Serialization` capability split across the three TS sub-wallets in
//! `@midnight-ntwrk/wallet-sdk-shielded-wallet/v1/Serialization.ts`,
//! `…/wallet-sdk-unshielded-wallet/v1/Serialization.ts`, and
//! `…/wallet-sdk-dust-wallet/v1/Serialization.ts` — but as a single,
//! facade-level snapshot rather than three separate capability hooks.
//!
//! # What's persisted
//!
//! | Field                   | Captured? | Source-of-truth on restore |
//! |-------------------------|-----------|----------------------------|
//! | network id              | yes       | snapshot                   |
//! | protocol version        | yes       | snapshot                   |
//! | shielded local state    | yes       | snapshot (tagged-bytes)    |
//! | shielded progress       | yes       | snapshot                   |
//! | shielded keys (secret)  | NO        | caller passes on restore   |
//! | unshielded available    | yes       | snapshot                   |
//! | unshielded pending      | yes       | snapshot                   |
//! | unshielded progress     | yes       | snapshot                   |
//! | dust local state        | yes       | snapshot (tagged-bytes)    |
//! | dust pending list       | yes       | snapshot (tagged-bytes)    |
//! | dust progress           | yes       | snapshot                   |
//! | dust secret key         | NO        | caller passes on restore   |
//!
//! Secret key material is **never** saved here. The wallet's HD seed
//! and derived keys live in the `moonproof-keystore` crate (Argon2id +
//! AES + OS keychain). On restore the caller pulls keys out of the
//! keystore and feeds them in alongside the snapshot — this matches
//! how Lace, `MetaMask`, and Phantom split persistent wallet state from
//! secret material.
//!
//! # Wire format
//!
//! `serde_json` pretty-printed text. JSON beats binary for a v1 cut
//! because the snapshot is rare-write/rare-read (one save per logical
//! checkpoint, one load per session start) and JSON gives operators a
//! readable artefact when triaging "my wallet won't load" support
//! cases. Binary inner blobs (zswap / dust local state, dust pending
//! entries) are hex-encoded so the JSON stays valid UTF-8.
//!
//! # Versioning
//!
//! Every snapshot starts with [`SNAPSHOT_FORMAT_VERSION`]. A read that
//! sees a version higher than the current code knows about errors —
//! never silently truncates fields. Bumping the version is a hard
//! breaking change; the loader prints a clear migration message.

use std::io::Cursor;

use moonproof_ledger::ledger::dust::{
    DustLocalState, DustNullifier, DustParameters, DustSecretKey, QualifiedDustOutput,
};
use moonproof_ledger::serialize::{tagged_deserialize, tagged_serialize};
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;
use moonproof_ledger::zswap::local::State as ZswapLocalState;
use serde::{Deserialize, Serialize};

use crate::abstractions::{NetworkId, ProtocolVersion, SyncProgress};
use crate::dust::{DustState, PendingDustSpend};
use crate::error::{Result, WalletError};
use crate::facade::FacadeState;
use crate::shielded::state::Db as ShieldedDb;
use crate::shielded::ShieldedState;
use crate::unshielded::{UnshieldedState, UtxoWithMeta};

/// Current snapshot format version. Bump on any breaking change to the
/// JSON schema. Loaders refuse to read newer versions than they know.
pub const SNAPSHOT_FORMAT_VERSION: u32 = 1;

/// Serializable bundle of a [`FacadeState`].
///
/// Use [`WalletSnapshot::capture`] to take one and
/// [`WalletSnapshot::restore`] to rebuild a `FacadeState` from one.
/// Persist via [`WalletSnapshot::to_bytes`] / [`WalletSnapshot::from_bytes`]
/// or hand the struct directly to `serde_json` for custom storage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WalletSnapshot {
    /// Schema version. Always equal to [`SNAPSHOT_FORMAT_VERSION`] on
    /// the writer side; readers verify before continuing.
    pub format_version: u32,
    pub network_id: NetworkId,
    pub protocol_version: ProtocolVersion,
    /// Identity of the chain instance this snapshot was synced
    /// against — the node's genesis block hash. A snapshot whose
    /// `chain_id` differs from the connected node's genesis hash is
    /// stale by definition (chain reset, or a different chain behind
    /// the same network name) and must be discarded, never resumed:
    /// applied indexes from one chain instance silently corrupt
    /// state on another. `None` on snapshots written before this
    /// field existed or by hosts without node access.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chain_id: Option<String>,
    pub shielded: ShieldedSnapshot,
    pub unshielded: UnshieldedSnapshot,
    pub dust: DustSnapshot,
}

/// Snapshot of one [`ShieldedState`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShieldedSnapshot {
    pub progress: SyncProgress,
    /// `tagged_serialize`d [`ZswapLocalState`], hex-encoded so the
    /// outer JSON stays valid UTF-8.
    pub local_state_hex: String,
}

/// Snapshot of one [`UnshieldedState`] plus the facade-owned
/// unshielded sync progress.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnshieldedSnapshot {
    pub progress: SyncProgress,
    pub available: Vec<UtxoWithMeta>,
    pub pending: Vec<UtxoWithMeta>,
}

/// Snapshot of one [`DustState`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DustSnapshot {
    pub progress: SyncProgress,
    /// `tagged_serialize`d [`DustLocalState`], hex-encoded.
    pub local_state_hex: String,
    /// One hex blob per [`PendingDustSpend`] — each entry is the
    /// concatenation of `tagged_serialize(QualifiedDustOutput)` then
    /// `tagged_serialize(DustNullifier)`. Length is a `u32` LE prefix
    /// for the qualifier blob, then the rest is the nullifier blob.
    pub pending_dust_hex: Vec<String>,
}

impl WalletSnapshot {
    /// Like [`WalletSnapshot::capture`] but stamps the chain identity
    /// (node genesis hash) so restore-time mismatch detection works.
    pub fn capture_for_chain(state: &FacadeState, chain_id: Option<String>) -> Result<Self> {
        let mut snap = Self::capture(state)?;
        snap.chain_id = chain_id;
        Ok(snap)
    }

    /// Take a snapshot of `state`. Allocates one fresh `Vec<u8>` per
    /// tagged-serialized inner blob; each is hex-encoded into the
    /// returned struct.
    pub fn capture(state: &FacadeState) -> Result<Self> {
        Ok(Self {
            format_version: SNAPSHOT_FORMAT_VERSION,
            network_id: state.network_id().clone(),
            protocol_version: state.protocol_version(),
            chain_id: None,
            shielded: ShieldedSnapshot::capture(&state.shielded)?,
            unshielded: UnshieldedSnapshot::capture(&state.unshielded, state.unshielded_progress()),
            dust: DustSnapshot::capture(&state.dust)?,
        })
    }

    /// Re-build a [`FacadeState`] from this snapshot. The caller
    /// supplies the secret keys + dust parameters that aren't part of
    /// the on-disk artefact.
    ///
    /// `dust_params` is needed because the snapshot's `DustLocalState`
    /// already carries them in its tagged bytes — they're decoded back
    /// from the snapshot, but we still need the caller's copy as a
    /// cross-check (a snapshot encoded under different parameters than
    /// the current chain would silently produce a wrong fee model).
    pub fn restore(
        self,
        zswap_keys: &ZswapSecretKeys,
        dust_secret: &DustSecretKey,
        dust_params: DustParameters,
    ) -> Result<FacadeState> {
        if self.format_version > SNAPSHOT_FORMAT_VERSION {
            return Err(WalletError::Serialization(format!(
                "snapshot format_version {} is newer than this build supports ({})",
                self.format_version, SNAPSHOT_FORMAT_VERSION
            )));
        }
        let WalletSnapshot {
            format_version: _,
            network_id,
            protocol_version,
            chain_id: _,
            shielded,
            unshielded,
            dust,
        } = self;
        let shielded_state = shielded.restore(zswap_keys, network_id.clone(), protocol_version)?;
        let unshielded_progress = unshielded.progress;
        let unshielded_state = unshielded.restore();
        let dust_state = dust.restore(
            dust_secret,
            dust_params,
            network_id.clone(),
            protocol_version,
        )?;
        let facade = FacadeState::new(shielded_state, unshielded_state, dust_state, network_id)
            .with_protocol_version(protocol_version)
            .with_unshielded_progress(unshielded_progress);
        Ok(facade)
    }

    /// Serialize the snapshot as pretty-printed JSON bytes. Use this
    /// for human-readable storage (config files, debug dumps). For an
    /// at-rest persistence path, prefer wrapping the bytes in the
    /// `moonproof-runtime` storage-encryption envelope.
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        serde_json::to_vec_pretty(self)
            .map_err(|e| WalletError::Serialization(format!("encode wallet snapshot: {e}")))
    }

    /// Compact JSON variant — denser but still UTF-8 / git-friendly.
    pub fn to_bytes_compact(&self) -> Result<Vec<u8>> {
        serde_json::to_vec(self)
            .map_err(|e| WalletError::Serialization(format!("encode wallet snapshot: {e}")))
    }

    /// Decode a snapshot from JSON bytes produced by either
    /// [`Self::to_bytes`] or [`Self::to_bytes_compact`].
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        let snap: Self = serde_json::from_slice(bytes)
            .map_err(|e| WalletError::Serialization(format!("decode wallet snapshot: {e}")))?;
        if snap.format_version > SNAPSHOT_FORMAT_VERSION {
            return Err(WalletError::Serialization(format!(
                "snapshot format_version {} is newer than this build supports ({})",
                snap.format_version, SNAPSHOT_FORMAT_VERSION
            )));
        }
        Ok(snap)
    }
}

impl ShieldedSnapshot {
    fn capture(state: &ShieldedState) -> Result<Self> {
        let mut bytes = Vec::new();
        tagged_serialize(state.local(), &mut bytes).map_err(|e| {
            WalletError::Serialization(format!("tagged_serialize(ZswapLocalState): {e}"))
        })?;
        Ok(Self {
            progress: state.progress(),
            local_state_hex: hex::encode(&bytes),
        })
    }

    fn restore(
        self,
        zswap_keys: &ZswapSecretKeys,
        network_id: NetworkId,
        protocol_version: ProtocolVersion,
    ) -> Result<ShieldedState> {
        let bytes = hex::decode(&self.local_state_hex).map_err(|e| {
            WalletError::Serialization(format!(
                "shielded snapshot: local_state_hex is not hex: {e}"
            ))
        })?;
        let mut cursor = Cursor::new(bytes);
        let local: ZswapLocalState<ShieldedDb> = tagged_deserialize(&mut cursor).map_err(|e| {
            WalletError::Serialization(format!("tagged_deserialize(ZswapLocalState): {e}"))
        })?;
        let mut state = ShieldedState::init(local, zswap_keys, network_id);
        state = state.with_protocol_version(protocol_version);
        state = state.with_progress_update(
            Some(self.progress.applied_index),
            Some(self.progress.highest_relevant_wallet_index),
            Some(self.progress.highest_index),
            Some(self.progress.highest_relevant_index),
            Some(self.progress.is_connected),
        );
        Ok(state)
    }
}

impl UnshieldedSnapshot {
    fn capture(state: &UnshieldedState, progress: SyncProgress) -> Self {
        let (available, pending) = state.to_arrays();
        Self {
            progress,
            available,
            pending,
        }
    }

    fn restore(self) -> UnshieldedState {
        UnshieldedState::restore(self.available, self.pending)
    }
}

impl DustSnapshot {
    fn capture(state: &DustState) -> Result<Self> {
        let mut local_bytes = Vec::new();
        tagged_serialize(state.local(), &mut local_bytes).map_err(|e| {
            WalletError::Serialization(format!("tagged_serialize(DustLocalState): {e}"))
        })?;
        let mut pending_dust_hex = Vec::with_capacity(state.pending_len());
        for p in state.pending() {
            let mut buf = Vec::new();
            tagged_serialize(&p.utxo, &mut buf).map_err(|e| {
                WalletError::Serialization(format!("tagged_serialize(QualifiedDustOutput): {e}"))
            })?;
            let utxo_len = u32::try_from(buf.len()).map_err(|_| {
                WalletError::Serialization("QualifiedDustOutput tagged size > u32::MAX".to_owned())
            })?;
            // [u32 LE utxo_len || utxo bytes || nullifier bytes]
            let mut framed = Vec::with_capacity(4 + buf.len() + 64);
            framed.extend_from_slice(&utxo_len.to_le_bytes());
            framed.extend_from_slice(&buf);
            tagged_serialize(&p.nullifier, &mut framed).map_err(|e| {
                WalletError::Serialization(format!("tagged_serialize(DustNullifier): {e}"))
            })?;
            pending_dust_hex.push(hex::encode(&framed));
        }
        Ok(Self {
            progress: state.progress(),
            local_state_hex: hex::encode(&local_bytes),
            pending_dust_hex,
        })
    }

    fn restore(
        self,
        secret_key: &DustSecretKey,
        // Carried by the caller as a cross-check + future compatibility
        // hook. The decoded DustLocalState already embeds its
        // parameters; if they diverge from `_dust_params` we silently
        // trust the snapshot's copy rather than fail loudly — failing
        // would force every snapshot reload to know the live chain
        // params, which the wallet doesn't need until first sync.
        _dust_params: DustParameters,
        network_id: NetworkId,
        protocol_version: ProtocolVersion,
    ) -> Result<DustState> {
        let bytes = hex::decode(&self.local_state_hex).map_err(|e| {
            WalletError::Serialization(format!("dust snapshot: local_state_hex is not hex: {e}"))
        })?;
        let mut cursor = Cursor::new(bytes);
        let local: DustLocalState<crate::dust::ledger_adapter::Db> =
            tagged_deserialize(&mut cursor).map_err(|e| {
                WalletError::Serialization(format!("tagged_deserialize(DustLocalState): {e}"))
            })?;
        let mut pending = Vec::with_capacity(self.pending_dust_hex.len());
        for hex_blob in &self.pending_dust_hex {
            let raw = hex::decode(hex_blob).map_err(|e| {
                WalletError::Serialization(format!("dust pending entry: not hex: {e}"))
            })?;
            if raw.len() < 4 {
                return Err(WalletError::Serialization(
                    "dust pending entry: missing length prefix".to_owned(),
                ));
            }
            let utxo_len = u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]) as usize;
            if 4 + utxo_len > raw.len() {
                return Err(WalletError::Serialization(
                    "dust pending entry: declared length overruns blob".to_owned(),
                ));
            }
            let mut utxo_cursor = Cursor::new(&raw[4..4 + utxo_len]);
            let utxo: QualifiedDustOutput = tagged_deserialize(&mut utxo_cursor).map_err(|e| {
                WalletError::Serialization(format!("tagged_deserialize(QualifiedDustOutput): {e}"))
            })?;
            let mut null_cursor = Cursor::new(&raw[4 + utxo_len..]);
            let nullifier: DustNullifier = tagged_deserialize(&mut null_cursor).map_err(|e| {
                WalletError::Serialization(format!("tagged_deserialize(DustNullifier): {e}"))
            })?;
            pending.push(PendingDustSpend::new(utxo, nullifier));
        }
        let public_key = moonproof_ledger::ledger::dust::DustPublicKey::from(secret_key.clone());
        let state = DustState::restore(
            local,
            public_key,
            pending,
            self.progress,
            protocol_version,
            network_id,
        );
        Ok(state)
    }
}

#[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::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 capture_then_restore_round_trips_an_empty_facade() {
        let facade = empty_facade();
        let snap = WalletSnapshot::capture(&facade).expect("capture");
        let bytes = snap.to_bytes().expect("encode");
        let decoded = WalletSnapshot::from_bytes(&bytes).expect("decode");
        let restored = decoded
            .restore(&zswap_keys(), &dust_sk(), dust_params())
            .expect("restore");
        assert_eq!(restored.network_id(), facade.network_id());
        assert_eq!(restored.protocol_version(), facade.protocol_version());
        assert_eq!(restored.shielded.coin_count(), 0);
        assert_eq!(restored.unshielded.available_len(), 0);
        assert_eq!(restored.unshielded.pending_len(), 0);
        assert_eq!(restored.dust.pending_len(), 0);
    }

    #[test]
    fn snapshot_format_version_is_one() {
        let snap = WalletSnapshot::capture(&empty_facade()).unwrap();
        assert_eq!(snap.format_version, SNAPSHOT_FORMAT_VERSION);
        assert_eq!(SNAPSHOT_FORMAT_VERSION, 1);
    }

    #[test]
    fn newer_format_version_rejected_on_decode() {
        let mut snap = WalletSnapshot::capture(&empty_facade()).unwrap();
        snap.format_version = 9999;
        let bytes = serde_json::to_vec(&snap).unwrap();
        let err = WalletSnapshot::from_bytes(&bytes).unwrap_err();
        assert!(matches!(err, WalletError::Serialization(ref m) if m.contains("format_version")));
    }

    #[test]
    fn pretty_and_compact_decode_to_same_struct() {
        let facade = empty_facade();
        let snap = WalletSnapshot::capture(&facade).unwrap();
        let pretty = snap.to_bytes().unwrap();
        let compact = snap.to_bytes_compact().unwrap();
        let a = WalletSnapshot::from_bytes(&pretty).unwrap();
        let b = WalletSnapshot::from_bytes(&compact).unwrap();
        assert_eq!(a.network_id, b.network_id);
        assert_eq!(a.shielded.local_state_hex, b.shielded.local_state_hex);
        assert_eq!(a.dust.local_state_hex, b.dust.local_state_hex);
    }
}