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
//! BIP32 + BIP44 HD derivation for Midnight wallets.
//!
//! Ported from `@midnight-ntwrk/wallet-sdk-hd`. Path layout:
//!
//! ```text
//! m / 44' / 2400' / account' / role / index
//! ```
//!
//! - `44'` — BIP44 purpose (hardened)
//! - `2400'` — Midnight's registered coin type (hardened)
//! - `account'` — hardened account index
//! - `role` — which key family (see [`Role`]); NOT hardened
//! - `index` — child index within the role; NOT hardened
//!
//! The TS reference uses `@scure/bip32` over secp256k1; we use the
//! [`bip32`] crate which implements the same BIP32 algorithm over the same
//! curve, so derivations produce bit-identical keys from a given seed.
//!
//! All derived secret material zeroizes on drop (via [`SecretKey`]).

use bip32::{DerivationPath, XPrv};
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::error::{Result, WalletError};

/// BIP44 `purpose` field — 44 (hardened on-path).
const PURPOSE: u32 = 44;
/// Midnight's registered BIP44 `coin_type`.
const COIN_TYPE: u32 = 2400;

/// Which key family to derive under an account.
///
/// Role values are encoded as the unhardened child index at path depth 4.
/// They match the TS reference exactly so mnemonics are portable across
/// implementations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(u32)]
pub enum Role {
    /// External (recipient-facing) shielded addresses.
    NightExternal = 0,
    /// Internal (change) shielded addresses.
    NightInternal = 1,
    /// DUST fee-token keys.
    Dust = 2,
    /// Zswap shielded-coin secret keys.
    Zswap = 3,
    /// Reserved for internal wallet metadata.
    Metadata = 4,
}

impl Role {
    /// All roles, for composite derivation / enumeration.
    pub const ALL: [Role; 5] = [
        Role::NightExternal,
        Role::NightInternal,
        Role::Dust,
        Role::Zswap,
        Role::Metadata,
    ];

    #[inline]
    #[must_use]
    pub fn as_child_number(self) -> u32 {
        self as u32
    }
}

/// A 32-byte secret key derived from the HD tree.
///
/// Bytes are zeroed on drop. Cloning is intentional and cheap (32-byte copy);
/// every clone gets its own zeroize-on-drop.
#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
pub struct SecretKey([u8; 32]);

impl SecretKey {
    #[inline]
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Move the inner bytes out. Caller is responsible for zeroizing if needed.
    #[inline]
    #[must_use]
    pub fn into_bytes(mut self) -> [u8; 32] {
        let out = self.0;
        self.0.zeroize();
        // Prevent ZeroizeOnDrop from running twice; the bytes are already copied out.
        std::mem::forget(self);
        out
    }
}

impl std::fmt::Debug for SecretKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Never print secret bytes — even in debug contexts.
        f.debug_struct("SecretKey")
            .field("bytes", &"[redacted]")
            .finish()
    }
}

/// A BIP32 HD wallet root. Constructed from a mnemonic (via BIP39) or a raw
/// 64-byte seed, then narrowed stepwise through [`AccountKey`] and
/// [`RoleKey`].
///
/// The root key holds its private material until [`HDWallet::clear`] is
/// called (or the struct is dropped).
pub struct HDWallet {
    root: XPrv,
}

impl HDWallet {
    /// Build a wallet from a BIP32 master seed (16..=64 bytes, typically 64).
    pub fn from_seed(seed: &[u8]) -> Result<Self> {
        if !(16..=64).contains(&seed.len()) {
            return Err(WalletError::SeedLength(seed.len()));
        }
        let root = XPrv::new(seed).map_err(|e| WalletError::Derivation(e.to_string()))?;
        Ok(Self { root })
    }

    /// Build a wallet from a BIP39 mnemonic phrase. The phrase is validated
    /// against the English wordlist and an optional passphrase is applied
    /// per BIP39.
    pub fn from_mnemonic(phrase: &str, passphrase: &str) -> Result<Self> {
        let mnemonic =
            bip39::Mnemonic::parse(phrase).map_err(|e| WalletError::Mnemonic(e.to_string()))?;
        let seed = mnemonic.to_seed(passphrase);
        Self::from_seed(&seed)
    }

    /// Step 1: select a BIP44 `account'` (hardened).
    #[inline]
    #[must_use]
    pub fn account(&self, account: u32) -> AccountKey<'_> {
        AccountKey {
            root: &self.root,
            account,
        }
    }

    /// Zero out the private material held by this wallet. The wallet is no
    /// longer usable for derivation after this call.
    pub fn clear(self) {
        // Dropping `self` triggers `XPrv::drop`, which zeroes the secret.
        // We accept `self` by value to make the consumption explicit.
        drop(self);
    }
}

/// Narrowed to a specific BIP44 account. Cheap view into [`HDWallet`].
pub struct AccountKey<'a> {
    root: &'a XPrv,
    account: u32,
}

impl AccountKey<'_> {
    /// Step 2a: select a single [`Role`].
    #[inline]
    #[must_use]
    pub fn role(&self, role: Role) -> RoleKey<'_> {
        RoleKey {
            root: self.root,
            account: self.account,
            role,
        }
    }

    /// Step 2b: select multiple roles at once. Cheaper than repeated
    /// `role(...)` calls when deriving the same index across all roles,
    /// because the first three levels of the BIP32 path (`m/44'/2400'/account'`)
    /// are derived once and reused.
    pub fn roles<'a>(&'a self, roles: &'a [Role]) -> CompositeRoleKey<'a> {
        CompositeRoleKey {
            root: self.root,
            account: self.account,
            roles,
        }
    }
}

/// Narrowed to a specific role; final step is [`RoleKey::derive`] with an
/// index.
pub struct RoleKey<'a> {
    root: &'a XPrv,
    account: u32,
    role: Role,
}

impl RoleKey<'_> {
    /// Derive the 32-byte secret at `m/44'/2400'/account'/role/index`.
    pub fn derive(&self, index: u32) -> Result<SecretKey> {
        let path = build_path(self.account, self.role, index)?;
        derive_key(self.root, &path)
    }
}

/// Narrowed to multiple roles under one account. Derives all of them at
/// a given index in one call.
pub struct CompositeRoleKey<'a> {
    root: &'a XPrv,
    account: u32,
    roles: &'a [Role],
}

impl CompositeRoleKey<'_> {
    /// Derive one secret key per role at the given index. The return vector
    /// preserves the order of `roles` passed to [`AccountKey::roles`].
    pub fn derive(&self, index: u32) -> Result<Vec<(Role, SecretKey)>> {
        // Pre-derive the common prefix m/44'/2400'/account' once so each role
        // only walks two more steps (role + index) instead of five.
        let prefix = build_prefix(self.account)?;
        let prefix_key = derive_xprv(self.root, &prefix)?;

        let mut out = Vec::with_capacity(self.roles.len());
        for role in self.roles {
            let path: DerivationPath = format!("m/{}/{}", role.as_child_number(), index)
                .parse()
                .map_err(|e: bip32::Error| WalletError::Derivation(e.to_string()))?;
            let key = derive_key(&prefix_key, &path)?;
            out.push((*role, key));
        }
        Ok(out)
    }
}

fn build_path(account: u32, role: Role, index: u32) -> Result<DerivationPath> {
    format!(
        "m/{PURPOSE}'/{COIN_TYPE}'/{account}'/{}/{index}",
        role.as_child_number()
    )
    .parse()
    .map_err(|e: bip32::Error| WalletError::Derivation(e.to_string()))
}

fn build_prefix(account: u32) -> Result<DerivationPath> {
    format!("m/{PURPOSE}'/{COIN_TYPE}'/{account}'")
        .parse()
        .map_err(|e: bip32::Error| WalletError::Derivation(e.to_string()))
}

fn derive_xprv(root: &XPrv, path: &DerivationPath) -> Result<XPrv> {
    let mut current = root.clone();
    for child in path.iter() {
        current = current
            .derive_child(child)
            .map_err(|e| WalletError::Derivation(e.to_string()))?;
    }
    Ok(current)
}

fn derive_key(root: &XPrv, path: &DerivationPath) -> Result<SecretKey> {
    let derived = derive_xprv(root, path)?;
    let bytes = derived.to_bytes();
    if bytes.iter().all(|b| *b == 0) {
        // BIP32 spec: a zero private key is invalid; the caller should retry
        // with the next index.
        return Err(WalletError::KeyOutOfBounds);
    }
    let mut out = [0u8; 32];
    out.copy_from_slice(bytes.as_slice());
    Ok(SecretKey(out))
}

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

    /// BIP32 Test Vector 1 master seed (from RFC; widely used across libraries).
    const BIP32_TEST_SEED_HEX: &str = "000102030405060708090a0b0c0d0e0f";

    #[test]
    fn roles_map_to_expected_child_numbers() {
        assert_eq!(Role::NightExternal.as_child_number(), 0);
        assert_eq!(Role::NightInternal.as_child_number(), 1);
        assert_eq!(Role::Dust.as_child_number(), 2);
        assert_eq!(Role::Zswap.as_child_number(), 3);
        assert_eq!(Role::Metadata.as_child_number(), 4);
    }

    #[test]
    fn rejects_out_of_range_seed() {
        let too_short = [0u8; 8];
        assert!(matches!(
            HDWallet::from_seed(&too_short),
            Err(WalletError::SeedLength(8))
        ));
    }

    #[test]
    fn derives_deterministically_from_seed() {
        let seed = hex::decode(BIP32_TEST_SEED_HEX).unwrap();
        let wallet = HDWallet::from_seed(&seed).expect("valid seed");

        let k1 = wallet
            .account(0)
            .role(Role::NightExternal)
            .derive(0)
            .expect("derive");
        let k2 = wallet
            .account(0)
            .role(Role::NightExternal)
            .derive(0)
            .expect("derive again");
        assert_eq!(k1.as_bytes(), k2.as_bytes(), "derivation is deterministic");
    }

    #[test]
    fn different_indices_produce_different_keys() {
        let seed = hex::decode(BIP32_TEST_SEED_HEX).unwrap();
        let wallet = HDWallet::from_seed(&seed).expect("valid seed");

        let k0 = wallet
            .account(0)
            .role(Role::NightExternal)
            .derive(0)
            .unwrap();
        let k1 = wallet
            .account(0)
            .role(Role::NightExternal)
            .derive(1)
            .unwrap();
        assert_ne!(k0.as_bytes(), k1.as_bytes());
    }

    #[test]
    fn different_roles_produce_different_keys() {
        let seed = hex::decode(BIP32_TEST_SEED_HEX).unwrap();
        let wallet = HDWallet::from_seed(&seed).expect("valid seed");

        let external = wallet
            .account(0)
            .role(Role::NightExternal)
            .derive(0)
            .unwrap();
        let internal = wallet
            .account(0)
            .role(Role::NightInternal)
            .derive(0)
            .unwrap();
        let dust = wallet.account(0).role(Role::Dust).derive(0).unwrap();
        let zswap = wallet.account(0).role(Role::Zswap).derive(0).unwrap();

        assert_ne!(external.as_bytes(), internal.as_bytes());
        assert_ne!(external.as_bytes(), dust.as_bytes());
        assert_ne!(external.as_bytes(), zswap.as_bytes());
        assert_ne!(internal.as_bytes(), dust.as_bytes());
    }

    #[test]
    fn different_accounts_produce_different_keys() {
        let seed = hex::decode(BIP32_TEST_SEED_HEX).unwrap();
        let wallet = HDWallet::from_seed(&seed).expect("valid seed");

        let a0 = wallet.account(0).role(Role::Zswap).derive(0).unwrap();
        let a1 = wallet.account(1).role(Role::Zswap).derive(0).unwrap();
        assert_ne!(a0.as_bytes(), a1.as_bytes());
    }

    #[test]
    fn composite_derivation_matches_per_role_derivation() {
        let seed = hex::decode(BIP32_TEST_SEED_HEX).unwrap();
        let wallet = HDWallet::from_seed(&seed).expect("valid seed");
        let account = wallet.account(0);

        let composite = account.roles(&Role::ALL).derive(7).expect("composite");
        for (role, k_composite) in &composite {
            let k_single = account.role(*role).derive(7).unwrap();
            assert_eq!(
                k_composite.as_bytes(),
                k_single.as_bytes(),
                "role {role:?} diverged between composite and single derivation",
            );
        }
    }

    #[test]
    fn from_mnemonic_round_trip() {
        // Canonical BIP39 test-vector 12-word mnemonic (all-zeros entropy).
        let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let wallet = HDWallet::from_mnemonic(phrase, "").expect("valid mnemonic");
        let key = wallet
            .account(0)
            .role(Role::NightExternal)
            .derive(0)
            .expect("derive");
        // We don't assert a specific vector (no official Midnight test vector
        // yet); we only assert the call succeeds and produces 32 non-zero
        // bytes, so any regression in BIP32/BIP39 plumbing is caught.
        assert_eq!(key.as_bytes().len(), 32);
        assert!(key.as_bytes().iter().any(|b| *b != 0));
    }

    #[test]
    fn secret_key_debug_is_redacted() {
        let key = SecretKey([0xABu8; 32]);
        let s = format!("{key:?}");
        assert!(!s.contains("ABAB"), "debug leaked secret bytes: {s}");
        assert!(s.contains("redacted"));
    }

    /// BIP32 Test Vector 1 from <https://en.bitcoin.it/wiki/BIP_0032_TestVectors>.
    /// Proves bit-for-bit compatibility with other BIP32 implementations
    /// (including the `@scure/bip32` used by the TS reference).
    ///
    /// We derive at `m/0'/1/2'/2/1000000000` by going through
    /// `XPrv::derive_child` directly (bypassing our Midnight-specific
    /// path builder), then assert the known private key.
    #[test]
    fn bip32_test_vector_1_interop() {
        use bip32::{ChildNumber, XPrv};

        let seed = hex::decode("000102030405060708090a0b0c0d0e0f").unwrap();
        let root = XPrv::new(&seed).expect("valid seed");

        // m/0'
        let k1 = root
            .derive_child(ChildNumber::new(0, true).unwrap())
            .unwrap();
        // m/0'/1
        let k2 = k1
            .derive_child(ChildNumber::new(1, false).unwrap())
            .unwrap();
        // m/0'/1/2'
        let k3 = k2.derive_child(ChildNumber::new(2, true).unwrap()).unwrap();
        // m/0'/1/2'/2
        let k4 = k3
            .derive_child(ChildNumber::new(2, false).unwrap())
            .unwrap();
        // m/0'/1/2'/2/1000000000
        let k5 = k4
            .derive_child(ChildNumber::new(1_000_000_000, false).unwrap())
            .unwrap();

        let got = hex::encode(k5.to_bytes());
        let expected = "471b76e389e528d6de6d816857e012c5455051cad6660850e58372a6c3e6e7c8";
        assert_eq!(
            got, expected,
            "BIP32 derivation diverged from the standard — wallet is NOT interoperable with @scure/bip32"
        );
    }

    /// Ensures our Midnight-path derivation uses the same hardened-bit
    /// conventions as the TS reference (`purpose`, `coin_type`, `account`
    /// hardened; role, index NOT hardened).
    #[test]
    fn midnight_path_hardening_matches_ts_reference() {
        use bip32::{ChildNumber, XPrv};

        let seed = [1u8; 32];
        let wallet = HDWallet::from_seed(&seed).unwrap();
        let via_api = wallet
            .account(0)
            .role(Role::NightExternal)
            .derive(0)
            .unwrap();

        // Manual derivation with the exact hardening pattern the TS uses:
        // m/44'/2400'/0'/0/0  (44, 2400, 0 hardened; 0, 0 not hardened).
        let root = XPrv::new(&seed).unwrap();
        let k = root
            .derive_child(ChildNumber::new(44, true).unwrap())
            .and_then(|k| k.derive_child(ChildNumber::new(2400, true).unwrap()))
            .and_then(|k| k.derive_child(ChildNumber::new(0, true).unwrap()))
            .and_then(|k| k.derive_child(ChildNumber::new(0, false).unwrap()))
            .and_then(|k| k.derive_child(ChildNumber::new(0, false).unwrap()))
            .unwrap();

        assert_eq!(
            via_api.as_bytes(),
            &k.to_bytes(),
            "HDWallet API diverged from the expected BIP44 hardened-bit layout"
        );
    }
}