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::{Result, SessionError, UnlockedIdentity};
11
12/// Entry point for turning stored, encrypted key material into a live signer.
13///
14/// `Session` is a stateless namespace over the compose-only flow
15/// `dig_keystore::Keystore::<K>::load -> unlock -> SignerHandle<K>`, plus the
16/// enrollment path that derives the canonical dig-identity signing key and
17/// persists it. It holds no state of its own; every method is associated.
18pub struct Session;
19
20impl Session {
21 /// Unlock an existing keystore file into an [`UnlockedIdentity`].
22 ///
23 /// Generic over the storage scheme `K`: use [`dig_keystore::L1WalletBls`]
24 /// for a stored, already-derived key (the identity signing key, wallet
25 /// keys) and [`dig_keystore::BlsSigning`] for a seed-derived validator key.
26 /// The scheme is verified against the file's magic on load, so unlocking a
27 /// file with the wrong scheme fails cleanly rather than yielding a bogus key.
28 ///
29 /// # Errors
30 ///
31 /// Returns [`SessionError::Keystore`] if the file is missing, the password
32 /// is wrong, the ciphertext is tampered, or the scheme does not match.
33 pub fn unlock<K: KeyScheme>(
34 backend: Arc<dyn KeychainBackend>,
35 path: BackendKey,
36 password: Password,
37 ) -> Result<UnlockedIdentity<K>> {
38 let keystore = Keystore::<K>::load(backend, path)?;
39 let signer = keystore.unlock(password)?;
40 Ok(UnlockedIdentity::new(signer))
41 }
42
43 /// Enroll a new identity: derive the canonical dig-identity BLS signing key
44 /// from `seed`, persist it encrypted under `password`, and return it
45 /// unlocked and ready to sign.
46 ///
47 /// The identity key is derived exactly once, via
48 /// [`dig_identity::master_secret_key_from_seed`] followed by
49 /// [`dig_identity::derive_identity_sk`] (the hardened path
50 /// `m/12381'/8444'/9'/0'`), and the resulting secret key's canonical bytes
51 /// are stored. See the module-level note in [`crate`] on why the storage
52 /// scheme is [`L1WalletBls`] (faithful `from_bytes` round-trip) rather than
53 /// `BlsSigning` (which would re-derive via `from_seed` and produce a
54 /// different key).
55 ///
56 /// # Errors
57 ///
58 /// Returns [`SessionError::EmptySeed`] if `seed` is empty, or
59 /// [`SessionError::Keystore`] if a file already exists at `path` or the
60 /// write fails.
61 pub fn enroll_identity(
62 backend: Arc<dyn KeychainBackend>,
63 path: BackendKey,
64 password: Password,
65 seed: &[u8],
66 ) -> Result<UnlockedIdentity<L1WalletBls>> {
67 if seed.is_empty() {
68 return Err(SessionError::EmptySeed);
69 }
70
71 // Derive the canonical identity signing key ONCE, extract its canonical
72 // bytes, and drop the transient key material as early as possible.
73 //
74 // Custody note: `master` and `identity_sk` are `chia_bls::SecretKey`,
75 // which — even in the latest chia-bls (0.46) — is a plain
76 // `#[derive(Clone)]` wrapper over `blst_scalar` with NO `Zeroize`/`Drop`
77 // impl. We therefore cannot wipe those foreign scalars in place; the
78 // best we can do is (a) confine them to the smallest possible scope so
79 // the compiler drops them the instant we no longer need them, and (b)
80 // route every byte buffer WE own through `Zeroizing` so it is wiped on
81 // drop. The 32-byte `to_bytes()` array is a stack temporary, so it is
82 // wrapped in `Zeroizing` before being copied into the returned `Vec`.
83 // A cross-repo follow-up requests `Zeroize` on `chia_bls::SecretKey`
84 // (or a zeroizing derivation in dig-identity); see #1327.
85 let secret: Zeroizing<Vec<u8>> = {
86 let master = master_secret_key_from_seed(seed);
87 let identity_sk = derive_identity_sk(&master);
88 let canonical_bytes = Zeroizing::new(identity_sk.to_bytes());
89 Zeroizing::new(canonical_bytes.to_vec())
90 // `master` and `identity_sk` drop here — as early as possible.
91 };
92
93 // Persist the already-derived key. `unlock` needs the password again,
94 // and `create` consumes it, so clone before the move.
95 let unlock_password = Password::new(password.as_bytes());
96 let keystore = Keystore::<L1WalletBls>::create(
97 backend,
98 path,
99 password,
100 Some(secret),
101 KdfParams::DEFAULT,
102 )?;
103 let signer = keystore.unlock(unlock_password)?;
104 Ok(UnlockedIdentity::new(signer))
105 }
106}