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
//! The master-SEED unlock path: an unlocked handle over a DIG account's root
//! HD seed, stored as BIP-39 entropy and re-expanded on demand.
//!
//! # Why this exists (the impedance mismatch it closes)
//!
//! The 0.2.0 identity path ([`crate::UnlockedIdentity`]) unlocks to the *derived
//! identity scalar* only — it stores `derive_identity_sk(master).to_bytes()` and
//! can never reconstruct the master seed. But `dig-wallet-backend`'s
//! `MasterKey::from_seed_bytes` (the master-HD model, dig_ecosystem #997) needs
//! the **master seed** to derive every profile's wallet keys. The identity
//! scalar cannot reconstruct the seed, so a consumer that wants BOTH the
//! dig-identity key AND a wallet `MasterKey` must persist the root itself.
//!
//! # The root is BIP-39 ENTROPY, and the seed is expanded from it
//!
//! A 24-word recovery phrase carries an implicit promise: *any* conforming
//! wallet can restore it. Standard Chia wallets (Sage, the reference client,
//! `chia-wallet-sdk`) honour that promise as
//!
//! ```text
//! phrase --BIP-39--> 32-byte entropy --PBKDF2("mnemonic", 2048)--> 64-byte seed --EIP-2333--> master SecretKey
//! ```
//!
//! Handing the **entropy** to `SecretKey::from_seed` instead of the expanded
//! 64-byte seed skips the PBKDF2 step. It does not fail — it derives a
//! different, entirely plausible wallet, so a user restoring a DIG phrase in
//! Sage would see an empty account with no error at all. dig_ecosystem #1759.
//!
//! This module therefore stores the **32-byte entropy** (which is exactly what
//! a 24-word phrase encodes, and what the phrase can be regenerated from) and
//! re-expands it to the [`MASTER_SEED_LEN`]-byte HD seed at
//! [`master_seed`](UnlockedMasterSeed::master_seed). **Every** derivation —
//! identity, per-profile DEK, wallet — reads that one expanded seed, so no two
//! of them can disagree about the root.
//!
//! [`UnlockedMasterSeed`] exposes:
//!
//! - [`master_seed`](UnlockedMasterSeed::master_seed) — the expanded 64-byte HD
//! seed, ready to feed to wallet-backend's `MasterKey::from_seed_bytes` (see
//! the layering note below);
//! - [`recovery_phrase`](UnlockedMasterSeed::recovery_phrase) — the 24 words,
//! *without* consuming the handle, so a UI can show them and carry on;
//! - [`sign`](UnlockedMasterSeed::sign) /
//! [`public_key`](UnlockedMasterSeed::public_key) — the dig-identity key at
//! the canonical hardened path;
//! - [`derive_symmetric_key`](UnlockedMasterSeed::derive_symmetric_key) — the
//! per-profile DEK, through the frozen `dig-constants` HKDF contract.
//!
//! # Layering (@10 reference-DOWN-only, HARD RULE)
//!
//! dig-session is a `10-primitives` crate; `MasterKey` is a `20-domain`
//! (`dig-wallet-backend`) type. This module therefore **must not** depend on
//! dig-wallet-backend or return a wallet-backend type — that would be an illegal
//! upward `@10 -> @20` edge. The seed is exposed as PRIMITIVE bytes only; the
//! app-tier consumer (dig-app) constructs the `MasterKey` itself via
//! `MasterKey::from_seed_bytes(handle.master_seed().to_vec())`.
//!
//! # Why the seed round-trips to the SAME master key everywhere
//!
//! Both dig-identity's `master_secret_key_from_seed(seed)` and wallet-backend's
//! `MasterKey::from_seed_bytes(seed)` reduce to `chia_bls::SecretKey::from_seed(seed)`
//! (EIP-2333 KeyGen). Handing the identical expanded seed bytes to both
//! therefore yields the identical master key — which is exactly why the seed
//! (not a derived scalar) is the value that must be reconstructible.
//!
//! # Storage
//!
//! The entropy is sealed in a versioned envelope (see [`crate::envelope`]) so a
//! stored blob DECLARES what its 32 bytes mean. A pre-envelope blob — whose 32
//! bytes were a raw master seed — fails closed with
//! [`SessionError::LegacySeedFormat`](crate::SessionError::LegacySeedFormat)
//! rather than being reinterpreted as entropy.
use Arc;
use ;
use SYMMETRIC_KEY_LEN;
use ;
use Zeroizing;
use cratederive_symmetric_key_from_scalar;
use crate::;
/// The number of bytes of BIP-39 entropy behind a DIG account — the value
/// actually stored at rest.
///
/// 32 bytes is precisely the entropy of a **24-word** English BIP-39 mnemonic
/// (256 bits + an 8-bit checksum = 264 bits = 24 × 11), so entropy and phrase
/// convert both ways losslessly and the phrase is the canonical backup.
pub const ENTROPY_LEN: usize = 32;
/// The number of bytes in an expanded BIP-39 master HD seed — the value fed to
/// `chia_bls::SecretKey::from_seed`.
///
/// Fixed at 64 by BIP-39: `PBKDF2-HMAC-SHA512(phrase, "mnemonic" || passphrase,
/// 2048)` emits 512 bits. DIG uses the **empty** passphrase, matching Chia.
pub const MASTER_SEED_LEN: usize = 64;
/// The number of words in a DIG recovery phrase.
pub const RECOVERY_PHRASE_WORDS: usize = 24;
/// The number of bytes in a compressed BLS12-381 **G1** identity public key.
pub const IDENTITY_PUBLIC_KEY_LEN: usize = 48;
/// The number of bytes in a BLS12-381 **G2** AugScheme signature.
pub const IDENTITY_SIGNATURE_LEN: usize = 96;
/// A standalone identity-signing primitive: a plain callable mapping a message to
/// a 96-byte G2 signature, carrying no dig-session or dig-identity type.
///
/// This is the bare shape [`UnlockedMasterSeed::signing_fn`] hands a downstream so
/// it can sign while staying identity-agnostic (dig_ecosystem #908). It mirrors
/// [`crate::SigningFn`] but is expressed over raw byte arrays because the
/// master-seed path derives the identity key itself rather than exposing a
/// scheme-parameterized `SignerHandle`.
pub type IdentitySigningFn = ;
/// Reconstruct the 24-word mnemonic that `entropy` encodes.
///
/// Infallible for [`ENTROPY_LEN`] bytes: BIP-39 accepts any 32-byte entropy and
/// computes the checksum itself, so there is no invalid input to report.
///
/// # Custody note
///
/// The returned `Mnemonic`'s word indices are a COMPLETE copy of the account
/// root, and one is built on every derivation. dig-session therefore enables
/// bip39's `zeroize` feature, which makes `Mnemonic` `Zeroize + ZeroizeOnDrop`,
/// so each copy is wiped when it drops. Callers still confine it to the
/// narrowest possible scope and route the byte/string buffers *we* own through
/// [`Zeroizing`].
///
/// Residual, not fixed by that feature: bip39's own intermediate `to_string()`
/// heap buffer and its transient `[u8; 33]` entropy+checksum stack array are not
/// wiped upstream. Both are short-lived and inside bip39; fixing them requires
/// an upstream change.
/// Expand BIP-39 `entropy` into the 64-byte master HD seed, the Chia way:
/// `entropy -> 24 words -> PBKDF2 with an EMPTY passphrase`.
///
/// This is the one function that closes the Sage-parity gap; every derivation in
/// this module goes through it so none can drift.
pub
/// Parse a recovery phrase back into the entropy DIG stores.
///
/// Accepts the forms a user plausibly types: any capitalisation, leading or
/// trailing whitespace, and any run of whitespace (including newlines, as when
/// pasting from a numbered list) between words. Restoring an account is a
/// high-stress moment — being rejected over a capital letter is a trap, not a
/// safety measure, and lowercasing cannot change which English BIP-39 word a
/// token is.
///
/// # Errors
///
/// [`SessionError::InvalidRecoveryPhrase`] if a word is not in the English
/// wordlist, the checksum fails, or the phrase is not
/// [`RECOVERY_PHRASE_WORDS`] words long. The message deliberately names only
/// the *shape* of the failure — never a word of the phrase, which is secret.
pub
/// A live, in-memory account root whose BIP-39 entropy has been decrypted and is
/// ready to (a) reconstruct the wallet `MasterKey` app-side, (b) derive the
/// dig-identity signing key + profile DEK in-crate, and (c) render the 24-word
/// recovery phrase for the user.
///
/// Obtained from [`crate::Session::enroll_master_seed`],
/// [`crate::Session::enroll_from_recovery_phrase`] or
/// [`crate::Session::unlock_master_seed`]. The entropy lives in a [`Zeroizing`]
/// buffer wiped when this value drops. The type deliberately does not implement
/// `Clone` and its `Debug` impl redacts the secret.
///
/// # Boundaries
///
/// An `UnlockedMasterSeed` must never cross an IPC boundary: it holds the root
/// wallet secret and belongs solely to the user-app process that owns the
/// identity (dig_ecosystem #908). It stays user-side; this crate crosses no
/// engine/IPC boundary.
/// Redacting `Debug`: shows the type name only, never the secret.