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
//! `ShieldedState` — the shielded (zswap) sub-wallet state machine.
//!
//! Port of `@midnight-ntwrk/wallet-sdk-shielded-wallet/v1/CoreWallet.ts`'s
//! state-only surface. Wraps [`moonproof_ledger::zswap::local::State`] (which
//! already tracks the commitment Merkle tree, the set of owned coins,
//! pending spends, and pending outputs) with a thin wallet layer that
//! adds:
//!
//! - The wallet's [`ZswapSecretKeys`] public keys (coin + encryption), so
//!   callers can read the identity without holding the secret bytes.
//! - Canonical [`NetworkId`] / [`ProtocolVersion`] / [`SyncProgress`]
//!   bookkeeping the facade layer needs.
//! - Apply / apply-failed / spend / watch-for / apply-collapsed-update
//!   transitions that delegate to the underlying [`ZswapLocalState`].
//!
//! The TS reference also maintains a `CoinHashesMap` cache of
//! `nonce → (commitment, nullifier)` to accelerate repeated lookups.
//! Moonproof computes these values on demand (a single persistent-hash
//! each) and skips the cache to keep the state machine small — the
//! cache is a UI optimization, not load-bearing for correctness.

use std::borrow::Cow;
use std::fmt;

use moonproof_ledger::coin_structure::coin::{
    Commitment, Info as CoinInfo, Nonce, Nullifier, PublicKey,
};
use moonproof_ledger::coin_structure::transfer::{Recipient, SenderEvidence};
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;
use moonproof_ledger::zswap::local::State as ZswapLocalState;
use moonproof_ledger::zswap::{Input as ZswapInput, Offer as ZswapOffer};

use crate::abstractions::{NetworkId, ProtocolVersion, SyncProgress};

/// Concrete DB type used throughout the shielded path — mirrors every
/// other moonproof sub-wallet.
pub type Db = InMemoryDB;

/// Alias for the ledger's `zswap::local::State` specialised to
/// [`InMemoryDB`]. Exposed so callers who already have a
/// `ZswapLocalState<D>` can construct a [`ShieldedState`] without
/// reaching into ledger types.
pub type InnerLocalState = ZswapLocalState<Db>;

/// The shielded wallet's local state.
///
/// This is the moonproof analogue of the TS `CoreWallet` struct — state
/// only. Every transition is a pure function `(state, input) -> state`;
/// the sync loop owns the event source.
#[derive(Clone)]
pub struct ShieldedState {
    local: InnerLocalState,
    coin_public_key: PublicKey,
    encryption_public_key: moonproof_ledger::transient_crypto::encryption::PublicKey,
    network_id: NetworkId,
    progress: SyncProgress,
    protocol_version: ProtocolVersion,
}

impl fmt::Debug for ShieldedState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ShieldedState")
            .field("coin_public_key", &self.coin_public_key)
            .field("encryption_public_key", &"<enc pk>")
            .field("network_id", &self.network_id)
            .field("progress", &self.progress)
            .field("protocol_version", &self.protocol_version)
            .field("coin_count", &self.local.coins.size())
            .field("pending_spend_count", &self.local.pending_spends.size())
            .field("pending_output_count", &self.local.pending_outputs.size())
            .field("first_free", &self.local.first_free)
            .finish()
    }
}

impl ShieldedState {
    /// Build a fresh, empty [`ShieldedState`] bound to the given secret
    /// keys and network. Mirrors TS `CoreWallet.initEmpty`.
    #[must_use]
    pub fn init_empty(secret_keys: &ZswapSecretKeys, network_id: NetworkId) -> Self {
        Self {
            local: ZswapLocalState::new(),
            coin_public_key: secret_keys.coin_public_key(),
            encryption_public_key: secret_keys.enc_public_key(),
            network_id,
            progress: SyncProgress::default(),
            protocol_version: ProtocolVersion::MIN_SUPPORTED,
        }
    }

    /// Build a [`ShieldedState`] wrapping an existing [`ZswapLocalState`]
    /// (e.g. a persisted snapshot). Mirrors TS `CoreWallet.init`.
    #[must_use]
    pub fn init(
        local: InnerLocalState,
        secret_keys: &ZswapSecretKeys,
        network_id: NetworkId,
    ) -> Self {
        Self {
            local,
            coin_public_key: secret_keys.coin_public_key(),
            encryption_public_key: secret_keys.enc_public_key(),
            network_id,
            progress: SyncProgress::default(),
            protocol_version: ProtocolVersion::MIN_SUPPORTED,
        }
    }

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

    #[inline]
    pub fn local(&self) -> &InnerLocalState {
        &self.local
    }

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

    #[inline]
    #[must_use]
    pub fn encryption_public_key(
        &self,
    ) -> moonproof_ledger::transient_crypto::encryption::PublicKey {
        self.encryption_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
    }

    /// True if this nullifier corresponds to a spend we've issued locally
    /// but the chain hasn't confirmed or rejected yet. Mirrors the TS
    /// reference's check against `state.pendingSpends`.
    #[inline]
    #[must_use]
    pub fn is_pending_spend(&self, nullifier: &Nullifier) -> bool {
        self.local.pending_spends.contains_key(nullifier)
    }

    /// Count of locally-pending spends (coins we've spent but not yet
    /// seen confirmed).
    #[inline]
    #[must_use]
    pub fn pending_spend_count(&self) -> usize {
        self.local.pending_spends.size()
    }

    /// Count of pending outputs (coins we've emitted to ourselves but
    /// not yet seen the commitment for on chain).
    #[inline]
    #[must_use]
    pub fn pending_output_count(&self) -> usize {
        self.local.pending_outputs.size()
    }

    /// Count of confirmed, unspent coins we own.
    #[inline]
    #[must_use]
    pub fn coin_count(&self) -> usize {
        self.local.coins.size()
    }

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

    /// Merge a collapsed Merkle-tree update into the underlying state.
    /// Mirrors TS `CoreWallet.applyCollapsedUpdate`. Used to skip over
    /// tree slots the wallet doesn't care about (no coin commitments for
    /// this wallet), so that the on-chain Merkle root stays consistent
    /// with our local view.
    pub fn apply_collapsed_update(
        mut self,
        update: &moonproof_ledger::transient_crypto::merkle_tree::MerkleTreeCollapsedUpdate,
    ) -> Result<Self, moonproof_ledger::transient_crypto::merkle_tree::InvalidUpdate> {
        self.local = self.local.apply_collapsed_update(update)?;
        Ok(self)
    }

    /// Apply a [`ZswapOffer`] to the state, updating coins, pending
    /// spends, and pending outputs. Mirrors TS `CoreWallet.apply`.
    ///
    /// The supplied secret keys are used to attempt decryption of each
    /// output's ciphertext — every output whose ciphertext decrypts to a
    /// coin owned by this wallet is inserted into [`InnerLocalState::coins`].
    pub fn apply<P: moonproof_ledger::storage::Storable<Db>>(
        mut self,
        secret_keys: &ZswapSecretKeys,
        offer: &ZswapOffer<P, Db>,
    ) -> Result<Self, moonproof_ledger::transient_crypto::merkle_tree::InvalidUpdate> {
        self.local = self.local.apply(secret_keys, offer)?;
        Ok(self)
    }

    /// Roll back a submitted offer that the chain rejected. Matches TS
    /// `CoreWallet.revertTransaction` and its underlying
    /// `ZswapLocalState.apply_failed`: drop any pending spends / pending
    /// outputs whose nullifiers or commitments show up in the rejected
    /// offer.
    #[must_use]
    pub fn apply_failed<P: moonproof_ledger::storage::Storable<Db>>(
        mut self,
        offer: &ZswapOffer<P, Db>,
    ) -> Self {
        self.local = self.local.apply_failed(offer);
        self
    }

    /// Spend one owned coin, producing a zswap `Input<ProofPreimage, D>`
    /// and the updated state (with the coin moved into `pending_spends`
    /// under its nullifier). Mirrors TS `CoreWallet.spendCoins` for a
    /// single coin.
    ///
    /// `segment` is the transaction segment this spend belongs to — pass
    /// `None` for the guaranteed section (segment 0) or `Some(n)` for a
    /// specific fallible segment.
    pub fn spend<R: rand::Rng + rand::CryptoRng + ?Sized>(
        self,
        rng: &mut R,
        secret_keys: &ZswapSecretKeys,
        coin: &moonproof_ledger::coin_structure::coin::QualifiedInfo,
        segment: Option<u16>,
    ) -> Result<
        (
            Self,
            ZswapInput<moonproof_ledger::transient_crypto::proofs::ProofPreimage, Db>,
        ),
        moonproof_ledger::zswap::error::OfferCreationFailed,
    > {
        let (new_local, input) = self.local.spend(rng, secret_keys, coin, segment)?;
        let next = Self {
            local: new_local,
            ..self
        };
        Ok((next, input))
    }

    /// Track a future output we expect to receive (e.g. a change coin
    /// we're emitting to ourselves). Mirrors TS `CoreWallet.watchCoins`
    /// for one coin.
    #[must_use]
    pub fn watch_for(mut self, coin: &CoinInfo) -> Self {
        self.local = self.local.watch_for(&self.coin_public_key, coin);
        self
    }

    /// Update one or more progress fields in place, leaving unsupplied
    /// fields untouched. Mirrors TS `CoreWallet.updateProgress`.
    #[must_use]
    pub fn with_progress_update(
        mut self,
        applied_index: Option<u64>,
        highest_relevant_wallet_index: Option<u64>,
        highest_index: Option<u64>,
        highest_relevant_index: Option<u64>,
        is_connected: Option<bool>,
    ) -> Self {
        if let Some(v) = applied_index {
            self.progress.applied_index = v;
        }
        if let Some(v) = highest_relevant_wallet_index {
            self.progress.highest_relevant_wallet_index = v;
        }
        if let Some(v) = highest_index {
            self.progress.highest_index = v;
        }
        if let Some(v) = highest_relevant_index {
            self.progress.highest_relevant_index = v;
        }
        if let Some(v) = is_connected {
            self.progress.is_connected = v;
        }
        self
    }

    /// Stamp the protocol version the chain last advertised. Cosmetic on
    /// the wallet side; the facade surfaces it for client-version gating.
    #[must_use]
    pub fn with_protocol_version(mut self, v: ProtocolVersion) -> Self {
        self.protocol_version = v;
        self
    }

    // --- Derived helpers -----------------------------------------------

    /// Compute the commitment for a coin under this wallet's coin public
    /// key. Cheap — a single persistent hash. Used by the balancer's
    /// equality checks and by tests.
    #[must_use]
    pub fn commitment_for(&self, coin: &CoinInfo) -> Commitment {
        coin.commitment(&Recipient::User(self.coin_public_key))
    }

    /// Compute the nullifier for a coin under this wallet's coin secret
    /// key. Requires the [`ZswapSecretKeys`] — [`ShieldedState`] never
    /// stores the secret itself.
    #[must_use]
    pub fn nullifier_for(coin: &CoinInfo, secret_keys: &ZswapSecretKeys) -> Nullifier {
        coin.nullifier(&SenderEvidence::User(Cow::Borrowed(
            &secret_keys.coin_secret_key,
        )))
    }

    /// Collect the nonces of every coin the wallet currently owns
    /// (confirmed, unspent) plus every coin waiting in `pending_outputs`
    /// (a committed output we expect to receive). Order matches the
    /// insertion order of [`InnerLocalState::coins`] followed by
    /// [`InnerLocalState::pending_outputs`]; callers that need a set
    /// should collect into one.
    #[must_use]
    pub fn all_coin_nonces(&self) -> Vec<Nonce> {
        let mut out =
            Vec::with_capacity(self.local.coins.size() + self.local.pending_outputs.size());
        for (_, coin) in self.local.coins.iter() {
            out.push(coin.nonce);
        }
        for (_, coin) in self.local.pending_outputs.iter() {
            out.push(coin.nonce);
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_ledger::coin_structure::coin::{Nonce, ShieldedTokenType};
    use moonproof_ledger::transient_crypto::hash::HashOutput;
    use moonproof_ledger::zswap::keys::Seed as ZswapSeed;

    fn keys_from_byte(b: u8) -> ZswapSecretKeys {
        ZswapSecretKeys::from(ZswapSeed::from([b; 32]))
    }

    fn shielded_coin(nonce_byte: u8, type_byte: u8, value: u128) -> CoinInfo {
        CoinInfo {
            nonce: Nonce(HashOutput([nonce_byte; 32])),
            type_: ShieldedTokenType(HashOutput([type_byte; 32])),
            value,
        }
    }

    #[test]
    fn init_empty_tracks_public_keys_and_network() {
        let keys = keys_from_byte(0x01);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        assert_eq!(s.coin_public_key(), keys.coin_public_key());
        assert_eq!(s.encryption_public_key(), keys.enc_public_key());
        assert_eq!(s.network_id(), &NetworkId::Undeployed);
        assert_eq!(s.protocol_version(), ProtocolVersion::MIN_SUPPORTED);
        assert_eq!(s.coin_count(), 0);
        assert_eq!(s.pending_spend_count(), 0);
        assert_eq!(s.pending_output_count(), 0);
    }

    #[test]
    fn distinct_seeds_produce_distinct_public_keys() {
        let a = ShieldedState::init_empty(&keys_from_byte(0x01), NetworkId::Undeployed);
        let b = ShieldedState::init_empty(&keys_from_byte(0x02), NetworkId::Undeployed);
        assert_ne!(a.coin_public_key(), b.coin_public_key());
        assert_ne!(a.encryption_public_key(), b.encryption_public_key());
    }

    #[test]
    fn with_progress_update_merges_only_supplied_fields() {
        let keys = keys_from_byte(0x03);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let updated = s.with_progress_update(Some(42), None, None, None, Some(true));
        assert_eq!(updated.progress().applied_index, 42);
        assert!(updated.progress().is_connected);
        // Untouched.
        assert_eq!(updated.progress().highest_index, 0);
        assert_eq!(updated.progress().highest_relevant_index, 0);
        assert_eq!(updated.progress().highest_relevant_wallet_index, 0);
    }

    #[test]
    fn commitment_and_nullifier_are_deterministic() {
        let keys = keys_from_byte(0x04);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let coin = shielded_coin(0xAA, 0xBB, 1_000);
        let c1 = s.commitment_for(&coin);
        let c2 = s.commitment_for(&coin);
        assert_eq!(c1, c2);
        let n1 = ShieldedState::nullifier_for(&coin, &keys);
        let n2 = ShieldedState::nullifier_for(&coin, &keys);
        assert_eq!(n1, n2);
    }

    #[test]
    fn commitment_differs_under_different_wallets() {
        let keys_a = keys_from_byte(0x05);
        let keys_b = keys_from_byte(0x06);
        let sa = ShieldedState::init_empty(&keys_a, NetworkId::Undeployed);
        let sb = ShieldedState::init_empty(&keys_b, NetworkId::Undeployed);
        let coin = shielded_coin(0x10, 0x20, 42);
        assert_ne!(
            sa.commitment_for(&coin),
            sb.commitment_for(&coin),
            "commitment binds to coin public key — different wallets must produce different commitments"
        );
    }

    #[test]
    fn watch_for_adds_to_pending_outputs() {
        let keys = keys_from_byte(0x07);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let coin = shielded_coin(0x11, 0x22, 500);
        let after = s.watch_for(&coin);
        assert_eq!(after.pending_output_count(), 1);
        assert_eq!(after.coin_count(), 0);
        // Commitment is known.
        let com = after.commitment_for(&coin);
        assert!(after.local().pending_outputs.contains_key(&com));
    }

    #[test]
    fn init_from_inner_local_state_round_trips() {
        let keys = keys_from_byte(0x08);
        let local = InnerLocalState::new();
        let s = ShieldedState::init(local, &keys, NetworkId::TestNet);
        assert_eq!(s.network_id(), &NetworkId::TestNet);
        assert_eq!(s.coin_public_key(), keys.coin_public_key());
    }

    #[test]
    fn with_protocol_version_is_reflected() {
        let keys = keys_from_byte(0x09);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed)
            .with_protocol_version(ProtocolVersion(7));
        assert_eq!(s.protocol_version(), ProtocolVersion(7));
    }

    #[test]
    fn all_coin_nonces_includes_pending_outputs() {
        let keys = keys_from_byte(0x0A);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let c1 = shielded_coin(0x01, 0xAA, 100);
        let c2 = shielded_coin(0x02, 0xAA, 200);
        let after = s.watch_for(&c1).watch_for(&c2);
        let nonces = after.all_coin_nonces();
        assert_eq!(nonces.len(), 2);
        assert!(nonces.contains(&c1.nonce));
        assert!(nonces.contains(&c2.nonce));
    }

    #[test]
    fn is_pending_spend_false_on_empty_state() {
        let keys = keys_from_byte(0x0B);
        let s = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
        let coin = shielded_coin(0x33, 0x44, 1);
        let nullifier = ShieldedState::nullifier_for(&coin, &keys);
        assert!(!s.is_pending_spend(&nullifier));
    }
}