Skip to main content

moonproof_wallet/
hd.rs

1//! BIP32 + BIP44 HD derivation for Midnight wallets.
2//!
3//! Ported from `@midnight-ntwrk/wallet-sdk-hd`. Path layout:
4//!
5//! ```text
6//! m / 44' / 2400' / account' / role / index
7//! ```
8//!
9//! - `44'` — BIP44 purpose (hardened)
10//! - `2400'` — Midnight's registered coin type (hardened)
11//! - `account'` — hardened account index
12//! - `role` — which key family (see [`Role`]); NOT hardened
13//! - `index` — child index within the role; NOT hardened
14//!
15//! The TS reference uses `@scure/bip32` over secp256k1; we use the
16//! [`bip32`] crate which implements the same BIP32 algorithm over the same
17//! curve, so derivations produce bit-identical keys from a given seed.
18//!
19//! All derived secret material zeroizes on drop (via [`SecretKey`]).
20
21use bip32::{DerivationPath, XPrv};
22use zeroize::{Zeroize, ZeroizeOnDrop};
23
24use crate::error::{Result, WalletError};
25
26/// BIP44 `purpose` field — 44 (hardened on-path).
27const PURPOSE: u32 = 44;
28/// Midnight's registered BIP44 `coin_type`.
29const COIN_TYPE: u32 = 2400;
30
31/// Which key family to derive under an account.
32///
33/// Role values are encoded as the unhardened child index at path depth 4.
34/// They match the TS reference exactly so mnemonics are portable across
35/// implementations.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
37#[repr(u32)]
38pub enum Role {
39    /// External (recipient-facing) shielded addresses.
40    NightExternal = 0,
41    /// Internal (change) shielded addresses.
42    NightInternal = 1,
43    /// DUST fee-token keys.
44    Dust = 2,
45    /// Zswap shielded-coin secret keys.
46    Zswap = 3,
47    /// Reserved for internal wallet metadata.
48    Metadata = 4,
49}
50
51impl Role {
52    /// All roles, for composite derivation / enumeration.
53    pub const ALL: [Role; 5] = [
54        Role::NightExternal,
55        Role::NightInternal,
56        Role::Dust,
57        Role::Zswap,
58        Role::Metadata,
59    ];
60
61    #[inline]
62    #[must_use]
63    pub fn as_child_number(self) -> u32 {
64        self as u32
65    }
66}
67
68/// A 32-byte secret key derived from the HD tree.
69///
70/// Bytes are zeroed on drop. Cloning is intentional and cheap (32-byte copy);
71/// every clone gets its own zeroize-on-drop.
72#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
73pub struct SecretKey([u8; 32]);
74
75impl SecretKey {
76    #[inline]
77    #[must_use]
78    pub fn as_bytes(&self) -> &[u8; 32] {
79        &self.0
80    }
81
82    /// Move the inner bytes out. Caller is responsible for zeroizing if needed.
83    #[inline]
84    #[must_use]
85    pub fn into_bytes(mut self) -> [u8; 32] {
86        let out = self.0;
87        self.0.zeroize();
88        // Prevent ZeroizeOnDrop from running twice; the bytes are already copied out.
89        std::mem::forget(self);
90        out
91    }
92}
93
94impl std::fmt::Debug for SecretKey {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        // Never print secret bytes — even in debug contexts.
97        f.debug_struct("SecretKey")
98            .field("bytes", &"[redacted]")
99            .finish()
100    }
101}
102
103/// A BIP32 HD wallet root. Constructed from a mnemonic (via BIP39) or a raw
104/// 64-byte seed, then narrowed stepwise through [`AccountKey`] and
105/// [`RoleKey`].
106///
107/// The root key holds its private material until [`HDWallet::clear`] is
108/// called (or the struct is dropped).
109pub struct HDWallet {
110    root: XPrv,
111}
112
113impl HDWallet {
114    /// Build a wallet from a BIP32 master seed (16..=64 bytes, typically 64).
115    pub fn from_seed(seed: &[u8]) -> Result<Self> {
116        if !(16..=64).contains(&seed.len()) {
117            return Err(WalletError::SeedLength(seed.len()));
118        }
119        let root = XPrv::new(seed).map_err(|e| WalletError::Derivation(e.to_string()))?;
120        Ok(Self { root })
121    }
122
123    /// Build a wallet from a BIP39 mnemonic phrase. The phrase is validated
124    /// against the English wordlist and an optional passphrase is applied
125    /// per BIP39.
126    pub fn from_mnemonic(phrase: &str, passphrase: &str) -> Result<Self> {
127        let mnemonic =
128            bip39::Mnemonic::parse(phrase).map_err(|e| WalletError::Mnemonic(e.to_string()))?;
129        let seed = mnemonic.to_seed(passphrase);
130        Self::from_seed(&seed)
131    }
132
133    /// Step 1: select a BIP44 `account'` (hardened).
134    #[inline]
135    #[must_use]
136    pub fn account(&self, account: u32) -> AccountKey<'_> {
137        AccountKey {
138            root: &self.root,
139            account,
140        }
141    }
142
143    /// Zero out the private material held by this wallet. The wallet is no
144    /// longer usable for derivation after this call.
145    pub fn clear(self) {
146        // Dropping `self` triggers `XPrv::drop`, which zeroes the secret.
147        // We accept `self` by value to make the consumption explicit.
148        drop(self);
149    }
150}
151
152/// Narrowed to a specific BIP44 account. Cheap view into [`HDWallet`].
153pub struct AccountKey<'a> {
154    root: &'a XPrv,
155    account: u32,
156}
157
158impl AccountKey<'_> {
159    /// Step 2a: select a single [`Role`].
160    #[inline]
161    #[must_use]
162    pub fn role(&self, role: Role) -> RoleKey<'_> {
163        RoleKey {
164            root: self.root,
165            account: self.account,
166            role,
167        }
168    }
169
170    /// Step 2b: select multiple roles at once. Cheaper than repeated
171    /// `role(...)` calls when deriving the same index across all roles,
172    /// because the first three levels of the BIP32 path (`m/44'/2400'/account'`)
173    /// are derived once and reused.
174    pub fn roles<'a>(&'a self, roles: &'a [Role]) -> CompositeRoleKey<'a> {
175        CompositeRoleKey {
176            root: self.root,
177            account: self.account,
178            roles,
179        }
180    }
181}
182
183/// Narrowed to a specific role; final step is [`RoleKey::derive`] with an
184/// index.
185pub struct RoleKey<'a> {
186    root: &'a XPrv,
187    account: u32,
188    role: Role,
189}
190
191impl RoleKey<'_> {
192    /// Derive the 32-byte secret at `m/44'/2400'/account'/role/index`.
193    pub fn derive(&self, index: u32) -> Result<SecretKey> {
194        let path = build_path(self.account, self.role, index)?;
195        derive_key(self.root, &path)
196    }
197}
198
199/// Narrowed to multiple roles under one account. Derives all of them at
200/// a given index in one call.
201pub struct CompositeRoleKey<'a> {
202    root: &'a XPrv,
203    account: u32,
204    roles: &'a [Role],
205}
206
207impl CompositeRoleKey<'_> {
208    /// Derive one secret key per role at the given index. The return vector
209    /// preserves the order of `roles` passed to [`AccountKey::roles`].
210    pub fn derive(&self, index: u32) -> Result<Vec<(Role, SecretKey)>> {
211        // Pre-derive the common prefix m/44'/2400'/account' once so each role
212        // only walks two more steps (role + index) instead of five.
213        let prefix = build_prefix(self.account)?;
214        let prefix_key = derive_xprv(self.root, &prefix)?;
215
216        let mut out = Vec::with_capacity(self.roles.len());
217        for role in self.roles {
218            let path: DerivationPath = format!("m/{}/{}", role.as_child_number(), index)
219                .parse()
220                .map_err(|e: bip32::Error| WalletError::Derivation(e.to_string()))?;
221            let key = derive_key(&prefix_key, &path)?;
222            out.push((*role, key));
223        }
224        Ok(out)
225    }
226}
227
228fn build_path(account: u32, role: Role, index: u32) -> Result<DerivationPath> {
229    format!(
230        "m/{PURPOSE}'/{COIN_TYPE}'/{account}'/{}/{index}",
231        role.as_child_number()
232    )
233    .parse()
234    .map_err(|e: bip32::Error| WalletError::Derivation(e.to_string()))
235}
236
237fn build_prefix(account: u32) -> Result<DerivationPath> {
238    format!("m/{PURPOSE}'/{COIN_TYPE}'/{account}'")
239        .parse()
240        .map_err(|e: bip32::Error| WalletError::Derivation(e.to_string()))
241}
242
243fn derive_xprv(root: &XPrv, path: &DerivationPath) -> Result<XPrv> {
244    let mut current = root.clone();
245    for child in path.iter() {
246        current = current
247            .derive_child(child)
248            .map_err(|e| WalletError::Derivation(e.to_string()))?;
249    }
250    Ok(current)
251}
252
253fn derive_key(root: &XPrv, path: &DerivationPath) -> Result<SecretKey> {
254    let derived = derive_xprv(root, path)?;
255    let bytes = derived.to_bytes();
256    if bytes.iter().all(|b| *b == 0) {
257        // BIP32 spec: a zero private key is invalid; the caller should retry
258        // with the next index.
259        return Err(WalletError::KeyOutOfBounds);
260    }
261    let mut out = [0u8; 32];
262    out.copy_from_slice(bytes.as_slice());
263    Ok(SecretKey(out))
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    /// BIP32 Test Vector 1 master seed (from RFC; widely used across libraries).
271    const BIP32_TEST_SEED_HEX: &str = "000102030405060708090a0b0c0d0e0f";
272
273    #[test]
274    fn roles_map_to_expected_child_numbers() {
275        assert_eq!(Role::NightExternal.as_child_number(), 0);
276        assert_eq!(Role::NightInternal.as_child_number(), 1);
277        assert_eq!(Role::Dust.as_child_number(), 2);
278        assert_eq!(Role::Zswap.as_child_number(), 3);
279        assert_eq!(Role::Metadata.as_child_number(), 4);
280    }
281
282    #[test]
283    fn rejects_out_of_range_seed() {
284        let too_short = [0u8; 8];
285        assert!(matches!(
286            HDWallet::from_seed(&too_short),
287            Err(WalletError::SeedLength(8))
288        ));
289    }
290
291    #[test]
292    fn derives_deterministically_from_seed() {
293        let seed = hex::decode(BIP32_TEST_SEED_HEX).unwrap();
294        let wallet = HDWallet::from_seed(&seed).expect("valid seed");
295
296        let k1 = wallet
297            .account(0)
298            .role(Role::NightExternal)
299            .derive(0)
300            .expect("derive");
301        let k2 = wallet
302            .account(0)
303            .role(Role::NightExternal)
304            .derive(0)
305            .expect("derive again");
306        assert_eq!(k1.as_bytes(), k2.as_bytes(), "derivation is deterministic");
307    }
308
309    #[test]
310    fn different_indices_produce_different_keys() {
311        let seed = hex::decode(BIP32_TEST_SEED_HEX).unwrap();
312        let wallet = HDWallet::from_seed(&seed).expect("valid seed");
313
314        let k0 = wallet
315            .account(0)
316            .role(Role::NightExternal)
317            .derive(0)
318            .unwrap();
319        let k1 = wallet
320            .account(0)
321            .role(Role::NightExternal)
322            .derive(1)
323            .unwrap();
324        assert_ne!(k0.as_bytes(), k1.as_bytes());
325    }
326
327    #[test]
328    fn different_roles_produce_different_keys() {
329        let seed = hex::decode(BIP32_TEST_SEED_HEX).unwrap();
330        let wallet = HDWallet::from_seed(&seed).expect("valid seed");
331
332        let external = wallet
333            .account(0)
334            .role(Role::NightExternal)
335            .derive(0)
336            .unwrap();
337        let internal = wallet
338            .account(0)
339            .role(Role::NightInternal)
340            .derive(0)
341            .unwrap();
342        let dust = wallet.account(0).role(Role::Dust).derive(0).unwrap();
343        let zswap = wallet.account(0).role(Role::Zswap).derive(0).unwrap();
344
345        assert_ne!(external.as_bytes(), internal.as_bytes());
346        assert_ne!(external.as_bytes(), dust.as_bytes());
347        assert_ne!(external.as_bytes(), zswap.as_bytes());
348        assert_ne!(internal.as_bytes(), dust.as_bytes());
349    }
350
351    #[test]
352    fn different_accounts_produce_different_keys() {
353        let seed = hex::decode(BIP32_TEST_SEED_HEX).unwrap();
354        let wallet = HDWallet::from_seed(&seed).expect("valid seed");
355
356        let a0 = wallet.account(0).role(Role::Zswap).derive(0).unwrap();
357        let a1 = wallet.account(1).role(Role::Zswap).derive(0).unwrap();
358        assert_ne!(a0.as_bytes(), a1.as_bytes());
359    }
360
361    #[test]
362    fn composite_derivation_matches_per_role_derivation() {
363        let seed = hex::decode(BIP32_TEST_SEED_HEX).unwrap();
364        let wallet = HDWallet::from_seed(&seed).expect("valid seed");
365        let account = wallet.account(0);
366
367        let composite = account.roles(&Role::ALL).derive(7).expect("composite");
368        for (role, k_composite) in &composite {
369            let k_single = account.role(*role).derive(7).unwrap();
370            assert_eq!(
371                k_composite.as_bytes(),
372                k_single.as_bytes(),
373                "role {role:?} diverged between composite and single derivation",
374            );
375        }
376    }
377
378    #[test]
379    fn from_mnemonic_round_trip() {
380        // Canonical BIP39 test-vector 12-word mnemonic (all-zeros entropy).
381        let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
382        let wallet = HDWallet::from_mnemonic(phrase, "").expect("valid mnemonic");
383        let key = wallet
384            .account(0)
385            .role(Role::NightExternal)
386            .derive(0)
387            .expect("derive");
388        // We don't assert a specific vector (no official Midnight test vector
389        // yet); we only assert the call succeeds and produces 32 non-zero
390        // bytes, so any regression in BIP32/BIP39 plumbing is caught.
391        assert_eq!(key.as_bytes().len(), 32);
392        assert!(key.as_bytes().iter().any(|b| *b != 0));
393    }
394
395    #[test]
396    fn secret_key_debug_is_redacted() {
397        let key = SecretKey([0xABu8; 32]);
398        let s = format!("{key:?}");
399        assert!(!s.contains("ABAB"), "debug leaked secret bytes: {s}");
400        assert!(s.contains("redacted"));
401    }
402
403    /// BIP32 Test Vector 1 from <https://en.bitcoin.it/wiki/BIP_0032_TestVectors>.
404    /// Proves bit-for-bit compatibility with other BIP32 implementations
405    /// (including the `@scure/bip32` used by the TS reference).
406    ///
407    /// We derive at `m/0'/1/2'/2/1000000000` by going through
408    /// `XPrv::derive_child` directly (bypassing our Midnight-specific
409    /// path builder), then assert the known private key.
410    #[test]
411    fn bip32_test_vector_1_interop() {
412        use bip32::{ChildNumber, XPrv};
413
414        let seed = hex::decode("000102030405060708090a0b0c0d0e0f").unwrap();
415        let root = XPrv::new(&seed).expect("valid seed");
416
417        // m/0'
418        let k1 = root
419            .derive_child(ChildNumber::new(0, true).unwrap())
420            .unwrap();
421        // m/0'/1
422        let k2 = k1
423            .derive_child(ChildNumber::new(1, false).unwrap())
424            .unwrap();
425        // m/0'/1/2'
426        let k3 = k2.derive_child(ChildNumber::new(2, true).unwrap()).unwrap();
427        // m/0'/1/2'/2
428        let k4 = k3
429            .derive_child(ChildNumber::new(2, false).unwrap())
430            .unwrap();
431        // m/0'/1/2'/2/1000000000
432        let k5 = k4
433            .derive_child(ChildNumber::new(1_000_000_000, false).unwrap())
434            .unwrap();
435
436        let got = hex::encode(k5.to_bytes());
437        let expected = "471b76e389e528d6de6d816857e012c5455051cad6660850e58372a6c3e6e7c8";
438        assert_eq!(
439            got, expected,
440            "BIP32 derivation diverged from the standard — wallet is NOT interoperable with @scure/bip32"
441        );
442    }
443
444    /// Ensures our Midnight-path derivation uses the same hardened-bit
445    /// conventions as the TS reference (`purpose`, `coin_type`, `account`
446    /// hardened; role, index NOT hardened).
447    #[test]
448    fn midnight_path_hardening_matches_ts_reference() {
449        use bip32::{ChildNumber, XPrv};
450
451        let seed = [1u8; 32];
452        let wallet = HDWallet::from_seed(&seed).unwrap();
453        let via_api = wallet
454            .account(0)
455            .role(Role::NightExternal)
456            .derive(0)
457            .unwrap();
458
459        // Manual derivation with the exact hardening pattern the TS uses:
460        // m/44'/2400'/0'/0/0  (44, 2400, 0 hardened; 0, 0 not hardened).
461        let root = XPrv::new(&seed).unwrap();
462        let k = root
463            .derive_child(ChildNumber::new(44, true).unwrap())
464            .and_then(|k| k.derive_child(ChildNumber::new(2400, true).unwrap()))
465            .and_then(|k| k.derive_child(ChildNumber::new(0, true).unwrap()))
466            .and_then(|k| k.derive_child(ChildNumber::new(0, false).unwrap()))
467            .and_then(|k| k.derive_child(ChildNumber::new(0, false).unwrap()))
468            .unwrap();
469
470        assert_eq!(
471            via_api.as_bytes(),
472            &k.to_bytes(),
473            "HDWallet API diverged from the expected BIP44 hardened-bit layout"
474        );
475    }
476}