dig_session/master_seed.rs
1//! The master-SEED unlock path: an unlocked handle over the raw master HD seed.
2//!
3//! # Why this exists (the impedance mismatch it closes)
4//!
5//! The 0.2.0 identity path ([`crate::UnlockedIdentity`]) unlocks to the *derived
6//! identity scalar* only — it stores `derive_identity_sk(master).to_bytes()` and
7//! can never reconstruct the master seed. But `dig-wallet-backend`'s
8//! `MasterKey::from_seed_bytes` (the master-HD model, dig_ecosystem #997) needs
9//! the **master seed** to derive every profile's wallet keys. The identity
10//! scalar cannot reconstruct the seed, so a consumer that wants BOTH the
11//! dig-identity key AND a wallet `MasterKey` must persist the seed itself.
12//!
13//! [`UnlockedMasterSeed`] is that path: it persists the raw 32-byte master seed
14//! (encrypted at rest) and, on unlock, exposes ALL of:
15//!
16//! - [`master_seed`](UnlockedMasterSeed::master_seed) — the raw seed bytes as a
17//! primitive `Zeroizing<[u8; SEED_LEN]>`, ready to feed to wallet-backend's
18//! `MasterKey::from_seed_bytes` (see the layering note below);
19//! - [`sign`](UnlockedMasterSeed::sign) /
20//! [`public_key`](UnlockedMasterSeed::public_key) — the dig-identity key
21//! derived from the seed at the canonical path, byte-identical to the 0.2.0
22//! identity path for the same seed;
23//! - [`derive_symmetric_key`](UnlockedMasterSeed::derive_symmetric_key) — the
24//! per-profile DEK, **byte-identical** to
25//! [`crate::UnlockedIdentity::derive_symmetric_key`] (§5.1 at-rest back-compat).
26//!
27//! # Layering (@10 reference-DOWN-only, HARD RULE)
28//!
29//! dig-session is a `10-primitives` crate; `MasterKey` is a `20-domain`
30//! (`dig-wallet-backend`) type. This module therefore **must not** depend on
31//! dig-wallet-backend or return a wallet-backend type — that would be an illegal
32//! upward `@10 -> @20` edge. The seed is exposed as PRIMITIVE bytes only; the
33//! app-tier consumer (dig-app) constructs the `MasterKey` itself via
34//! `MasterKey::from_seed_bytes(handle.master_seed())`.
35//!
36//! # Why the seed round-trips to the SAME master key everywhere
37//!
38//! Both dig-identity's `master_secret_key_from_seed(seed)` and wallet-backend's
39//! `MasterKey::from_seed_bytes(seed)` reduce to `chia_bls::SecretKey::from_seed(seed)`
40//! (EIP-2333 KeyGen). Handing the identical seed bytes to both therefore yields
41//! the identical master key — which is exactly why the seed (not the derived
42//! scalar) is the value that must be persisted and exposed.
43//!
44//! # Storage scheme
45//!
46//! The seed is stored under [`dig_keystore::BlsSigning`] purely as a 32-byte
47//! encrypted-at-rest byte vault: that scheme persists exactly its 32 secret
48//! bytes verbatim and returns them via `expose_secret()`. This path never uses
49//! the `BlsSigning` handle's own `sign`/`public_key` (which would derive the
50//! *master* key via `from_seed`); the dig-identity key is derived in this crate
51//! instead. The `L1WalletBls` scheme is unsuitable here because it stores an
52//! already-derived *scalar* (`from_bytes`), not a *seed*.
53
54use std::sync::Arc;
55
56use dig_constants::SYMMETRIC_KEY_LEN;
57use dig_identity::{
58 derive_identity_sk, master_secret_key_from_seed, public_key_bytes, sign_message,
59};
60use dig_keystore::{BlsSigning, SignerHandle};
61use zeroize::Zeroizing;
62
63use crate::unlocked::derive_symmetric_key_from_scalar;
64
65/// The number of bytes in a DIG master HD seed.
66///
67/// Fixed at 32 to match dig-app's master-seed model (`SCALAR_LEN`, a 32-byte
68/// entropy seed drawn from the CSPRNG) and the `BlsSigning` storage scheme's
69/// `SECRET_LEN`. The seed is fed to `chia_bls::SecretKey::from_seed`, which
70/// accepts any length ≥ 32; 32 bytes is the DIG canonical size.
71pub const SEED_LEN: usize = 32;
72
73/// The number of bytes in a compressed BLS12-381 **G1** identity public key.
74pub const IDENTITY_PUBLIC_KEY_LEN: usize = 48;
75
76/// The number of bytes in a BLS12-381 **G2** AugScheme signature.
77pub const IDENTITY_SIGNATURE_LEN: usize = 96;
78
79/// A standalone identity-signing primitive: a plain callable mapping a message to
80/// a 96-byte G2 signature, carrying no dig-session or dig-identity type.
81///
82/// This is the bare shape [`UnlockedMasterSeed::signing_fn`] hands a downstream so
83/// it can sign while staying identity-agnostic (dig_ecosystem #908). It mirrors
84/// [`crate::SigningFn`] but is expressed over raw byte arrays because the
85/// master-seed path derives the identity key itself rather than exposing a
86/// scheme-parameterized `SignerHandle`.
87pub type IdentitySigningFn = Arc<dyn Fn(&[u8]) -> [u8; IDENTITY_SIGNATURE_LEN] + Send + Sync>;
88
89/// A live, in-memory master HD seed whose bytes have been decrypted and are
90/// ready to (a) reconstruct the wallet `MasterKey` app-side and (b) derive the
91/// dig-identity signing key + profile DEK in-crate.
92///
93/// Obtained from [`crate::Session::enroll_master_seed`] or
94/// [`crate::Session::unlock_master_seed`]. The seed lives inside the wrapped
95/// [`SignerHandle`], which stores it in a `Zeroizing` buffer and wipes it when
96/// this value is dropped. The type deliberately does not implement `Clone` and
97/// its `Debug` impl redacts the secret.
98///
99/// # Boundaries
100///
101/// An `UnlockedMasterSeed` must never cross an IPC boundary: it holds the root
102/// wallet seed and belongs solely to the user-app process that owns the identity
103/// (dig_ecosystem #908). The seed stays user-side; this crate crosses no
104/// engine/IPC boundary.
105pub struct UnlockedMasterSeed {
106 /// The `BlsSigning` handle is used ONLY as a zeroizing 32-byte vault for the
107 /// raw seed (`expose_secret()` returns it verbatim). Its own signing key is
108 /// never used — the identity key is derived from the seed in this crate.
109 seed_handle: SignerHandle<BlsSigning>,
110}
111
112impl UnlockedMasterSeed {
113 /// Wrap a freshly unlocked seed-storage [`SignerHandle`].
114 pub(crate) fn new(seed_handle: SignerHandle<BlsSigning>) -> Self {
115 Self { seed_handle }
116 }
117
118 /// The raw master HD seed bytes, as a primitive `Zeroizing<[u8; SEED_LEN]>`.
119 ///
120 /// This is the value an app-tier consumer feeds to wallet-backend's
121 /// `MasterKey::from_seed_bytes` to reconstruct the wallet master key
122 /// (`MasterKey::from_seed_bytes(handle.master_seed())`). The returned buffer
123 /// is `Zeroizing`, so the caller's copy is wiped on drop — it is the caller's
124 /// responsibility to keep it zeroizing all the way into `from_seed_bytes`
125 /// (whose parameter is itself moved into a `Zeroizing` buffer).
126 ///
127 /// A primitive byte array is returned (never a wallet-backend type) to keep
128 /// dig-session free of any upward `@10 -> @20` dependency edge.
129 pub fn master_seed(&self) -> Zeroizing<[u8; SEED_LEN]> {
130 let raw = self.seed_handle.expose_secret();
131 let mut seed = Zeroizing::new([0u8; SEED_LEN]);
132 // The storage scheme guarantees exactly SEED_LEN bytes (`BlsSigning`'s
133 // SECRET_LEN); the enroll path only ever writes SEED_LEN bytes.
134 seed.copy_from_slice(raw);
135 seed
136 }
137
138 /// The 48-byte compressed BLS12-381 G1 dig-identity public key derived from
139 /// the seed.
140 ///
141 /// Byte-identical to
142 /// `dig_identity::public_key_bytes(derive_identity_sk(master_secret_key_from_seed(seed)))`
143 /// and to the 0.2.0 identity path's public key for the same seed — so
144 /// signatures produced here verify against the published DID identity.
145 pub fn public_key(&self) -> [u8; IDENTITY_PUBLIC_KEY_LEN] {
146 // Reconstruct the identity key transiently; it drops at end of scope.
147 let seed = self.master_seed();
148 let identity_sk = derive_identity_sk(&master_secret_key_from_seed(&*seed));
149 public_key_bytes(&identity_sk)
150 }
151
152 /// Sign `msg` with the dig-identity key derived from the seed, returning the
153 /// 96-byte G2 AugScheme signature.
154 ///
155 /// The signature verifies under [`public_key`](Self::public_key).
156 pub fn sign(&self, msg: &[u8]) -> [u8; IDENTITY_SIGNATURE_LEN] {
157 let seed = self.master_seed();
158 let identity_sk = derive_identity_sk(&master_secret_key_from_seed(&*seed));
159 sign_message(&identity_sk, msg)
160 }
161
162 /// Derive a per-profile symmetric key (DEK) bound to `label`.
163 ///
164 /// **Byte-identical to [`crate::UnlockedIdentity::derive_symmetric_key`]**
165 /// for the same underlying identity: the identity scalar is re-derived from
166 /// the seed and fed to the SAME frozen HKDF construction
167 /// (`HKDF-SHA256(ikm = IDENTITY_IKM_VERSION || identity_scalar,
168 /// salt = DEK_SALT, info = label)` → [`SYMMETRIC_KEY_LEN`] bytes). So a
169 /// profile blob sealed via the 0.2.0 identity path opens unchanged after a
170 /// consumer migrates to the master-seed path (§5.1 at-rest back-compat).
171 ///
172 /// The returned key and all intermediates are wrapped in [`Zeroizing`].
173 pub fn derive_symmetric_key(&self, label: &[u8]) -> Zeroizing<[u8; SYMMETRIC_KEY_LEN]> {
174 // Re-derive the identity scalar from the seed, then run the shared,
175 // frozen DEK construction. The scalar is captured into a zeroizing
176 // buffer so it is wiped when this call returns.
177 let seed = self.master_seed();
178 let identity_scalar =
179 Zeroizing::new(derive_identity_sk(&master_secret_key_from_seed(&*seed)).to_bytes());
180 derive_symmetric_key_from_scalar(&*identity_scalar, label)
181 }
182
183 /// Produce a standalone signing primitive that signs with this identity's
184 /// key — a plain callable carrying no dig-session or identity type.
185 ///
186 /// The closure owns its own zeroizing copy of the seed, so it keeps working
187 /// after this handle is dropped and wipes its copy when the closure itself
188 /// is dropped. This is how a downstream stays identity-agnostic while still
189 /// being able to sign (dig_ecosystem #908).
190 pub fn signing_fn(&self) -> IdentitySigningFn {
191 let seed = self.master_seed();
192 Arc::new(move |msg: &[u8]| {
193 let identity_sk = derive_identity_sk(&master_secret_key_from_seed(&*seed));
194 sign_message(&identity_sk, msg)
195 })
196 }
197}
198
199/// Redacting `Debug`: shows the type name only, never the seed.
200impl core::fmt::Debug for UnlockedMasterSeed {
201 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
202 f.debug_struct("UnlockedMasterSeed")
203 .field("seed", &"<redacted>")
204 .finish()
205 }
206}