dig_session/session.rs
1//! The [`Session`] facade: unlock an existing key, or enroll a new identity.
2
3use std::sync::Arc;
4
5use dig_identity::{derive_identity_sk, master_secret_key_from_seed};
6use dig_keystore::scheme::KeyScheme;
7use dig_keystore::{BackendKey, KdfParams, KeychainBackend, Keystore, L1WalletBls, Password};
8use zeroize::Zeroizing;
9
10use crate::envelope;
11use crate::master_seed::{entropy_from_phrase, ENTROPY_LEN};
12use crate::{Result, SessionError, UnlockedIdentity, UnlockedMasterSeed};
13
14/// Entry point for turning stored, encrypted key material into a live signer.
15///
16/// `Session` is a stateless namespace over the compose-only flow
17/// `dig_keystore::Keystore::<K>::load -> unlock -> SignerHandle<K>`, plus the
18/// enrollment path that derives the canonical dig-identity signing key and
19/// persists it. It holds no state of its own; every method is associated.
20pub struct Session;
21
22impl Session {
23 /// Unlock an existing keystore file into an [`UnlockedIdentity`].
24 ///
25 /// Generic over the storage scheme `K`: use [`dig_keystore::L1WalletBls`]
26 /// for a stored, already-derived key (the identity signing key, wallet
27 /// keys) and [`dig_keystore::BlsSigning`] for a seed-derived validator key.
28 /// The scheme is verified against the file's magic on load, so unlocking a
29 /// file with the wrong scheme fails cleanly rather than yielding a bogus key.
30 ///
31 /// # Errors
32 ///
33 /// Returns [`SessionError::Keystore`] if the file is missing, the password
34 /// is wrong, the ciphertext is tampered, or the scheme does not match.
35 pub fn unlock<K: KeyScheme>(
36 backend: Arc<dyn KeychainBackend>,
37 path: BackendKey,
38 password: Password,
39 ) -> Result<UnlockedIdentity<K>> {
40 let keystore = Keystore::<K>::load(backend, path)?;
41 let signer = keystore.unlock(password)?;
42 Ok(UnlockedIdentity::new(signer))
43 }
44
45 /// Enroll a new identity: derive the canonical dig-identity BLS signing key
46 /// from `seed`, persist it encrypted under `password`, and return it
47 /// unlocked and ready to sign.
48 ///
49 /// The identity key is derived exactly once, via
50 /// [`dig_identity::master_secret_key_from_seed`] followed by
51 /// [`dig_identity::derive_identity_sk`] (the hardened path
52 /// `m/12381'/8444'/9'/0'`), and the resulting secret key's canonical bytes
53 /// are stored. See the module-level note in [`crate`] on why the storage
54 /// scheme is [`L1WalletBls`] (faithful `from_bytes` round-trip) rather than
55 /// `BlsSigning` (which would re-derive via `from_seed` and produce a
56 /// different key).
57 ///
58 /// # Errors
59 ///
60 /// Returns [`SessionError::EmptySeed`] if `seed` is empty, or
61 /// [`SessionError::Keystore`] if a file already exists at `path` or the
62 /// write fails.
63 pub fn enroll_identity(
64 backend: Arc<dyn KeychainBackend>,
65 path: BackendKey,
66 password: Password,
67 seed: &[u8],
68 ) -> Result<UnlockedIdentity<L1WalletBls>> {
69 if seed.is_empty() {
70 return Err(SessionError::EmptySeed);
71 }
72
73 // Derive the canonical identity signing key ONCE, extract its canonical
74 // bytes, and drop the transient key material as early as possible.
75 //
76 // Custody note: `master` and `identity_sk` are `chia_bls::SecretKey`,
77 // which — even in the latest chia-bls (0.46) — is a plain
78 // `#[derive(Clone)]` wrapper over `blst_scalar` with NO `Zeroize`/`Drop`
79 // impl. We therefore cannot wipe those foreign scalars in place; the
80 // best we can do is (a) confine them to the smallest possible scope so
81 // the compiler drops them the instant we no longer need them, and (b)
82 // route every byte buffer WE own through `Zeroizing` so it is wiped on
83 // drop. The 32-byte `to_bytes()` array is a stack temporary, so it is
84 // wrapped in `Zeroizing` before being copied into the returned `Vec`.
85 // A cross-repo follow-up requests `Zeroize` on `chia_bls::SecretKey`
86 // (or a zeroizing derivation in dig-identity); see #1327.
87 let secret: Zeroizing<Vec<u8>> = {
88 let master = master_secret_key_from_seed(seed);
89 let identity_sk = derive_identity_sk(&master);
90 let canonical_bytes = Zeroizing::new(identity_sk.to_bytes());
91 Zeroizing::new(canonical_bytes.to_vec())
92 // `master` and `identity_sk` drop here — as early as possible.
93 };
94
95 // Persist the already-derived key. `unlock` needs the password again,
96 // and `create` consumes it, so clone before the move.
97 let unlock_password = Password::new(password.as_bytes());
98 let keystore = Keystore::<L1WalletBls>::create(
99 backend,
100 path,
101 password,
102 Some(secret),
103 KdfParams::DEFAULT,
104 )?;
105 let signer = keystore.unlock(unlock_password)?;
106 Ok(UnlockedIdentity::new(signer))
107 }
108
109 /// Enroll a new account root from `entropy`: seal the 32 bytes of BIP-39
110 /// entropy under `password` in a versioned envelope and return an
111 /// [`UnlockedMasterSeed`].
112 ///
113 /// Unlike [`enroll_identity`](Self::enroll_identity) — which stores the
114 /// *derived identity scalar* and can never recover the root — this path
115 /// stores the **root itself**, so a consumer can reconstruct the wallet
116 /// `MasterKey` (the master-HD model, dig_ecosystem #997), derive the
117 /// dig-identity key, and render the 24-word recovery phrase, all from one
118 /// value.
119 ///
120 /// `entropy` is BIP-39 entropy, **not** an HD seed: it is expanded to the
121 /// 64-byte seed via `to_seed("")` at every derivation, which is what makes
122 /// the resulting phrase restore identically in Sage and every standard Chia
123 /// wallet (dig_ecosystem #1759). Any [`ENTROPY_LEN`] CSPRNG bytes are valid
124 /// entropy, so a caller may pass fresh randomness directly.
125 ///
126 /// # Errors
127 ///
128 /// Returns [`SessionError::Keystore`] if a blob already exists at `path`
129 /// (never silently overwritten) or the write fails.
130 pub fn enroll_master_seed(
131 backend: Arc<dyn KeychainBackend>,
132 path: BackendKey,
133 password: Password,
134 entropy: &[u8; ENTROPY_LEN],
135 ) -> Result<UnlockedMasterSeed> {
136 envelope::write_bip39_entropy(&*backend, &path, &password, entropy)?;
137 let mut stored = Zeroizing::new([0u8; ENTROPY_LEN]);
138 stored.copy_from_slice(entropy);
139 Ok(UnlockedMasterSeed::new(stored))
140 }
141
142 /// Enroll an account root from an existing 24-word recovery `phrase` — the
143 /// restore-on-a-new-machine path.
144 ///
145 /// The phrase may be any capitalisation with any whitespace between words
146 /// (BIP-39 normalised). Restoring the phrase that
147 /// [`UnlockedMasterSeed::recovery_phrase`] produced — or one exported from
148 /// Sage — reproduces the identical account: same wallet addresses, same
149 /// identity key, same per-profile DEKs.
150 ///
151 /// # Errors
152 ///
153 /// - [`SessionError::InvalidRecoveryPhrase`] if the phrase is not a valid
154 /// 24-word English BIP-39 mnemonic.
155 /// - [`SessionError::Keystore`] if a blob already exists at `path` or the
156 /// write fails.
157 pub fn enroll_from_recovery_phrase(
158 backend: Arc<dyn KeychainBackend>,
159 path: BackendKey,
160 password: Password,
161 phrase: &str,
162 ) -> Result<UnlockedMasterSeed> {
163 let entropy = entropy_from_phrase(phrase)?;
164 Self::enroll_master_seed(backend, path, password, &entropy)
165 }
166
167 /// Unlock an existing account root into an [`UnlockedMasterSeed`].
168 ///
169 /// # Errors
170 ///
171 /// - [`SessionError::LegacySeedFormat`] if the blob predates the versioned
172 /// envelope. Its 32 bytes are a raw seed, and are **never** reinterpreted
173 /// as BIP-39 entropy — that would silently derive a different wallet. The
174 /// account must be re-enrolled via
175 /// [`enroll_from_recovery_phrase`](Self::enroll_from_recovery_phrase).
176 /// - [`SessionError::UnsupportedEnvelopeVersion`] /
177 /// [`SessionError::UnsupportedSeedKind`] for a blob from a newer build.
178 /// - [`SessionError::Keystore`] if the blob is missing, the password is
179 /// wrong, or the ciphertext is tampered.
180 pub fn unlock_master_seed(
181 backend: Arc<dyn KeychainBackend>,
182 path: BackendKey,
183 password: Password,
184 ) -> Result<UnlockedMasterSeed> {
185 let entropy = envelope::read_bip39_entropy(&*backend, &path, &password)?;
186 Ok(UnlockedMasterSeed::new(entropy))
187 }
188}