moonproof_wallet/testing.rs
1//! Deterministic test-wallet helpers. Not a secret-key generator — do not
2//! use with real mnemonics.
3//!
4//! Port of the genesis-wallet derivation in
5//! `midnight-local-dev/src/wallet.ts::buildWalletFromHexSeed` and
6//! `midnight-local-dev/src/index.ts::GENESIS_MINT_WALLET_SEED`.
7//!
8//! The genesis wallet's 32-byte seed `0x00..01` has pre-minted NIGHT at
9//! block 0 on the harness's `undeployed` network. Every integration test
10//! that needs funded UTXOs derives from this seed.
11//!
12//! The derivation path is **BIP44** under Midnight's coin type (2400):
13//!
14//! ```text
15//! m/44'/2400'/0'/0/0 → NightExternal (unshielded receive key)
16//! m/44'/2400'/0'/2/0 → Dust (fee key)
17//! m/44'/2400'/0'/3/0 → Zswap (shielded key)
18//! ```
19//!
20//! At present we only derive [`Role::NightExternal`]. Shielded and dust
21//! role derivations are added as those sub-wallets land.
22
23use moonproof_ledger::coin_structure::coin::UserAddress;
24use moonproof_ledger::ledger::dust::DustSecretKey;
25use moonproof_ledger::signatures::{SigningKey, VerifyingKey};
26use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
27
28use crate::abstractions::NetworkId;
29use crate::address::UnshieldedAddress;
30use crate::error::{Result, WalletError};
31use crate::hd::{HDWallet, Role, SecretKey};
32use crate::unshielded::ledger_adapter::signing_key_from_bytes;
33
34/// The genesis mint wallet's 32-byte seed — identical to
35/// `midnight-local-dev/src/index.ts::GENESIS_MINT_WALLET_SEED`.
36///
37/// On the `undeployed` harness network, the wallet derived from this seed
38/// has pre-minted NIGHT at genesis. Use this seed **only** for tests and
39/// local-dev funding — never for a real wallet.
40pub const GENESIS_MINT_WALLET_SEED_HEX: &str =
41 "0000000000000000000000000000000000000000000000000000000000000001";
42
43/// A deterministic wallet derived from a 32-byte seed, exposing the
44/// pre-computed keys and addresses needed to build, sign, and target
45/// transactions.
46///
47/// All fields are public so integration tests can mix and match as needed.
48/// The [`SecretKey`] and [`SigningKey`] zeroize on drop.
49#[derive(Debug, Clone)]
50pub struct Wallet {
51 /// BIP44 path `m/44'/2400'/0'/0/0` — the `NightExternal` secret.
52 pub night_external_secret: SecretKey,
53 /// [`SigningKey`] built from the raw 32 bytes of
54 /// [`Self::night_external_secret`]. This is what [`Self::sign`] uses.
55 pub signing_key: SigningKey,
56 /// Public verifying key; goes into `UtxoSpend.owner` on every input
57 /// this wallet spends.
58 pub verifying_key: VerifyingKey,
59 /// 32-byte [`UserAddress`] = `persistent_hash(verifying_key.binary_vec())`.
60 /// This is the `owner` field on ledger [`moonproof_ledger::ledger::structure::UtxoOutput`]s
61 /// that pay to this wallet.
62 pub user_address: UserAddress,
63 /// Canonical `moonproof` representation of the unshielded address.
64 pub unshielded_address: UnshieldedAddress,
65 /// Bech32m encoding of [`Self::unshielded_address`] under the network
66 /// this wallet was built for. What the indexer's GraphQL operations and
67 /// the TS SDK expect as a recipient-address string.
68 pub bech32_address: String,
69 /// Which network the bech32 was encoded for — kept for test diagnostics.
70 pub network: NetworkId,
71 /// BIP44 path `m/44'/2400'/0'/2/0` — the `Dust` role secret bytes,
72 /// fed into [`DustSecretKey::derive_secret_key`] to build the actual
73 /// dust key on demand.
74 pub dust_role_secret: SecretKey,
75 /// BIP44 path `m/44'/2400'/0'/3/0` — the `Zswap` role secret bytes.
76 /// The raw 32-byte output here is fed into
77 /// [`moonproof_ledger::zswap::keys::Seed::from`] + [`moonproof_ledger::zswap::keys::SecretKeys::from`]
78 /// (via [`Self::zswap_secret_keys`]) to derive both the coin secret key
79 /// and the encryption secret key the shielded wallet uses.
80 pub zswap_role_secret: SecretKey,
81}
82
83impl Wallet {
84 /// Derive the genesis mint wallet — BIP44 path `m/44'/2400'/0'/0/0`
85 /// seeded from [`GENESIS_MINT_WALLET_SEED_HEX`].
86 pub fn genesis(network: NetworkId) -> Result<Self> {
87 Self::from_hex_seed(GENESIS_MINT_WALLET_SEED_HEX, network)
88 }
89
90 /// Derive a wallet from a hex-encoded 32-byte seed. The hex string may
91 /// be prefixed with `0x` or not.
92 pub fn from_hex_seed(hex_seed: &str, network: NetworkId) -> Result<Self> {
93 let trimmed = hex_seed.strip_prefix("0x").unwrap_or(hex_seed);
94 let seed = hex::decode(trimmed)
95 .map_err(|e| WalletError::InvalidSeed(format!("not valid hex: {e}")))?;
96 Self::from_seed(&seed, network)
97 }
98
99 /// Derive a wallet from a raw seed (16..=64 bytes, per BIP32). The seed
100 /// is *not* a BIP39 phrase-seed — this is the direct master seed. For
101 /// BIP39 mnemonic derivation, build the [`HDWallet`] yourself via
102 /// [`HDWallet::from_mnemonic`] and call [`Self::from_hd_wallet`].
103 pub fn from_seed(seed: &[u8], network: NetworkId) -> Result<Self> {
104 let hd = HDWallet::from_seed(seed)?;
105 Self::from_hd_wallet(&hd, network)
106 }
107
108 /// Derive the `NightExternal` and `Dust` keys at `account=0, index=0`
109 /// from an existing [`HDWallet`]. Useful if the caller already owns
110 /// the wallet (e.g. from a mnemonic) and wants to avoid re-seeding.
111 pub fn from_hd_wallet(hd: &HDWallet, network: NetworkId) -> Result<Self> {
112 let secret = hd.account(0).role(Role::NightExternal).derive(0)?;
113 let dust_role_secret = hd.account(0).role(Role::Dust).derive(0)?;
114 let zswap_role_secret = hd.account(0).role(Role::Zswap).derive(0)?;
115
116 let signing_key = signing_key_from_bytes(secret.as_bytes())?;
117 let verifying_key = signing_key.verifying_key();
118 let user_address = UserAddress::from(verifying_key.clone());
119 let unshielded_address = UnshieldedAddress(user_address.0 .0);
120 let bech32_encoded = unshielded_address.encode(&network)?;
121 let bech32_address = bech32_encoded.to_string()?;
122
123 Ok(Self {
124 night_external_secret: secret,
125 signing_key,
126 verifying_key,
127 user_address,
128 unshielded_address,
129 bech32_address,
130 network,
131 dust_role_secret,
132 zswap_role_secret,
133 })
134 }
135
136 /// Raw 32-byte owner bytes — the `[u8; 32]` that goes into
137 /// `UnshieldedOutputSpec::owner` when building a transfer to this
138 /// wallet.
139 #[must_use]
140 pub fn owner_bytes(&self) -> [u8; 32] {
141 self.user_address.0 .0
142 }
143
144 /// Build the dust secret key from this wallet's BIP44-derived dust
145 /// role bytes. Each call materializes a fresh [`DustSecretKey`] —
146 /// the underlying bytes are copied via `derive_secret_key`'s domain
147 /// separator and then zeroize on drop.
148 ///
149 /// This mirrors `getDustSeed(seed)` from the TS reference's test
150 /// utilities (`midnight-wallet/packages/dust-wallet/test/utils.ts`).
151 #[must_use]
152 pub fn dust_secret_key(&self) -> DustSecretKey {
153 DustSecretKey::derive_secret_key(self.dust_role_secret.as_bytes())
154 }
155
156 /// Derive the zswap secret keys (coin secret + encryption secret) from
157 /// this wallet's BIP44-derived Zswap role bytes.
158 ///
159 /// Mirrors `ZswapSecretKeys.fromSeed(seed)` in the TS reference: the
160 /// 32-byte BIP44 output at `m/44'/2400'/0'/3/0` is wrapped as a
161 /// [`moonproof_ledger::zswap::keys::Seed`] and fed through
162 /// [`moonproof_ledger::zswap::keys::SecretKeys::from`], which runs the
163 /// `midnight:csk` / `midnight:esk` domain-separated hashes to produce
164 /// the two secret keys. Every call materializes a fresh pair; the
165 /// returned [`ZswapSecretKeys`] zeroizes on drop.
166 #[must_use]
167 pub fn zswap_secret_keys(&self) -> ZswapSecretKeys {
168 let mut bytes = [0u8; 32];
169 bytes.copy_from_slice(self.zswap_role_secret.as_bytes());
170 let seed = ZswapSeed::from(bytes);
171 ZswapSecretKeys::from(seed)
172 }
173
174 /// Encode this wallet's shielded **encryption secret key** as a
175 /// bech32m `mn_shield-esk_<network>…` string — the payload the
176 /// indexer's `connect(viewingKey)` mutation accepts.
177 ///
178 /// The bech32m payload is `Serializable::serialize(SecretKey)` —
179 /// 33 bytes (1 magic-tag byte `0x73` + 32 raw scalar bytes).
180 /// The indexer's `try_into_domain` calls
181 /// `transient_crypto::encryption::SecretKey::deserialize` which
182 /// requires the tagged form; passing the raw 32-byte `repr()`
183 /// silently produces a viewing key that decodes to a *different*
184 /// scalar, so output ciphertexts encrypted to this wallet's
185 /// `enc_public_key()` never decrypt and the indexer reports
186 /// `highest_relevant=0` even after the wallet receives shielded
187 /// outputs.
188 pub fn viewing_key_bech32m(&self) -> Result<String> {
189 use moonproof_ledger::serialize::Serializable;
190 let keys = self.zswap_secret_keys();
191 let mut tagged = Vec::with_capacity(keys.encryption_secret_key.serialized_size().max(33));
192 keys.encryption_secret_key
193 .serialize(&mut tagged)
194 .map_err(|e| WalletError::Bech32(format!("serializing encryption SK: {e}")))?;
195 crate::address::MidnightBech32m::new("shield-esk", self.network.clone(), tagged)?
196 .to_string()
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203
204 #[test]
205 fn genesis_hex_seed_is_32_bytes_of_zeros_with_trailing_one() {
206 // Load-bearing: this seed is the protocol-level constant that
207 // midnight-node mints NIGHT to at genesis. If it drifts,
208 // integration tests will fail in hard-to-debug ways (wallet thinks
209 // it's funded, chain says otherwise).
210 assert_eq!(GENESIS_MINT_WALLET_SEED_HEX.len(), 64);
211 let bytes = hex::decode(GENESIS_MINT_WALLET_SEED_HEX).unwrap();
212 assert_eq!(bytes.len(), 32);
213 assert_eq!(bytes[31], 1);
214 assert!(bytes[..31].iter().all(|&b| b == 0));
215 }
216
217 #[test]
218 fn genesis_wallet_derives_deterministically() {
219 let w1 = Wallet::genesis(NetworkId::Undeployed).unwrap();
220 let w2 = Wallet::genesis(NetworkId::Undeployed).unwrap();
221 assert_eq!(
222 w1.owner_bytes(),
223 w2.owner_bytes(),
224 "genesis wallet must derive the same address every time — \
225 deterministic derivation is load-bearing for harness funding"
226 );
227 assert_eq!(w1.bech32_address, w2.bech32_address);
228 }
229
230 #[test]
231 fn from_hex_seed_accepts_0x_prefix() {
232 let unprefixed = Wallet::from_hex_seed(
233 "0000000000000000000000000000000000000000000000000000000000000002",
234 NetworkId::Undeployed,
235 )
236 .unwrap();
237 let prefixed = Wallet::from_hex_seed(
238 "0x0000000000000000000000000000000000000000000000000000000000000002",
239 NetworkId::Undeployed,
240 )
241 .unwrap();
242 assert_eq!(unprefixed.owner_bytes(), prefixed.owner_bytes());
243 }
244
245 #[test]
246 fn from_hex_seed_rejects_non_hex() {
247 let err = Wallet::from_hex_seed("not-hex", NetworkId::Undeployed).unwrap_err();
248 assert!(
249 matches!(err, WalletError::InvalidSeed(_)),
250 "expected InvalidSeed, got {err:?}"
251 );
252 }
253
254 #[test]
255 fn viewing_key_bech32m_payload_roundtrips_through_serializable() {
256 // Load-bearing: the indexer's `connect(viewingKey)` mutation
257 // decodes the bech32m payload via
258 // `transient_crypto::encryption::SecretKey::deserialize`. If
259 // the wallet emits the raw `repr()` (32 bytes) instead of the
260 // tagged `Serializable::serialize` form (33 bytes), the
261 // indexer reconstructs a different scalar and outputs
262 // encrypted to this wallet's enc_pk are silently classified
263 // as not-relevant — `highest_relevant_zswap_end_index` stays
264 // at 0 forever even after the wallet receives shielded mints.
265 // Regression: the pre-fix `viewing_key_bech32m()` wrote
266 // `repr()` and the e2e mint flow showed `relevant=0`.
267 use moonproof_ledger::serialize::Deserializable;
268
269 let wallet = Wallet::genesis(NetworkId::Undeployed).unwrap();
270 let viewing_key = wallet.viewing_key_bech32m().unwrap();
271
272 // Mirror the indexer's parse: bech32m → bytes → SecretKey.
273 let bech32 = crate::address::MidnightBech32m::parse(&viewing_key).unwrap();
274 assert_eq!(bech32.type_tag, "shield-esk");
275 let mut cursor = &bech32.data[..];
276 let reconstructed =
277 moonproof_ledger::transient_crypto::encryption::SecretKey::deserialize(&mut cursor, 0)
278 .expect("indexer-side SK deserialize must succeed on the bech32m payload");
279
280 // The reconstructed SK must derive the same public key the
281 // wallet uses when encrypting outputs.
282 let zswap_keys = wallet.zswap_secret_keys();
283 let expected_pk = zswap_keys.enc_public_key();
284 assert_eq!(
285 reconstructed.public_key(),
286 expected_pk,
287 "indexer-side SK must derive the wallet's enc_pk; otherwise \
288 output ciphertexts encrypted to enc_pk won't decrypt for \
289 the indexer's relevance classifier"
290 );
291 }
292
293 #[test]
294 fn distinct_seeds_derive_distinct_addresses() {
295 let a = Wallet::from_hex_seed(
296 "0000000000000000000000000000000000000000000000000000000000000001",
297 NetworkId::Undeployed,
298 )
299 .unwrap();
300 let b = Wallet::from_hex_seed(
301 "0000000000000000000000000000000000000000000000000000000000000002",
302 NetworkId::Undeployed,
303 )
304 .unwrap();
305 assert_ne!(a.owner_bytes(), b.owner_bytes());
306 assert_ne!(a.bech32_address, b.bech32_address);
307 }
308
309 #[test]
310 fn bech32_address_uses_the_selected_network_hrp() {
311 let undeployed = Wallet::genesis(NetworkId::Undeployed).unwrap();
312 let testnet = Wallet::genesis(NetworkId::TestNet).unwrap();
313 // Same owner bytes; different HRP — so the bech32 strings MUST differ.
314 assert_eq!(undeployed.owner_bytes(), testnet.owner_bytes());
315 assert_ne!(
316 undeployed.bech32_address, testnet.bech32_address,
317 "bech32 encoding must incorporate network-specific HRP"
318 );
319 }
320
321 #[test]
322 fn zswap_secret_keys_derive_deterministically() {
323 // Same seed → same coin & encryption public keys. Load-bearing:
324 // shielded-side integration tests rely on the derived public keys
325 // staying stable so the indexer can match what the wallet expects.
326 let w1 = Wallet::genesis(NetworkId::Undeployed).unwrap();
327 let w2 = Wallet::genesis(NetworkId::Undeployed).unwrap();
328 let k1 = w1.zswap_secret_keys();
329 let k2 = w2.zswap_secret_keys();
330 assert_eq!(k1.coin_public_key(), k2.coin_public_key());
331 assert_eq!(k1.enc_public_key(), k2.enc_public_key());
332 }
333
334 #[test]
335 fn zswap_keys_differ_from_night_role_bytes() {
336 // Rule out a sneaky misderivation where every role happened to
337 // collapse onto the same bytes. The Zswap role runs an additional
338 // `midnight:csk`-domain hash before producing the coin secret key,
339 // so even if the BIP44 outputs ever coincided, the final coin PK
340 // should differ from the raw NightExternal 32-byte secret.
341 let w = Wallet::genesis(NetworkId::Undeployed).unwrap();
342 let zswap = w.zswap_secret_keys();
343 let coin_pk_bytes = zswap.coin_public_key().0 .0;
344 let night_bytes: &[u8; 32] = w.night_external_secret.as_bytes();
345 assert_ne!(
346 &coin_pk_bytes, night_bytes,
347 "Zswap coin PK must not equal the NightExternal BIP44 bytes"
348 );
349 }
350
351 #[test]
352 fn distinct_seeds_derive_distinct_zswap_keys() {
353 let a = Wallet::from_hex_seed(
354 "0000000000000000000000000000000000000000000000000000000000000001",
355 NetworkId::Undeployed,
356 )
357 .unwrap();
358 let b = Wallet::from_hex_seed(
359 "0000000000000000000000000000000000000000000000000000000000000002",
360 NetworkId::Undeployed,
361 )
362 .unwrap();
363 let ka = a.zswap_secret_keys();
364 let kb = b.zswap_secret_keys();
365 assert_ne!(ka.coin_public_key(), kb.coin_public_key());
366 assert_ne!(ka.enc_public_key(), kb.enc_public_key());
367 }
368
369 #[test]
370 fn same_seed_yields_same_keys_across_networks() {
371 // Lace-style invariant: HD derivation is network-independent
372 // (`m/44'/2400'/account'/role/index` — no network in the
373 // path). Same seed → same owner_bytes / signing_key / coin /
374 // enc keys on EVERY network. Only the bech32 encoding
375 // rotates per network. Confirms that `session_connect` can
376 // re-derive addresses under a new NetworkId without
377 // touching the underlying keys.
378 let seed = [7u8; 32];
379 let undeployed = Wallet::from_seed(&seed, NetworkId::Undeployed).unwrap();
380 let preview = Wallet::from_seed(&seed, NetworkId::Preview).unwrap();
381 let preprod = Wallet::from_seed(&seed, NetworkId::PreProd).unwrap();
382
383 // Identity (network-INDEPENDENT) — same on every network.
384 assert_eq!(undeployed.owner_bytes(), preview.owner_bytes());
385 assert_eq!(undeployed.owner_bytes(), preprod.owner_bytes());
386 assert_eq!(undeployed.verifying_key, preview.verifying_key);
387 assert_eq!(undeployed.verifying_key, preprod.verifying_key);
388
389 // Coin + encryption pubkeys (used by shielded transfer
390 // targeting) — also network-INDEPENDENT.
391 let z_undeployed = undeployed.zswap_secret_keys();
392 let z_preview = preview.zswap_secret_keys();
393 let z_preprod = preprod.zswap_secret_keys();
394 assert_eq!(z_undeployed.coin_public_key(), z_preview.coin_public_key());
395 assert_eq!(z_undeployed.coin_public_key(), z_preprod.coin_public_key());
396 assert_eq!(z_undeployed.enc_public_key(), z_preview.enc_public_key());
397 assert_eq!(z_undeployed.enc_public_key(), z_preprod.enc_public_key());
398
399 // Bech32 encoding (network-DEPENDENT) — must differ.
400 assert_ne!(undeployed.bech32_address, preview.bech32_address);
401 assert_ne!(undeployed.bech32_address, preprod.bech32_address);
402 assert_ne!(preview.bech32_address, preprod.bech32_address);
403 }
404
405 #[test]
406 fn signing_key_derived_from_secret_matches_verifying_key() {
407 // Regression: signing_key_from_bytes is the shared path used by
408 // every transaction-signing flow. If the genesis wallet derives a
409 // key that doesn't round-trip, every downstream test silently
410 // signs with the wrong key.
411 let wallet = Wallet::genesis(NetworkId::Undeployed).unwrap();
412 let re_derived = signing_key_from_bytes(wallet.night_external_secret.as_bytes()).unwrap();
413 assert_eq!(
414 re_derived.verifying_key(),
415 wallet.verifying_key,
416 "re-deriving the SigningKey from the SAME secret bytes must \
417 produce the SAME verifying key — otherwise derivation is \
418 non-deterministic and signatures will drift"
419 );
420 }
421}