dig_session/master_seed.rs
1//! The master-SEED unlock path: an unlocked handle over a DIG account's root
2//! HD seed, stored as BIP-39 entropy and re-expanded on demand.
3//!
4//! # Why this exists (the impedance mismatch it closes)
5//!
6//! The 0.2.0 identity path ([`crate::UnlockedIdentity`]) unlocks to the *derived
7//! identity scalar* only — it stores `derive_identity_sk(master).to_bytes()` and
8//! can never reconstruct the master seed. But `dig-wallet-backend`'s
9//! `MasterKey::from_seed_bytes` (the master-HD model, dig_ecosystem #997) needs
10//! the **master seed** to derive every profile's wallet keys. The identity
11//! scalar cannot reconstruct the seed, so a consumer that wants BOTH the
12//! dig-identity key AND a wallet `MasterKey` must persist the root itself.
13//!
14//! # The root is BIP-39 ENTROPY, and the seed is expanded from it
15//!
16//! A 24-word recovery phrase carries an implicit promise: *any* conforming
17//! wallet can restore it. Standard Chia wallets (Sage, the reference client,
18//! `chia-wallet-sdk`) honour that promise as
19//!
20//! ```text
21//! phrase --BIP-39--> 32-byte entropy --PBKDF2("mnemonic", 2048)--> 64-byte seed --EIP-2333--> master SecretKey
22//! ```
23//!
24//! Handing the **entropy** to `SecretKey::from_seed` instead of the expanded
25//! 64-byte seed skips the PBKDF2 step. It does not fail — it derives a
26//! different, entirely plausible wallet, so a user restoring a DIG phrase in
27//! Sage would see an empty account with no error at all. dig_ecosystem #1759.
28//!
29//! This module therefore stores the **32-byte entropy** (which is exactly what
30//! a 24-word phrase encodes, and what the phrase can be regenerated from) and
31//! re-expands it to the [`MASTER_SEED_LEN`]-byte HD seed at
32//! [`master_seed`](UnlockedMasterSeed::master_seed). **Every** derivation —
33//! identity, per-profile DEK, wallet — reads that one expanded seed, so no two
34//! of them can disagree about the root.
35//!
36//! [`UnlockedMasterSeed`] exposes:
37//!
38//! - [`master_seed`](UnlockedMasterSeed::master_seed) — the expanded 64-byte HD
39//! seed, ready to feed to wallet-backend's `MasterKey::from_seed_bytes` (see
40//! the layering note below);
41//! - [`recovery_phrase`](UnlockedMasterSeed::recovery_phrase) — the 24 words,
42//! *without* consuming the handle, so a UI can show them and carry on;
43//! - [`sign`](UnlockedMasterSeed::sign) /
44//! [`public_key`](UnlockedMasterSeed::public_key) — the dig-identity key at
45//! the canonical hardened path;
46//! - [`derive_symmetric_key`](UnlockedMasterSeed::derive_symmetric_key) — the
47//! per-profile DEK, through the frozen `dig-constants` HKDF contract.
48//!
49//! # Layering (@10 reference-DOWN-only, HARD RULE)
50//!
51//! dig-session is a `10-primitives` crate; `MasterKey` is a `20-domain`
52//! (`dig-wallet-backend`) type. This module therefore **must not** depend on
53//! dig-wallet-backend or return a wallet-backend type — that would be an illegal
54//! upward `@10 -> @20` edge. The seed is exposed as PRIMITIVE bytes only; the
55//! app-tier consumer (dig-app) constructs the `MasterKey` itself via
56//! `MasterKey::from_seed_bytes(handle.master_seed().to_vec())`.
57//!
58//! # Why the seed round-trips to the SAME master key everywhere
59//!
60//! Both dig-identity's `master_secret_key_from_seed(seed)` and wallet-backend's
61//! `MasterKey::from_seed_bytes(seed)` reduce to `chia_bls::SecretKey::from_seed(seed)`
62//! (EIP-2333 KeyGen). Handing the identical expanded seed bytes to both
63//! therefore yields the identical master key — which is exactly why the seed
64//! (not a derived scalar) is the value that must be reconstructible.
65//!
66//! # Storage
67//!
68//! The entropy is sealed in a versioned envelope (see [`crate::envelope`]) so a
69//! stored blob DECLARES what its 32 bytes mean. A pre-envelope blob — whose 32
70//! bytes were a raw master seed — fails closed with
71//! [`SessionError::LegacySeedFormat`](crate::SessionError::LegacySeedFormat)
72//! rather than being reinterpreted as entropy.
73
74use std::sync::Arc;
75
76use bip39::{Language, Mnemonic};
77use dig_constants::SYMMETRIC_KEY_LEN;
78use dig_identity::{
79 derive_identity_sk, derive_identity_sk_at, master_secret_key_from_seed, public_key_bytes,
80 sign_message,
81};
82use zeroize::Zeroizing;
83
84use crate::unlocked::derive_symmetric_key_from_scalar;
85use crate::{Result, SessionError};
86
87/// The number of bytes of BIP-39 entropy behind a DIG account — the value
88/// actually stored at rest.
89///
90/// 32 bytes is precisely the entropy of a **24-word** English BIP-39 mnemonic
91/// (256 bits + an 8-bit checksum = 264 bits = 24 × 11), so entropy and phrase
92/// convert both ways losslessly and the phrase is the canonical backup.
93pub const ENTROPY_LEN: usize = 32;
94
95/// The number of bytes in an expanded BIP-39 master HD seed — the value fed to
96/// `chia_bls::SecretKey::from_seed`.
97///
98/// Fixed at 64 by BIP-39: `PBKDF2-HMAC-SHA512(phrase, "mnemonic" || passphrase,
99/// 2048)` emits 512 bits. DIG uses the **empty** passphrase, matching Chia.
100pub const MASTER_SEED_LEN: usize = 64;
101
102/// The number of words in a DIG recovery phrase.
103pub const RECOVERY_PHRASE_WORDS: usize = 24;
104
105/// The number of bytes in a compressed BLS12-381 **G1** identity public key.
106pub const IDENTITY_PUBLIC_KEY_LEN: usize = 48;
107
108/// The number of bytes in a BLS12-381 **G2** AugScheme signature.
109pub const IDENTITY_SIGNATURE_LEN: usize = 96;
110
111/// A standalone identity-signing primitive: a plain callable mapping a message to
112/// a 96-byte G2 signature, carrying no dig-session or dig-identity type.
113///
114/// This is the bare shape [`UnlockedMasterSeed::signing_fn`] hands a downstream so
115/// it can sign while staying identity-agnostic (dig_ecosystem #908). It mirrors
116/// [`crate::SigningFn`] but is expressed over raw byte arrays because the
117/// master-seed path derives the identity key itself rather than exposing a
118/// scheme-parameterized `SignerHandle`.
119pub type IdentitySigningFn = Arc<dyn Fn(&[u8]) -> [u8; IDENTITY_SIGNATURE_LEN] + Send + Sync>;
120
121/// Reconstruct the 24-word mnemonic that `entropy` encodes.
122///
123/// Infallible for [`ENTROPY_LEN`] bytes: BIP-39 accepts any 32-byte entropy and
124/// computes the checksum itself, so there is no invalid input to report.
125///
126/// # Custody note
127///
128/// The returned `Mnemonic`'s word indices are a COMPLETE copy of the account
129/// root, and one is built on every derivation. dig-session therefore enables
130/// bip39's `zeroize` feature, which makes `Mnemonic` `Zeroize + ZeroizeOnDrop`,
131/// so each copy is wiped when it drops. Callers still confine it to the
132/// narrowest possible scope and route the byte/string buffers *we* own through
133/// [`Zeroizing`].
134///
135/// Residual, not fixed by that feature: bip39's own intermediate `to_string()`
136/// heap buffer and its transient `[u8; 33]` entropy+checksum stack array are not
137/// wiped upstream. Both are short-lived and inside bip39; fixing them requires
138/// an upstream change.
139fn mnemonic_from_entropy(entropy: &[u8; ENTROPY_LEN]) -> Mnemonic {
140 Mnemonic::from_entropy_in(Language::English, entropy)
141 .expect("BIP-39 accepts any 32-byte entropy (24 words); length is a compile-time constant")
142}
143
144/// Expand BIP-39 `entropy` into the 64-byte master HD seed, the Chia way:
145/// `entropy -> 24 words -> PBKDF2 with an EMPTY passphrase`.
146///
147/// This is the one function that closes the Sage-parity gap; every derivation in
148/// this module goes through it so none can drift.
149pub(crate) fn expand_entropy(entropy: &[u8; ENTROPY_LEN]) -> Zeroizing<[u8; MASTER_SEED_LEN]> {
150 let mnemonic = mnemonic_from_entropy(entropy);
151 // Chia convention: the BIP-39 passphrase is empty. A non-empty passphrase
152 // here would silently fork the wallet from every standard client.
153 Zeroizing::new(mnemonic.to_seed(""))
154}
155
156/// Parse a recovery phrase back into the entropy DIG stores.
157///
158/// Accepts the forms a user plausibly types: any capitalisation, leading or
159/// trailing whitespace, and any run of whitespace (including newlines, as when
160/// pasting from a numbered list) between words. Restoring an account is a
161/// high-stress moment — being rejected over a capital letter is a trap, not a
162/// safety measure, and lowercasing cannot change which English BIP-39 word a
163/// token is.
164///
165/// # Errors
166///
167/// [`SessionError::InvalidRecoveryPhrase`] if a word is not in the English
168/// wordlist, the checksum fails, or the phrase is not
169/// [`RECOVERY_PHRASE_WORDS`] words long. The message deliberately names only
170/// the *shape* of the failure — never a word of the phrase, which is secret.
171pub(crate) fn entropy_from_phrase(phrase: &str) -> Result<Zeroizing<[u8; ENTROPY_LEN]>> {
172 // bip39's "normalized" parse handles Unicode normalisation only; case and
173 // whitespace shape are ours to forgive.
174 let normalized = Zeroizing::new(
175 phrase
176 .split_whitespace()
177 .map(str::to_lowercase)
178 .collect::<Vec<_>>()
179 .join(" "),
180 );
181 let mnemonic = Mnemonic::parse_in_normalized(Language::English, &normalized)
182 .map_err(|_| SessionError::InvalidRecoveryPhrase)?;
183 let entropy = Zeroizing::new(mnemonic.to_entropy());
184 if entropy.len() != ENTROPY_LEN {
185 return Err(SessionError::InvalidRecoveryPhrase);
186 }
187 let mut out = Zeroizing::new([0u8; ENTROPY_LEN]);
188 out.copy_from_slice(&entropy);
189 Ok(out)
190}
191
192/// A live, in-memory account root whose BIP-39 entropy has been decrypted and is
193/// ready to (a) reconstruct the wallet `MasterKey` app-side, (b) derive the
194/// dig-identity signing key + profile DEK in-crate, and (c) render the 24-word
195/// recovery phrase for the user.
196///
197/// Obtained from [`crate::Session::enroll_master_seed`],
198/// [`crate::Session::enroll_from_recovery_phrase`] or
199/// [`crate::Session::unlock_master_seed`]. The entropy lives in a [`Zeroizing`]
200/// buffer wiped when this value drops. The type deliberately does not implement
201/// `Clone` and its `Debug` impl redacts the secret.
202///
203/// # Boundaries
204///
205/// An `UnlockedMasterSeed` must never cross an IPC boundary: it holds the root
206/// wallet secret and belongs solely to the user-app process that owns the
207/// identity (dig_ecosystem #908). It stays user-side; this crate crosses no
208/// engine/IPC boundary.
209pub struct UnlockedMasterSeed {
210 /// The stored BIP-39 entropy. Wiped on drop. Expanded to the HD seed on
211 /// every derivation rather than being cached, so no long-lived copy of the
212 /// expanded seed exists.
213 entropy: Zeroizing<[u8; ENTROPY_LEN]>,
214}
215
216impl UnlockedMasterSeed {
217 /// Wrap freshly decrypted BIP-39 entropy.
218 pub(crate) fn new(entropy: Zeroizing<[u8; ENTROPY_LEN]>) -> Self {
219 Self { entropy }
220 }
221
222 /// The expanded 64-byte master HD seed.
223 ///
224 /// This is the value an app-tier consumer feeds to wallet-backend's
225 /// `MasterKey::from_seed_bytes` to reconstruct the wallet master key
226 /// (`MasterKey::from_seed_bytes(handle.master_seed().to_vec())`). It is
227 /// byte-identical to what Sage and every standard Chia wallet derive from
228 /// the same 24 words, so the wallet addresses match.
229 ///
230 /// The returned buffer is `Zeroizing`, so the caller's copy is wiped on drop
231 /// — it is the caller's responsibility to keep it zeroizing all the way into
232 /// `from_seed_bytes` (whose parameter is itself moved into a `Zeroizing`
233 /// buffer).
234 ///
235 /// A primitive byte array is returned (never a wallet-backend type) to keep
236 /// dig-session free of any upward `@10 -> @20` dependency edge.
237 pub fn master_seed(&self) -> Zeroizing<[u8; MASTER_SEED_LEN]> {
238 expand_entropy(&self.entropy)
239 }
240
241 /// The [`RECOVERY_PHRASE_WORDS`]-word BIP-39 recovery phrase for this
242 /// account, space-separated and lowercase.
243 ///
244 /// Takes `&self`: showing the user their phrase must not cost them their
245 /// session, so the handle stays usable afterwards. Typing these words into
246 /// Sage — or into
247 /// [`Session::enroll_from_recovery_phrase`](crate::Session::enroll_from_recovery_phrase)
248 /// on a new machine — reproduces this exact account.
249 ///
250 /// # Never log this (the type will NOT stop you)
251 ///
252 /// The returned `String` is [`Zeroizing`], so its heap buffer is wiped on
253 /// drop — but `Zeroizing<String>` **derefs to `String`**, so
254 /// `info!("{phrase}")` compiles without complaint. And `dig-logging`'s
255 /// BIP-39 redactor runs at **bundle time**, not at write time: a logged
256 /// phrase sits in plaintext on disk until (and unless) a bundle is built.
257 /// Treat that redactor as a last-resort scrub, never as protection.
258 pub fn recovery_phrase(&self) -> Zeroizing<String> {
259 Zeroizing::new(mnemonic_from_entropy(&self.entropy).to_string())
260 }
261
262 /// The 48-byte compressed BLS12-381 G1 dig-identity public key derived from
263 /// the expanded master seed at the canonical hardened path
264 /// `m/12381'/8444'/9'/0'`.
265 ///
266 /// Byte-identical to
267 /// `dig_identity::public_key_bytes(derive_identity_sk(master_secret_key_from_seed(master_seed)))`,
268 /// so signatures produced here verify against the published DID identity.
269 pub fn public_key(&self) -> [u8; IDENTITY_PUBLIC_KEY_LEN] {
270 // Reconstruct the identity key transiently; it drops at end of scope.
271 let seed = self.master_seed();
272 let identity_sk = derive_identity_sk(&master_secret_key_from_seed(&*seed));
273 public_key_bytes(&identity_sk)
274 }
275
276 /// Sign `msg` with the dig-identity key derived from the master seed,
277 /// returning the 96-byte G2 AugScheme signature.
278 ///
279 /// The signature verifies under [`public_key`](Self::public_key).
280 pub fn sign(&self, msg: &[u8]) -> [u8; IDENTITY_SIGNATURE_LEN] {
281 let seed = self.master_seed();
282 let identity_sk = derive_identity_sk(&master_secret_key_from_seed(&*seed));
283 sign_message(&identity_sk, msg)
284 }
285
286 /// Derive a per-profile symmetric key (DEK) bound to `label`.
287 ///
288 /// The identity scalar is re-derived from the **expanded** master seed and
289 /// fed to the frozen HKDF construction shared with every other DEK path
290 /// ([`derive_symmetric_key_from_scalar`]):
291 /// `HKDF-SHA256(ikm = IDENTITY_IKM_VERSION || identity_scalar,
292 /// salt = DEK_SALT, info = label)` → [`SYMMETRIC_KEY_LEN`] bytes. The HKDF is
293 /// never duplicated, so all paths stay byte-compatible for one root.
294 ///
295 /// The returned key and all intermediates are wrapped in [`Zeroizing`].
296 pub fn derive_symmetric_key(&self, label: &[u8]) -> Zeroizing<[u8; SYMMETRIC_KEY_LEN]> {
297 // Re-derive the identity scalar from the seed, then run the shared,
298 // frozen DEK construction. The scalar is captured into a zeroizing
299 // buffer so it is wiped when this call returns.
300 let seed = self.master_seed();
301 let identity_scalar =
302 Zeroizing::new(derive_identity_sk(&master_secret_key_from_seed(&*seed)).to_bytes());
303 derive_symmetric_key_from_scalar(&*identity_scalar, label)
304 }
305
306 /// The 48-byte compressed BLS12-381 G1 dig-identity public key for the
307 /// profile at `profile_ix`, derived from the expanded master seed at
308 /// `m/12381'/8444'/9'/{profile_ix}'` via
309 /// [`dig_identity::derive_identity_sk_at`].
310 ///
311 /// # `profile_ix == 0` is byte-identical to [`public_key`](Self::public_key)
312 ///
313 /// `derive_identity_sk_at(master, 0) == derive_identity_sk(master)`
314 /// (adversarial-confirmed in dig-identity 0.5.0), so
315 /// `profile_public_key(0) == public_key()` byte-for-byte — the default path is
316 /// exactly profile 0. Each `profile_ix` yields a distinct, deterministic key.
317 pub fn profile_public_key(&self, profile_ix: u32) -> [u8; IDENTITY_PUBLIC_KEY_LEN] {
318 let seed = self.master_seed();
319 let profile_sk = derive_identity_sk_at(&master_secret_key_from_seed(&*seed), profile_ix);
320 public_key_bytes(&profile_sk)
321 }
322
323 /// Sign `msg` with the profile at `profile_ix`'s derived identity key,
324 /// returning the 96-byte G2 AugScheme signature.
325 ///
326 /// The signature verifies under
327 /// [`profile_public_key(profile_ix)`](Self::profile_public_key).
328 /// `profile_sign(0, msg) == sign(msg)` byte-for-byte.
329 pub fn profile_sign(&self, profile_ix: u32, msg: &[u8]) -> [u8; IDENTITY_SIGNATURE_LEN] {
330 let seed = self.master_seed();
331 let profile_sk = derive_identity_sk_at(&master_secret_key_from_seed(&*seed), profile_ix);
332 sign_message(&profile_sk, msg)
333 }
334
335 /// Derive the profile at `profile_ix`'s per-profile symmetric key (DEK) bound
336 /// to `label`.
337 ///
338 /// The profile's identity scalar is derived from the expanded master seed via
339 /// [`dig_identity::derive_identity_sk_at`] and fed to the SAME frozen HKDF
340 /// construction as every other DEK path
341 /// ([`derive_symmetric_key_from_scalar`]) — the HKDF is never duplicated, so
342 /// all paths stay byte-compatible for the same underlying scalar.
343 ///
344 /// # `profile_ix == 0` is byte-identical to
345 /// [`derive_symmetric_key`](Self::derive_symmetric_key)
346 ///
347 /// Because `derive_identity_sk_at(master, 0) == derive_identity_sk(master)`,
348 /// `profile_derive_symmetric_key(0, label) == derive_symmetric_key(label)`
349 /// byte-for-byte. Each `profile_ix` yields a distinct, deterministic DEK.
350 ///
351 /// The returned key and all intermediates are wrapped in [`Zeroizing`].
352 pub fn profile_derive_symmetric_key(
353 &self,
354 profile_ix: u32,
355 label: &[u8],
356 ) -> Zeroizing<[u8; SYMMETRIC_KEY_LEN]> {
357 // Re-derive the profile scalar from the seed, then run the shared, frozen
358 // DEK construction. The scalar is captured into a zeroizing buffer so it
359 // is wiped when this call returns.
360 let seed = self.master_seed();
361 let profile_scalar = Zeroizing::new(
362 derive_identity_sk_at(&master_secret_key_from_seed(&*seed), profile_ix).to_bytes(),
363 );
364 derive_symmetric_key_from_scalar(&*profile_scalar, label)
365 }
366
367 /// Produce a standalone signing primitive that signs with this identity's
368 /// key — a plain callable carrying no dig-session or identity type.
369 ///
370 /// The closure owns its own zeroizing copy of the entropy, so it keeps
371 /// working after this handle is dropped and wipes its copy when the closure
372 /// itself is dropped. This is how a downstream stays identity-agnostic while
373 /// still being able to sign (dig_ecosystem #908).
374 pub fn signing_fn(&self) -> IdentitySigningFn {
375 let entropy = self.entropy.clone();
376 Arc::new(move |msg: &[u8]| {
377 let seed = expand_entropy(&entropy);
378 let identity_sk = derive_identity_sk(&master_secret_key_from_seed(&*seed));
379 sign_message(&identity_sk, msg)
380 })
381 }
382}
383
384/// Redacting `Debug`: shows the type name only, never the secret.
385impl core::fmt::Debug for UnlockedMasterSeed {
386 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
387 f.debug_struct("UnlockedMasterSeed")
388 .field("entropy", &"<redacted>")
389 .finish()
390 }
391}