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
//! Deterministic test-wallet helpers. Not a secret-key generator — do not
//! use with real mnemonics.
//!
//! Port of the genesis-wallet derivation in
//! `midnight-local-dev/src/wallet.ts::buildWalletFromHexSeed` and
//! `midnight-local-dev/src/index.ts::GENESIS_MINT_WALLET_SEED`.
//!
//! The genesis wallet's 32-byte seed `0x00..01` has pre-minted NIGHT at
//! block 0 on the harness's `undeployed` network. Every integration test
//! that needs funded UTXOs derives from this seed.
//!
//! The derivation path is **BIP44** under Midnight's coin type (2400):
//!
//! ```text
//! m/44'/2400'/0'/0/0    →  NightExternal  (unshielded receive key)
//! m/44'/2400'/0'/2/0    →  Dust           (fee key)
//! m/44'/2400'/0'/3/0    →  Zswap          (shielded key)
//! ```
//!
//! At present we only derive [`Role::NightExternal`]. Shielded and dust
//! role derivations are added as those sub-wallets land.

use moonproof_ledger::coin_structure::coin::UserAddress;
use moonproof_ledger::ledger::dust::DustSecretKey;
use moonproof_ledger::signatures::{SigningKey, VerifyingKey};
use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};

use crate::abstractions::NetworkId;
use crate::address::UnshieldedAddress;
use crate::error::{Result, WalletError};
use crate::hd::{HDWallet, Role, SecretKey};
use crate::unshielded::ledger_adapter::signing_key_from_bytes;

/// The genesis mint wallet's 32-byte seed — identical to
/// `midnight-local-dev/src/index.ts::GENESIS_MINT_WALLET_SEED`.
///
/// On the `undeployed` harness network, the wallet derived from this seed
/// has pre-minted NIGHT at genesis. Use this seed **only** for tests and
/// local-dev funding — never for a real wallet.
pub const GENESIS_MINT_WALLET_SEED_HEX: &str =
    "0000000000000000000000000000000000000000000000000000000000000001";

/// A deterministic wallet derived from a 32-byte seed, exposing the
/// pre-computed keys and addresses needed to build, sign, and target
/// transactions.
///
/// All fields are public so integration tests can mix and match as needed.
/// The [`SecretKey`] and [`SigningKey`] zeroize on drop.
#[derive(Debug, Clone)]
pub struct Wallet {
    /// BIP44 path `m/44'/2400'/0'/0/0` — the `NightExternal` secret.
    pub night_external_secret: SecretKey,
    /// [`SigningKey`] built from the raw 32 bytes of
    /// [`Self::night_external_secret`]. This is what [`Self::sign`] uses.
    pub signing_key: SigningKey,
    /// Public verifying key; goes into `UtxoSpend.owner` on every input
    /// this wallet spends.
    pub verifying_key: VerifyingKey,
    /// 32-byte [`UserAddress`] = `persistent_hash(verifying_key.binary_vec())`.
    /// This is the `owner` field on ledger [`moonproof_ledger::ledger::structure::UtxoOutput`]s
    /// that pay to this wallet.
    pub user_address: UserAddress,
    /// Canonical `moonproof` representation of the unshielded address.
    pub unshielded_address: UnshieldedAddress,
    /// Bech32m encoding of [`Self::unshielded_address`] under the network
    /// this wallet was built for. What the indexer's GraphQL operations and
    /// the TS SDK expect as a recipient-address string.
    pub bech32_address: String,
    /// Which network the bech32 was encoded for — kept for test diagnostics.
    pub network: NetworkId,
    /// BIP44 path `m/44'/2400'/0'/2/0` — the `Dust` role secret bytes,
    /// fed into [`DustSecretKey::derive_secret_key`] to build the actual
    /// dust key on demand.
    pub dust_role_secret: SecretKey,
    /// BIP44 path `m/44'/2400'/0'/3/0` — the `Zswap` role secret bytes.
    /// The raw 32-byte output here is fed into
    /// [`moonproof_ledger::zswap::keys::Seed::from`] + [`moonproof_ledger::zswap::keys::SecretKeys::from`]
    /// (via [`Self::zswap_secret_keys`]) to derive both the coin secret key
    /// and the encryption secret key the shielded wallet uses.
    pub zswap_role_secret: SecretKey,
}

impl Wallet {
    /// Derive the genesis mint wallet — BIP44 path `m/44'/2400'/0'/0/0`
    /// seeded from [`GENESIS_MINT_WALLET_SEED_HEX`].
    pub fn genesis(network: NetworkId) -> Result<Self> {
        Self::from_hex_seed(GENESIS_MINT_WALLET_SEED_HEX, network)
    }

    /// Derive a wallet from a hex-encoded 32-byte seed. The hex string may
    /// be prefixed with `0x` or not.
    pub fn from_hex_seed(hex_seed: &str, network: NetworkId) -> Result<Self> {
        let trimmed = hex_seed.strip_prefix("0x").unwrap_or(hex_seed);
        let seed = hex::decode(trimmed)
            .map_err(|e| WalletError::InvalidSeed(format!("not valid hex: {e}")))?;
        Self::from_seed(&seed, network)
    }

    /// Derive a wallet from a raw seed (16..=64 bytes, per BIP32). The seed
    /// is *not* a BIP39 phrase-seed — this is the direct master seed. For
    /// BIP39 mnemonic derivation, build the [`HDWallet`] yourself via
    /// [`HDWallet::from_mnemonic`] and call [`Self::from_hd_wallet`].
    pub fn from_seed(seed: &[u8], network: NetworkId) -> Result<Self> {
        let hd = HDWallet::from_seed(seed)?;
        Self::from_hd_wallet(&hd, network)
    }

    /// Derive the `NightExternal` and `Dust` keys at `account=0, index=0`
    /// from an existing [`HDWallet`]. Useful if the caller already owns
    /// the wallet (e.g. from a mnemonic) and wants to avoid re-seeding.
    pub fn from_hd_wallet(hd: &HDWallet, network: NetworkId) -> Result<Self> {
        let secret = hd.account(0).role(Role::NightExternal).derive(0)?;
        let dust_role_secret = hd.account(0).role(Role::Dust).derive(0)?;
        let zswap_role_secret = hd.account(0).role(Role::Zswap).derive(0)?;

        let signing_key = signing_key_from_bytes(secret.as_bytes())?;
        let verifying_key = signing_key.verifying_key();
        let user_address = UserAddress::from(verifying_key.clone());
        let unshielded_address = UnshieldedAddress(user_address.0 .0);
        let bech32_encoded = unshielded_address.encode(&network)?;
        let bech32_address = bech32_encoded.to_string()?;

        Ok(Self {
            night_external_secret: secret,
            signing_key,
            verifying_key,
            user_address,
            unshielded_address,
            bech32_address,
            network,
            dust_role_secret,
            zswap_role_secret,
        })
    }

    /// Raw 32-byte owner bytes — the `[u8; 32]` that goes into
    /// `UnshieldedOutputSpec::owner` when building a transfer to this
    /// wallet.
    #[must_use]
    pub fn owner_bytes(&self) -> [u8; 32] {
        self.user_address.0 .0
    }

    /// Build the dust secret key from this wallet's BIP44-derived dust
    /// role bytes. Each call materializes a fresh [`DustSecretKey`] —
    /// the underlying bytes are copied via `derive_secret_key`'s domain
    /// separator and then zeroize on drop.
    ///
    /// This mirrors `getDustSeed(seed)` from the TS reference's test
    /// utilities (`midnight-wallet/packages/dust-wallet/test/utils.ts`).
    #[must_use]
    pub fn dust_secret_key(&self) -> DustSecretKey {
        DustSecretKey::derive_secret_key(self.dust_role_secret.as_bytes())
    }

    /// Derive the zswap secret keys (coin secret + encryption secret) from
    /// this wallet's BIP44-derived Zswap role bytes.
    ///
    /// Mirrors `ZswapSecretKeys.fromSeed(seed)` in the TS reference: the
    /// 32-byte BIP44 output at `m/44'/2400'/0'/3/0` is wrapped as a
    /// [`moonproof_ledger::zswap::keys::Seed`] and fed through
    /// [`moonproof_ledger::zswap::keys::SecretKeys::from`], which runs the
    /// `midnight:csk` / `midnight:esk` domain-separated hashes to produce
    /// the two secret keys. Every call materializes a fresh pair; the
    /// returned [`ZswapSecretKeys`] zeroizes on drop.
    #[must_use]
    pub fn zswap_secret_keys(&self) -> ZswapSecretKeys {
        let mut bytes = [0u8; 32];
        bytes.copy_from_slice(self.zswap_role_secret.as_bytes());
        let seed = ZswapSeed::from(bytes);
        ZswapSecretKeys::from(seed)
    }

    /// Encode this wallet's shielded **encryption secret key** as a
    /// bech32m `mn_shield-esk_<network>…` string — the payload the
    /// indexer's `connect(viewingKey)` mutation accepts.
    ///
    /// The bech32m payload is `Serializable::serialize(SecretKey)` —
    /// 33 bytes (1 magic-tag byte `0x73` + 32 raw scalar bytes).
    /// The indexer's `try_into_domain` calls
    /// `transient_crypto::encryption::SecretKey::deserialize` which
    /// requires the tagged form; passing the raw 32-byte `repr()`
    /// silently produces a viewing key that decodes to a *different*
    /// scalar, so output ciphertexts encrypted to this wallet's
    /// `enc_public_key()` never decrypt and the indexer reports
    /// `highest_relevant=0` even after the wallet receives shielded
    /// outputs.
    pub fn viewing_key_bech32m(&self) -> Result<String> {
        use moonproof_ledger::serialize::Serializable;
        let keys = self.zswap_secret_keys();
        let mut tagged = Vec::with_capacity(keys.encryption_secret_key.serialized_size().max(33));
        keys.encryption_secret_key
            .serialize(&mut tagged)
            .map_err(|e| WalletError::Bech32(format!("serializing encryption SK: {e}")))?;
        crate::address::MidnightBech32m::new("shield-esk", self.network.clone(), tagged)?
            .to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn genesis_hex_seed_is_32_bytes_of_zeros_with_trailing_one() {
        // Load-bearing: this seed is the protocol-level constant that
        // midnight-node mints NIGHT to at genesis. If it drifts,
        // integration tests will fail in hard-to-debug ways (wallet thinks
        // it's funded, chain says otherwise).
        assert_eq!(GENESIS_MINT_WALLET_SEED_HEX.len(), 64);
        let bytes = hex::decode(GENESIS_MINT_WALLET_SEED_HEX).unwrap();
        assert_eq!(bytes.len(), 32);
        assert_eq!(bytes[31], 1);
        assert!(bytes[..31].iter().all(|&b| b == 0));
    }

    #[test]
    fn genesis_wallet_derives_deterministically() {
        let w1 = Wallet::genesis(NetworkId::Undeployed).unwrap();
        let w2 = Wallet::genesis(NetworkId::Undeployed).unwrap();
        assert_eq!(
            w1.owner_bytes(),
            w2.owner_bytes(),
            "genesis wallet must derive the same address every time — \
             deterministic derivation is load-bearing for harness funding"
        );
        assert_eq!(w1.bech32_address, w2.bech32_address);
    }

    #[test]
    fn from_hex_seed_accepts_0x_prefix() {
        let unprefixed = Wallet::from_hex_seed(
            "0000000000000000000000000000000000000000000000000000000000000002",
            NetworkId::Undeployed,
        )
        .unwrap();
        let prefixed = Wallet::from_hex_seed(
            "0x0000000000000000000000000000000000000000000000000000000000000002",
            NetworkId::Undeployed,
        )
        .unwrap();
        assert_eq!(unprefixed.owner_bytes(), prefixed.owner_bytes());
    }

    #[test]
    fn from_hex_seed_rejects_non_hex() {
        let err = Wallet::from_hex_seed("not-hex", NetworkId::Undeployed).unwrap_err();
        assert!(
            matches!(err, WalletError::InvalidSeed(_)),
            "expected InvalidSeed, got {err:?}"
        );
    }

    #[test]
    fn viewing_key_bech32m_payload_roundtrips_through_serializable() {
        // Load-bearing: the indexer's `connect(viewingKey)` mutation
        // decodes the bech32m payload via
        // `transient_crypto::encryption::SecretKey::deserialize`.  If
        // the wallet emits the raw `repr()` (32 bytes) instead of the
        // tagged `Serializable::serialize` form (33 bytes), the
        // indexer reconstructs a different scalar and outputs
        // encrypted to this wallet's enc_pk are silently classified
        // as not-relevant — `highest_relevant_zswap_end_index` stays
        // at 0 forever even after the wallet receives shielded mints.
        // Regression: the pre-fix `viewing_key_bech32m()` wrote
        // `repr()` and the e2e mint flow showed `relevant=0`.
        use moonproof_ledger::serialize::Deserializable;

        let wallet = Wallet::genesis(NetworkId::Undeployed).unwrap();
        let viewing_key = wallet.viewing_key_bech32m().unwrap();

        // Mirror the indexer's parse: bech32m → bytes → SecretKey.
        let bech32 = crate::address::MidnightBech32m::parse(&viewing_key).unwrap();
        assert_eq!(bech32.type_tag, "shield-esk");
        let mut cursor = &bech32.data[..];
        let reconstructed =
            moonproof_ledger::transient_crypto::encryption::SecretKey::deserialize(&mut cursor, 0)
                .expect("indexer-side SK deserialize must succeed on the bech32m payload");

        // The reconstructed SK must derive the same public key the
        // wallet uses when encrypting outputs.
        let zswap_keys = wallet.zswap_secret_keys();
        let expected_pk = zswap_keys.enc_public_key();
        assert_eq!(
            reconstructed.public_key(),
            expected_pk,
            "indexer-side SK must derive the wallet's enc_pk; otherwise \
             output ciphertexts encrypted to enc_pk won't decrypt for \
             the indexer's relevance classifier"
        );
    }

    #[test]
    fn distinct_seeds_derive_distinct_addresses() {
        let a = Wallet::from_hex_seed(
            "0000000000000000000000000000000000000000000000000000000000000001",
            NetworkId::Undeployed,
        )
        .unwrap();
        let b = Wallet::from_hex_seed(
            "0000000000000000000000000000000000000000000000000000000000000002",
            NetworkId::Undeployed,
        )
        .unwrap();
        assert_ne!(a.owner_bytes(), b.owner_bytes());
        assert_ne!(a.bech32_address, b.bech32_address);
    }

    #[test]
    fn bech32_address_uses_the_selected_network_hrp() {
        let undeployed = Wallet::genesis(NetworkId::Undeployed).unwrap();
        let testnet = Wallet::genesis(NetworkId::TestNet).unwrap();
        // Same owner bytes; different HRP — so the bech32 strings MUST differ.
        assert_eq!(undeployed.owner_bytes(), testnet.owner_bytes());
        assert_ne!(
            undeployed.bech32_address, testnet.bech32_address,
            "bech32 encoding must incorporate network-specific HRP"
        );
    }

    #[test]
    fn zswap_secret_keys_derive_deterministically() {
        // Same seed → same coin & encryption public keys. Load-bearing:
        // shielded-side integration tests rely on the derived public keys
        // staying stable so the indexer can match what the wallet expects.
        let w1 = Wallet::genesis(NetworkId::Undeployed).unwrap();
        let w2 = Wallet::genesis(NetworkId::Undeployed).unwrap();
        let k1 = w1.zswap_secret_keys();
        let k2 = w2.zswap_secret_keys();
        assert_eq!(k1.coin_public_key(), k2.coin_public_key());
        assert_eq!(k1.enc_public_key(), k2.enc_public_key());
    }

    #[test]
    fn zswap_keys_differ_from_night_role_bytes() {
        // Rule out a sneaky misderivation where every role happened to
        // collapse onto the same bytes. The Zswap role runs an additional
        // `midnight:csk`-domain hash before producing the coin secret key,
        // so even if the BIP44 outputs ever coincided, the final coin PK
        // should differ from the raw NightExternal 32-byte secret.
        let w = Wallet::genesis(NetworkId::Undeployed).unwrap();
        let zswap = w.zswap_secret_keys();
        let coin_pk_bytes = zswap.coin_public_key().0 .0;
        let night_bytes: &[u8; 32] = w.night_external_secret.as_bytes();
        assert_ne!(
            &coin_pk_bytes, night_bytes,
            "Zswap coin PK must not equal the NightExternal BIP44 bytes"
        );
    }

    #[test]
    fn distinct_seeds_derive_distinct_zswap_keys() {
        let a = Wallet::from_hex_seed(
            "0000000000000000000000000000000000000000000000000000000000000001",
            NetworkId::Undeployed,
        )
        .unwrap();
        let b = Wallet::from_hex_seed(
            "0000000000000000000000000000000000000000000000000000000000000002",
            NetworkId::Undeployed,
        )
        .unwrap();
        let ka = a.zswap_secret_keys();
        let kb = b.zswap_secret_keys();
        assert_ne!(ka.coin_public_key(), kb.coin_public_key());
        assert_ne!(ka.enc_public_key(), kb.enc_public_key());
    }

    #[test]
    fn same_seed_yields_same_keys_across_networks() {
        // Lace-style invariant: HD derivation is network-independent
        // (`m/44'/2400'/account'/role/index` — no network in the
        // path). Same seed → same owner_bytes / signing_key / coin /
        // enc keys on EVERY network. Only the bech32 encoding
        // rotates per network. Confirms that `session_connect` can
        // re-derive addresses under a new NetworkId without
        // touching the underlying keys.
        let seed = [7u8; 32];
        let undeployed = Wallet::from_seed(&seed, NetworkId::Undeployed).unwrap();
        let preview = Wallet::from_seed(&seed, NetworkId::Preview).unwrap();
        let preprod = Wallet::from_seed(&seed, NetworkId::PreProd).unwrap();

        // Identity (network-INDEPENDENT) — same on every network.
        assert_eq!(undeployed.owner_bytes(), preview.owner_bytes());
        assert_eq!(undeployed.owner_bytes(), preprod.owner_bytes());
        assert_eq!(undeployed.verifying_key, preview.verifying_key);
        assert_eq!(undeployed.verifying_key, preprod.verifying_key);

        // Coin + encryption pubkeys (used by shielded transfer
        // targeting) — also network-INDEPENDENT.
        let z_undeployed = undeployed.zswap_secret_keys();
        let z_preview = preview.zswap_secret_keys();
        let z_preprod = preprod.zswap_secret_keys();
        assert_eq!(z_undeployed.coin_public_key(), z_preview.coin_public_key());
        assert_eq!(z_undeployed.coin_public_key(), z_preprod.coin_public_key());
        assert_eq!(z_undeployed.enc_public_key(), z_preview.enc_public_key());
        assert_eq!(z_undeployed.enc_public_key(), z_preprod.enc_public_key());

        // Bech32 encoding (network-DEPENDENT) — must differ.
        assert_ne!(undeployed.bech32_address, preview.bech32_address);
        assert_ne!(undeployed.bech32_address, preprod.bech32_address);
        assert_ne!(preview.bech32_address, preprod.bech32_address);
    }

    #[test]
    fn signing_key_derived_from_secret_matches_verifying_key() {
        // Regression: signing_key_from_bytes is the shared path used by
        // every transaction-signing flow. If the genesis wallet derives a
        // key that doesn't round-trip, every downstream test silently
        // signs with the wrong key.
        let wallet = Wallet::genesis(NetworkId::Undeployed).unwrap();
        let re_derived = signing_key_from_bytes(wallet.night_external_secret.as_bytes()).unwrap();
        assert_eq!(
            re_derived.verifying_key(),
            wallet.verifying_key,
            "re-deriving the SigningKey from the SAME secret bytes must \
             produce the SAME verifying key — otherwise derivation is \
             non-deterministic and signatures will drift"
        );
    }
}