Skip to main content

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::{
8    BackendKey, BlsSigning, KdfParams, KeychainBackend, Keystore, L1WalletBls, Password,
9};
10use zeroize::Zeroizing;
11
12use crate::master_seed::SEED_LEN;
13use crate::{Result, SessionError, UnlockedIdentity, UnlockedMasterSeed};
14
15/// Entry point for turning stored, encrypted key material into a live signer.
16///
17/// `Session` is a stateless namespace over the compose-only flow
18/// `dig_keystore::Keystore::<K>::load -> unlock -> SignerHandle<K>`, plus the
19/// enrollment path that derives the canonical dig-identity signing key and
20/// persists it. It holds no state of its own; every method is associated.
21pub struct Session;
22
23impl Session {
24    /// Unlock an existing keystore file into an [`UnlockedIdentity`].
25    ///
26    /// Generic over the storage scheme `K`: use [`dig_keystore::L1WalletBls`]
27    /// for a stored, already-derived key (the identity signing key, wallet
28    /// keys) and [`dig_keystore::BlsSigning`] for a seed-derived validator key.
29    /// The scheme is verified against the file's magic on load, so unlocking a
30    /// file with the wrong scheme fails cleanly rather than yielding a bogus key.
31    ///
32    /// # Errors
33    ///
34    /// Returns [`SessionError::Keystore`] if the file is missing, the password
35    /// is wrong, the ciphertext is tampered, or the scheme does not match.
36    pub fn unlock<K: KeyScheme>(
37        backend: Arc<dyn KeychainBackend>,
38        path: BackendKey,
39        password: Password,
40    ) -> Result<UnlockedIdentity<K>> {
41        let keystore = Keystore::<K>::load(backend, path)?;
42        let signer = keystore.unlock(password)?;
43        Ok(UnlockedIdentity::new(signer))
44    }
45
46    /// Enroll a new identity: derive the canonical dig-identity BLS signing key
47    /// from `seed`, persist it encrypted under `password`, and return it
48    /// unlocked and ready to sign.
49    ///
50    /// The identity key is derived exactly once, via
51    /// [`dig_identity::master_secret_key_from_seed`] followed by
52    /// [`dig_identity::derive_identity_sk`] (the hardened path
53    /// `m/12381'/8444'/9'/0'`), and the resulting secret key's canonical bytes
54    /// are stored. See the module-level note in [`crate`] on why the storage
55    /// scheme is [`L1WalletBls`] (faithful `from_bytes` round-trip) rather than
56    /// `BlsSigning` (which would re-derive via `from_seed` and produce a
57    /// different key).
58    ///
59    /// # Errors
60    ///
61    /// Returns [`SessionError::EmptySeed`] if `seed` is empty, or
62    /// [`SessionError::Keystore`] if a file already exists at `path` or the
63    /// write fails.
64    pub fn enroll_identity(
65        backend: Arc<dyn KeychainBackend>,
66        path: BackendKey,
67        password: Password,
68        seed: &[u8],
69    ) -> Result<UnlockedIdentity<L1WalletBls>> {
70        if seed.is_empty() {
71            return Err(SessionError::EmptySeed);
72        }
73
74        // Derive the canonical identity signing key ONCE, extract its canonical
75        // bytes, and drop the transient key material as early as possible.
76        //
77        // Custody note: `master` and `identity_sk` are `chia_bls::SecretKey`,
78        // which — even in the latest chia-bls (0.46) — is a plain
79        // `#[derive(Clone)]` wrapper over `blst_scalar` with NO `Zeroize`/`Drop`
80        // impl. We therefore cannot wipe those foreign scalars in place; the
81        // best we can do is (a) confine them to the smallest possible scope so
82        // the compiler drops them the instant we no longer need them, and (b)
83        // route every byte buffer WE own through `Zeroizing` so it is wiped on
84        // drop. The 32-byte `to_bytes()` array is a stack temporary, so it is
85        // wrapped in `Zeroizing` before being copied into the returned `Vec`.
86        // A cross-repo follow-up requests `Zeroize` on `chia_bls::SecretKey`
87        // (or a zeroizing derivation in dig-identity); see #1327.
88        let secret: Zeroizing<Vec<u8>> = {
89            let master = master_secret_key_from_seed(seed);
90            let identity_sk = derive_identity_sk(&master);
91            let canonical_bytes = Zeroizing::new(identity_sk.to_bytes());
92            Zeroizing::new(canonical_bytes.to_vec())
93            // `master` and `identity_sk` drop here — as early as possible.
94        };
95
96        // Persist the already-derived key. `unlock` needs the password again,
97        // and `create` consumes it, so clone before the move.
98        let unlock_password = Password::new(password.as_bytes());
99        let keystore = Keystore::<L1WalletBls>::create(
100            backend,
101            path,
102            password,
103            Some(secret),
104            KdfParams::DEFAULT,
105        )?;
106        let signer = keystore.unlock(unlock_password)?;
107        Ok(UnlockedIdentity::new(signer))
108    }
109
110    /// Enroll a new master HD seed: persist the raw `seed` bytes encrypted under
111    /// `password` and return an [`UnlockedMasterSeed`] ready to reconstruct the
112    /// wallet `MasterKey` app-side and to derive the dig-identity key + DEK.
113    ///
114    /// Unlike [`enroll_identity`](Self::enroll_identity) — which stores the
115    /// *derived identity scalar* and can never recover the seed — this path
116    /// stores the **seed itself**, so a consumer can feed it to
117    /// wallet-backend's `MasterKey::from_seed_bytes` (the master-HD model,
118    /// dig_ecosystem #997) while still deriving the byte-identical dig-identity
119    /// key. See the [`crate::UnlockedMasterSeed`] module docs for the layering
120    /// and storage-scheme rationale.
121    ///
122    /// The seed is stored under [`dig_keystore::BlsSigning`] as a 32-byte
123    /// encrypted byte vault (its own signer is never used); the identity key is
124    /// derived from the seed in-crate.
125    ///
126    /// # Errors
127    ///
128    /// Returns [`SessionError::Keystore`] if a file already exists at `path` or
129    /// the write fails.
130    pub fn enroll_master_seed(
131        backend: Arc<dyn KeychainBackend>,
132        path: BackendKey,
133        password: Password,
134        seed: &[u8; SEED_LEN],
135    ) -> Result<UnlockedMasterSeed> {
136        // Store the raw seed verbatim. `create` consumes the password, and
137        // `unlock` needs it again, so clone before the move.
138        let secret = Zeroizing::new(seed.to_vec());
139        let unlock_password = Password::new(password.as_bytes());
140        let keystore = Keystore::<BlsSigning>::create(
141            backend,
142            path,
143            password,
144            Some(secret),
145            KdfParams::DEFAULT,
146        )?;
147        let seed_handle = keystore.unlock(unlock_password)?;
148        Ok(UnlockedMasterSeed::new(seed_handle))
149    }
150
151    /// Unlock an existing master-seed keystore file into an
152    /// [`UnlockedMasterSeed`].
153    ///
154    /// The file must have been written by [`enroll_master_seed`](Self::enroll_master_seed)
155    /// (the [`dig_keystore::BlsSigning`] scheme / `DIGVK1` magic); loading it
156    /// with the wrong scheme fails cleanly.
157    ///
158    /// # Errors
159    ///
160    /// Returns [`SessionError::Keystore`] if the file is missing, the password
161    /// is wrong, the ciphertext is tampered, or the scheme does not match.
162    pub fn unlock_master_seed(
163        backend: Arc<dyn KeychainBackend>,
164        path: BackendKey,
165        password: Password,
166    ) -> Result<UnlockedMasterSeed> {
167        let keystore = Keystore::<BlsSigning>::load(backend, path)?;
168        let seed_handle = keystore.unlock(password)?;
169        Ok(UnlockedMasterSeed::new(seed_handle))
170    }
171}