Skip to main content

keep_core/frost/
signing.rs

1// SPDX-FileCopyrightText: © 2026 PrivKey LLC
2// SPDX-License-Identifier: MIT
3
4//! FROST signing session management.
5
6use std::collections::BTreeMap;
7
8use frost::{
9    keys::{KeyPackage, PublicKeyPackage},
10    rand_core::OsRng,
11    round1::{SigningCommitments, SigningNonces},
12    round2::SignatureShare,
13    Identifier, Signature, SigningPackage,
14};
15use frost_secp256k1_tr as frost;
16use zeroize::ZeroizeOnDrop;
17
18use crate::crypto;
19use crate::error::{KeepError, Result};
20
21/// State of a signing session.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum SessionState {
24    /// Collecting round 1 commitments from participants.
25    CollectingCommitments,
26    /// Collecting round 2 signature shares.
27    CollectingShares,
28    /// Signing completed successfully.
29    Complete,
30    /// Signing failed.
31    Failed,
32}
33
34/// A FROST signing session.
35///
36/// Manages the two-round signing protocol state and collected data.
37#[derive(ZeroizeOnDrop)]
38pub struct SigningSession {
39    #[zeroize(skip)]
40    session_id: [u8; 32],
41    #[zeroize(skip)]
42    message: Vec<u8>,
43    #[zeroize(skip)]
44    threshold: u16,
45    #[zeroize(skip)]
46    state: SessionState,
47
48    #[zeroize(skip)]
49    commitments: BTreeMap<Identifier, SigningCommitments>,
50    #[zeroize(skip)]
51    signature_shares: BTreeMap<Identifier, SignatureShare>,
52
53    our_nonces: Option<SigningNonces>,
54
55    #[zeroize(skip)]
56    signature: Option<Signature>,
57}
58
59impl SigningSession {
60    /// Create a new signing session. Returns `Err` (rather than panicking) if the
61    /// CSPRNG health check fails, so a broken RNG cannot crash the caller.
62    pub fn new(message: Vec<u8>, threshold: u16) -> Result<Self> {
63        let session_id = Self::compute_session_id(&message)?;
64
65        Ok(Self {
66            session_id,
67            message,
68            threshold,
69            state: SessionState::CollectingCommitments,
70            commitments: BTreeMap::new(),
71            signature_shares: BTreeMap::new(),
72            our_nonces: None,
73            signature: None,
74        })
75    }
76
77    fn compute_session_id(message: &[u8]) -> Result<[u8; 32]> {
78        let timestamp = chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0);
79        let random: [u8; 16] = crypto::try_random_bytes()?;
80
81        let mut preimage = Vec::with_capacity(message.len() + 24);
82        preimage.extend_from_slice(message);
83        preimage.extend_from_slice(&timestamp.to_le_bytes());
84        preimage.extend_from_slice(&random);
85
86        Ok(crypto::blake2b_256(&preimage))
87    }
88
89    /// The session ID.
90    pub fn session_id(&self) -> &[u8; 32] {
91        &self.session_id
92    }
93
94    /// The current session state.
95    pub fn state(&self) -> SessionState {
96        self.state
97    }
98
99    /// Generate our commitment (round 1). Must not have been called before.
100    pub fn generate_commitment(&mut self, key_package: &KeyPackage) -> Result<SigningCommitments> {
101        if self.state != SessionState::CollectingCommitments {
102            return Err(KeepError::Frost(
103                "Invalid session state for commitment".into(),
104            ));
105        }
106
107        if self.our_nonces.is_some() {
108            return Err(KeepError::Frost(
109                "Commitment already generated for this session".into(),
110            ));
111        }
112
113        let (nonces, commitments) = frost::round1::commit(key_package.signing_share(), &mut OsRng);
114
115        self.our_nonces = Some(nonces);
116        self.commitments
117            .insert(*key_package.identifier(), commitments);
118
119        Ok(commitments)
120    }
121
122    /// Add another participant's commitment.
123    pub fn add_commitment(&mut self, id: Identifier, commitment: SigningCommitments) -> Result<()> {
124        if self.state != SessionState::CollectingCommitments {
125            return Err(KeepError::Frost("Not collecting commitments".into()));
126        }
127
128        if self.commitments.contains_key(&id) {
129            return Err(KeepError::Frost("Duplicate commitment".into()));
130        }
131
132        self.commitments.insert(id, commitment);
133
134        if self.commitments.len() >= self.threshold as usize {
135            self.state = SessionState::CollectingShares;
136        }
137
138        Ok(())
139    }
140
141    /// Commitments still needed to reach threshold.
142    pub fn commitments_needed(&self) -> usize {
143        (self.threshold as usize).saturating_sub(self.commitments.len())
144    }
145
146    /// Generate our signature share (round 2).
147    pub fn generate_signature_share(&mut self, key_package: &KeyPackage) -> Result<SignatureShare> {
148        if self.state != SessionState::CollectingShares {
149            return Err(KeepError::Frost(
150                "Not ready to generate signature share".into(),
151            ));
152        }
153
154        let nonces = self
155            .our_nonces
156            .take()
157            .ok_or_else(|| KeepError::Frost("No nonces available - already used?".into()))?;
158
159        let signing_package = SigningPackage::new(self.commitments.clone(), &self.message);
160
161        let share = frost::round2::sign(&signing_package, &nonces, key_package)
162            .map_err(|e| KeepError::Frost(format!("Signing failed: {e}")))?;
163
164        self.signature_shares
165            .insert(*key_package.identifier(), share);
166
167        Ok(share)
168    }
169
170    /// Add another participant's signature share.
171    /// Returns the aggregated signature when threshold is met.
172    pub fn add_signature_share(
173        &mut self,
174        id: Identifier,
175        share: SignatureShare,
176        pubkey_pkg: &PublicKeyPackage,
177    ) -> Result<Option<Signature>> {
178        if self.state != SessionState::CollectingShares {
179            return Err(KeepError::Frost("Not collecting signature shares".into()));
180        }
181
182        if self.signature_shares.contains_key(&id) {
183            return Err(KeepError::Frost("Duplicate signature share".into()));
184        }
185
186        self.signature_shares.insert(id, share);
187
188        if self.signature_shares.len() >= self.threshold as usize {
189            let signing_package = SigningPackage::new(self.commitments.clone(), &self.message);
190
191            match frost::aggregate(&signing_package, &self.signature_shares, pubkey_pkg) {
192                Ok(signature) => {
193                    self.signature = Some(signature);
194                    self.state = SessionState::Complete;
195                    return Ok(Some(signature));
196                }
197                Err(e) => {
198                    self.state = SessionState::Failed;
199                    return Err(KeepError::Frost(format!("Aggregation failed: {e}")));
200                }
201            }
202        }
203
204        Ok(None)
205    }
206
207    /// Signature shares still needed to reach threshold.
208    pub fn shares_needed(&self) -> usize {
209        (self.threshold as usize).saturating_sub(self.signature_shares.len())
210    }
211
212    /// The signature bytes, if signing is complete.
213    pub fn signature_bytes(&self) -> Result<Option<[u8; 64]>> {
214        match &self.signature {
215            Some(s) => {
216                let serialized = s
217                    .serialize()
218                    .map_err(|e| KeepError::Frost(format!("Failed to serialize signature: {e}")))?;
219                let bytes_slice = serialized.as_slice();
220                if bytes_slice.len() != 64 {
221                    return Err(KeepError::Frost("Invalid signature length".into()));
222                }
223                let mut bytes = [0u8; 64];
224                bytes.copy_from_slice(bytes_slice);
225                Ok(Some(bytes))
226            }
227            None => Ok(None),
228        }
229    }
230
231    /// Returns true if signing completed successfully.
232    pub fn is_complete(&self) -> bool {
233        self.state == SessionState::Complete
234    }
235}
236
237/// Sign using local shares only (no network). Requires threshold shares.
238pub fn sign_with_local_shares(shares: &[super::SharePackage], message: &[u8]) -> Result<[u8; 64]> {
239    if shares.is_empty() {
240        return Err(KeepError::Frost("No shares provided".into()));
241    }
242
243    let threshold = shares[0].metadata.threshold as usize;
244    if shares.len() < threshold {
245        return Err(KeepError::Frost(format!(
246            "Need {} shares to sign, only {} provided",
247            threshold,
248            shares.len()
249        )));
250    }
251
252    let kps: Vec<KeyPackage> = shares[..threshold]
253        .iter()
254        .map(|s| s.key_package())
255        .collect::<Result<Vec<_>>>()?;
256    aggregate_local(&kps, message)
257}
258
259/// Run the FROST round1/round2/aggregate flow over an explicit set of
260/// `KeyPackage`s and return the 64-byte BIP-340 signature. Shared by the
261/// plain local-shares path and the BIP-32 child-key signing path (which
262/// passes tweaked packages). `kps` must be non-empty and already reduced to
263/// exactly the threshold set of signers.
264pub(super) fn aggregate_local(kps: &[KeyPackage], message: &[u8]) -> Result<[u8; 64]> {
265    use frost::{round1, round2};
266
267    let mut nonces_map: BTreeMap<Identifier, round1::SigningNonces> = BTreeMap::new();
268    let mut commitments_map: BTreeMap<Identifier, round1::SigningCommitments> = BTreeMap::new();
269    let mut verifying_shares: BTreeMap<Identifier, frost::keys::VerifyingShare> = BTreeMap::new();
270
271    for kp in kps {
272        let (nonces, commitments) = round1::commit(kp.signing_share(), &mut OsRng);
273        nonces_map.insert(*kp.identifier(), nonces);
274        commitments_map.insert(*kp.identifier(), commitments);
275        verifying_shares.insert(*kp.identifier(), *kp.verifying_share());
276    }
277
278    let signing_package = SigningPackage::new(commitments_map, message);
279
280    let mut signature_shares: BTreeMap<Identifier, round2::SignatureShare> = BTreeMap::new();
281    for kp in kps {
282        let id = *kp.identifier();
283        let nonces = nonces_map
284            .remove(&id)
285            .ok_or_else(|| KeepError::Frost("Missing nonces for share".into()))?;
286        let sig_share = round2::sign(&signing_package, &nonces, kp)
287            .map_err(|e| KeepError::Frost(format!("Signing failed: {e}")))?;
288        signature_shares.insert(id, sig_share);
289    }
290
291    let pubkey_pkg = PublicKeyPackage::new(
292        verifying_shares,
293        *kps[0].verifying_key(),
294        Some(*kps[0].min_signers()),
295    );
296    let signature = frost::aggregate(&signing_package, &signature_shares, &pubkey_pkg)
297        .map_err(|e| KeepError::Frost(format!("Aggregation failed: {e}")))?;
298
299    let serialized = signature
300        .serialize()
301        .map_err(|e| KeepError::Frost(format!("Failed to serialize signature: {e}")))?;
302    let bytes_slice = serialized.as_slice();
303    if bytes_slice.len() != 64 {
304        return Err(KeepError::Frost("Invalid signature length".into()));
305    }
306
307    let mut sig_bytes = [0u8; 64];
308    sig_bytes.copy_from_slice(bytes_slice);
309    Ok(sig_bytes)
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use crate::frost::{ThresholdConfig, TrustedDealer};
316
317    #[test]
318    fn test_signing_session_two_of_three() {
319        let config = ThresholdConfig::two_of_three();
320        let dealer = TrustedDealer::new(config);
321        let (shares, pubkey_pkg) = dealer.generate("test").unwrap();
322
323        let message = b"test message to sign".to_vec();
324
325        let kp0 = shares[0].key_package().unwrap();
326        let kp1 = shares[1].key_package().unwrap();
327
328        let mut session0 = SigningSession::new(message.clone(), 2).unwrap();
329        let mut session1 = SigningSession::new(message.clone(), 2).unwrap();
330        session1.session_id = session0.session_id;
331
332        let commit0 = session0.generate_commitment(&kp0).unwrap();
333        let commit1 = session1.generate_commitment(&kp1).unwrap();
334
335        session0.add_commitment(*kp1.identifier(), commit1).unwrap();
336        session1.add_commitment(*kp0.identifier(), commit0).unwrap();
337
338        assert_eq!(session0.state(), SessionState::CollectingShares);
339        assert_eq!(session1.state(), SessionState::CollectingShares);
340
341        let share0 = session0.generate_signature_share(&kp0).unwrap();
342        let share1 = session1.generate_signature_share(&kp1).unwrap();
343
344        session0
345            .add_signature_share(*kp1.identifier(), share1, &pubkey_pkg)
346            .unwrap();
347        let result = session1
348            .add_signature_share(*kp0.identifier(), share0, &pubkey_pkg)
349            .unwrap();
350
351        assert!(session0.is_complete());
352        assert!(result.is_some());
353
354        let sig_bytes = session0.signature_bytes().unwrap().unwrap();
355        assert_eq!(sig_bytes.len(), 64);
356    }
357
358    #[test]
359    fn test_nonce_single_use() {
360        let config = ThresholdConfig::two_of_three();
361        let dealer = TrustedDealer::new(config);
362        let (shares, _) = dealer.generate("test").unwrap();
363
364        let message = b"test message".to_vec();
365        let kp = shares[0].key_package().unwrap();
366
367        let mut session = SigningSession::new(message, 2).unwrap();
368        let _ = session.generate_commitment(&kp).unwrap();
369
370        let result = session.generate_commitment(&kp);
371        assert!(result.is_err());
372    }
373}