Skip to main content

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, derive_identity_sk_at, master_secret_key_from_seed, public_key_bytes,
59    sign_message,
60};
61use dig_keystore::{BlsSigning, SignerHandle};
62use zeroize::Zeroizing;
63
64use crate::unlocked::derive_symmetric_key_from_scalar;
65
66/// The number of bytes in a DIG master HD seed.
67///
68/// Fixed at 32 to match dig-app's master-seed model (`SCALAR_LEN`, a 32-byte
69/// entropy seed drawn from the CSPRNG) and the `BlsSigning` storage scheme's
70/// `SECRET_LEN`. The seed is fed to `chia_bls::SecretKey::from_seed`, which
71/// accepts any length ≥ 32; 32 bytes is the DIG canonical size.
72pub const SEED_LEN: usize = 32;
73
74/// The number of bytes in a compressed BLS12-381 **G1** identity public key.
75pub const IDENTITY_PUBLIC_KEY_LEN: usize = 48;
76
77/// The number of bytes in a BLS12-381 **G2** AugScheme signature.
78pub const IDENTITY_SIGNATURE_LEN: usize = 96;
79
80/// A standalone identity-signing primitive: a plain callable mapping a message to
81/// a 96-byte G2 signature, carrying no dig-session or dig-identity type.
82///
83/// This is the bare shape [`UnlockedMasterSeed::signing_fn`] hands a downstream so
84/// it can sign while staying identity-agnostic (dig_ecosystem #908). It mirrors
85/// [`crate::SigningFn`] but is expressed over raw byte arrays because the
86/// master-seed path derives the identity key itself rather than exposing a
87/// scheme-parameterized `SignerHandle`.
88pub type IdentitySigningFn = Arc<dyn Fn(&[u8]) -> [u8; IDENTITY_SIGNATURE_LEN] + Send + Sync>;
89
90/// A live, in-memory master HD seed whose bytes have been decrypted and are
91/// ready to (a) reconstruct the wallet `MasterKey` app-side and (b) derive the
92/// dig-identity signing key + profile DEK in-crate.
93///
94/// Obtained from [`crate::Session::enroll_master_seed`] or
95/// [`crate::Session::unlock_master_seed`]. The seed lives inside the wrapped
96/// [`SignerHandle`], which stores it in a `Zeroizing` buffer and wipes it when
97/// this value is dropped. The type deliberately does not implement `Clone` and
98/// its `Debug` impl redacts the secret.
99///
100/// # Boundaries
101///
102/// An `UnlockedMasterSeed` must never cross an IPC boundary: it holds the root
103/// wallet seed and belongs solely to the user-app process that owns the identity
104/// (dig_ecosystem #908). The seed stays user-side; this crate crosses no
105/// engine/IPC boundary.
106pub struct UnlockedMasterSeed {
107    /// The `BlsSigning` handle is used ONLY as a zeroizing 32-byte vault for the
108    /// raw seed (`expose_secret()` returns it verbatim). Its own signing key is
109    /// never used — the identity key is derived from the seed in this crate.
110    seed_handle: SignerHandle<BlsSigning>,
111}
112
113impl UnlockedMasterSeed {
114    /// Wrap a freshly unlocked seed-storage [`SignerHandle`].
115    pub(crate) fn new(seed_handle: SignerHandle<BlsSigning>) -> Self {
116        Self { seed_handle }
117    }
118
119    /// The raw master HD seed bytes, as a primitive `Zeroizing<[u8; SEED_LEN]>`.
120    ///
121    /// This is the value an app-tier consumer feeds to wallet-backend's
122    /// `MasterKey::from_seed_bytes` to reconstruct the wallet master key
123    /// (`MasterKey::from_seed_bytes(handle.master_seed())`). The returned buffer
124    /// is `Zeroizing`, so the caller's copy is wiped on drop — it is the caller's
125    /// responsibility to keep it zeroizing all the way into `from_seed_bytes`
126    /// (whose parameter is itself moved into a `Zeroizing` buffer).
127    ///
128    /// A primitive byte array is returned (never a wallet-backend type) to keep
129    /// dig-session free of any upward `@10 -> @20` dependency edge.
130    pub fn master_seed(&self) -> Zeroizing<[u8; SEED_LEN]> {
131        let raw = self.seed_handle.expose_secret();
132        let mut seed = Zeroizing::new([0u8; SEED_LEN]);
133        // The storage scheme guarantees exactly SEED_LEN bytes (`BlsSigning`'s
134        // SECRET_LEN); the enroll path only ever writes SEED_LEN bytes.
135        seed.copy_from_slice(raw);
136        seed
137    }
138
139    /// The 48-byte compressed BLS12-381 G1 dig-identity public key derived from
140    /// the seed.
141    ///
142    /// Byte-identical to
143    /// `dig_identity::public_key_bytes(derive_identity_sk(master_secret_key_from_seed(seed)))`
144    /// and to the 0.2.0 identity path's public key for the same seed — so
145    /// signatures produced here verify against the published DID identity.
146    pub fn public_key(&self) -> [u8; IDENTITY_PUBLIC_KEY_LEN] {
147        // Reconstruct the identity key transiently; it drops at end of scope.
148        let seed = self.master_seed();
149        let identity_sk = derive_identity_sk(&master_secret_key_from_seed(&*seed));
150        public_key_bytes(&identity_sk)
151    }
152
153    /// Sign `msg` with the dig-identity key derived from the seed, returning the
154    /// 96-byte G2 AugScheme signature.
155    ///
156    /// The signature verifies under [`public_key`](Self::public_key).
157    pub fn sign(&self, msg: &[u8]) -> [u8; IDENTITY_SIGNATURE_LEN] {
158        let seed = self.master_seed();
159        let identity_sk = derive_identity_sk(&master_secret_key_from_seed(&*seed));
160        sign_message(&identity_sk, msg)
161    }
162
163    /// Derive a per-profile symmetric key (DEK) bound to `label`.
164    ///
165    /// **Byte-identical to [`crate::UnlockedIdentity::derive_symmetric_key`]**
166    /// for the same underlying identity: the identity scalar is re-derived from
167    /// the seed and fed to the SAME frozen HKDF construction
168    /// (`HKDF-SHA256(ikm = IDENTITY_IKM_VERSION || identity_scalar,
169    /// salt = DEK_SALT, info = label)` → [`SYMMETRIC_KEY_LEN`] bytes). So a
170    /// profile blob sealed via the 0.2.0 identity path opens unchanged after a
171    /// consumer migrates to the master-seed path (§5.1 at-rest back-compat).
172    ///
173    /// The returned key and all intermediates are wrapped in [`Zeroizing`].
174    pub fn derive_symmetric_key(&self, label: &[u8]) -> Zeroizing<[u8; SYMMETRIC_KEY_LEN]> {
175        // Re-derive the identity scalar from the seed, then run the shared,
176        // frozen DEK construction. The scalar is captured into a zeroizing
177        // buffer so it is wiped when this call returns.
178        let seed = self.master_seed();
179        let identity_scalar =
180            Zeroizing::new(derive_identity_sk(&master_secret_key_from_seed(&*seed)).to_bytes());
181        derive_symmetric_key_from_scalar(&*identity_scalar, label)
182    }
183
184    /// The 48-byte compressed BLS12-381 G1 dig-identity public key for the
185    /// profile at `profile_ix`, derived from the seed at
186    /// `m/12381'/8444'/9'/{profile_ix}'` via
187    /// [`dig_identity::derive_identity_sk_at`].
188    ///
189    /// # `profile_ix == 0` is byte-identical to [`public_key`](Self::public_key)
190    ///
191    /// `derive_identity_sk_at(master, 0) == derive_identity_sk(master)`
192    /// (adversarial-confirmed in dig-identity 0.5.0), so
193    /// `profile_public_key(0) == public_key()` byte-for-byte — the default path is
194    /// exactly profile 0, and this method is a pure ADDITIVE generalization
195    /// (§5.1). Each `profile_ix` yields a distinct, deterministic identity key.
196    pub fn profile_public_key(&self, profile_ix: u32) -> [u8; IDENTITY_PUBLIC_KEY_LEN] {
197        let seed = self.master_seed();
198        let profile_sk = derive_identity_sk_at(&master_secret_key_from_seed(&*seed), profile_ix);
199        public_key_bytes(&profile_sk)
200    }
201
202    /// Sign `msg` with the profile at `profile_ix`'s derived identity key,
203    /// returning the 96-byte G2 AugScheme signature.
204    ///
205    /// The signature verifies under
206    /// [`profile_public_key(profile_ix)`](Self::profile_public_key).
207    /// `profile_sign(0, msg) == sign(msg)` byte-for-byte (§5.1 additive).
208    pub fn profile_sign(&self, profile_ix: u32, msg: &[u8]) -> [u8; IDENTITY_SIGNATURE_LEN] {
209        let seed = self.master_seed();
210        let profile_sk = derive_identity_sk_at(&master_secret_key_from_seed(&*seed), profile_ix);
211        sign_message(&profile_sk, msg)
212    }
213
214    /// Derive the profile at `profile_ix`'s per-profile symmetric key (DEK) bound
215    /// to `label`.
216    ///
217    /// The profile's identity scalar is derived from the seed via
218    /// [`dig_identity::derive_identity_sk_at`] and fed to the SAME frozen HKDF
219    /// construction as every other DEK path
220    /// ([`derive_symmetric_key_from_scalar`]) — the HKDF is never duplicated, so
221    /// all paths stay byte-compatible for the same underlying scalar.
222    ///
223    /// # `profile_ix == 0` is byte-identical to
224    /// [`derive_symmetric_key`](Self::derive_symmetric_key)
225    ///
226    /// Because `derive_identity_sk_at(master, 0) == derive_identity_sk(master)`,
227    /// `profile_derive_symmetric_key(0, label) == derive_symmetric_key(label)`
228    /// byte-for-byte — so a profile blob sealed via the default path opens
229    /// unchanged (§5.1 at-rest back-compat). Each `profile_ix` yields a distinct,
230    /// deterministic DEK.
231    ///
232    /// The returned key and all intermediates are wrapped in [`Zeroizing`].
233    pub fn profile_derive_symmetric_key(
234        &self,
235        profile_ix: u32,
236        label: &[u8],
237    ) -> Zeroizing<[u8; SYMMETRIC_KEY_LEN]> {
238        // Re-derive the profile scalar from the seed, then run the shared, frozen
239        // DEK construction. The scalar is captured into a zeroizing buffer so it
240        // is wiped when this call returns.
241        let seed = self.master_seed();
242        let profile_scalar = Zeroizing::new(
243            derive_identity_sk_at(&master_secret_key_from_seed(&*seed), profile_ix).to_bytes(),
244        );
245        derive_symmetric_key_from_scalar(&*profile_scalar, label)
246    }
247
248    /// Produce a standalone signing primitive that signs with this identity's
249    /// key — a plain callable carrying no dig-session or identity type.
250    ///
251    /// The closure owns its own zeroizing copy of the seed, so it keeps working
252    /// after this handle is dropped and wipes its copy when the closure itself
253    /// is dropped. This is how a downstream stays identity-agnostic while still
254    /// being able to sign (dig_ecosystem #908).
255    pub fn signing_fn(&self) -> IdentitySigningFn {
256        let seed = self.master_seed();
257        Arc::new(move |msg: &[u8]| {
258            let identity_sk = derive_identity_sk(&master_secret_key_from_seed(&*seed));
259            sign_message(&identity_sk, msg)
260        })
261    }
262}
263
264/// Redacting `Debug`: shows the type name only, never the seed.
265impl core::fmt::Debug for UnlockedMasterSeed {
266    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
267        f.debug_struct("UnlockedMasterSeed")
268            .field("seed", &"<redacted>")
269            .finish()
270    }
271}