Skip to main content

vouch_core/
threshold.rs

1//! FROST(Ed25519, SHA-512) threshold signing (RFC 9591).
2//!
3//! Wraps the audited Zcash Foundation `frost-ed25519` crate. A key is split
4//! among `max_signers` participants so that any `min_signers` of them can
5//! produce a signature together, WITHOUT the full private key ever being
6//! reconstructed at any point, not even during signing. This is distinct from
7//! Shamir secret sharing (see the Python `vouch.recovery` module and its
8//! `split_secret`/`combine_shares`), where the secret IS reconstructed; FROST
9//! is for live, repeated signing across a threshold of custodians.
10//!
11//! The critical property that makes this a drop-in fit for Vouch: the
12//! aggregated signature is a STANDARD Ed25519 signature (RFC 8032), so it
13//! verifies with the existing [`crate::keys::verify`] and needs no new proof
14//! type, cryptosuite, or verifier anywhere in the protocol. A verifier cannot
15//! tell whether a credential was signed by one key or by a threshold of
16//! shares.
17//!
18//! Design note: [`generate_key`] mints a FRESH threshold-native group
19//! identity (via a trusted dealer), rather than converting an existing
20//! single-key Ed25519 identity into a threshold one. This is deliberate: a
21//! standard Ed25519 private key is derived from its 32-byte seed via
22//! SHA-512-and-clamp (RFC 8032 §5.1.5), and the resulting scalar is not
23//! generally a canonical element of the group order used by FROST's scalar
24//! field. Naively reducing it would silently produce a DIFFERENT public key,
25//! which would break the DID it was meant to protect. Treat a threshold
26//! identity as its own identity from the start, exactly like
27//! `generate_identity`, and enroll it as a device or root the same way any
28//! other Vouch identity is enrolled.
29//!
30//! Ceremony (four steps, mirroring RFC 9591 §5):
31//!
32//!   1. [`generate_key`]: a trusted dealer mints `max_signers` key shares and
33//!      a group public key. (Full distributed key generation, where no single
34//!      party ever sees a complete key even momentarily, is a further step not
35//!      implemented here; the dealer only ever handles shares and the public
36//!      key, never a reconstructed private scalar.)
37//!   2. [`commit`]: each signer, locally, generates single-use signing nonces
38//!      (kept secret, never transmitted) and a public commitment (safe to
39//!      send to the coordinator).
40//!   3. [`sign_share`]: each signer, given the message and every signer's
41//!      commitment, produces a signature share using its own key share and
42//!      nonces.
43//!   4. [`aggregate`]: the coordinator combines `min_signers` (or more)
44//!      signature shares into one final, standard Ed25519 signature.
45//!
46//! There is deliberately no `reconstruct` function exposed here. The
47//! underlying crate provides one (`frost_ed25519::keys::reconstruct`) as an
48//! explicit escape hatch documented as NOT required for signing; Vouch does
49//! not wrap or expose it, so nothing in this module can assemble the full key.
50
51use std::collections::BTreeMap;
52
53use frost_ed25519 as frost;
54use rand_core::OsRng;
55
56use crate::error::{CoreError, Result};
57
58fn threshold_err<E: std::fmt::Display>(e: E) -> CoreError {
59    CoreError::Threshold(e.to_string())
60}
61
62/// One participant's share of a threshold key. `key_package` is secret key
63/// material (a scalar share of the group secret) and must be kept only by the
64/// participant it was issued to.
65#[derive(Clone)]
66pub struct KeyShare {
67    pub identifier: Vec<u8>,
68    pub key_package: Vec<u8>,
69}
70
71/// The group's public identity. `verifying_key` is a standard 32-byte Ed25519
72/// public key: it is what you publish as the DID's verification method key,
73/// exactly like any other Vouch identity's public key.
74#[derive(Clone)]
75pub struct GroupPublicKey {
76    pub verifying_key: [u8; 32],
77    pub public_key_package: Vec<u8>,
78}
79
80/// Output of [`generate_key`].
81pub struct GenerateKeyResult {
82    pub shares: Vec<KeyShare>,
83    pub group_public_key: GroupPublicKey,
84}
85
86/// Mint a fresh threshold-native Ed25519 identity: `max_signers` key shares,
87/// any `min_signers` of which can sign together, and a group public key. The
88/// dealer performing this call sees every share transiently (to hand them out)
89/// but never a reconstructed private key; the underlying crate samples the
90/// group secret directly as shares via verifiable secret sharing, never
91/// materializing it as a single scalar.
92pub fn generate_key(min_signers: u16, max_signers: u16) -> Result<GenerateKeyResult> {
93    if min_signers < 2 || min_signers > max_signers {
94        return Err(CoreError::Threshold(format!(
95            "require 2 <= min_signers <= max_signers, got min={min_signers} max={max_signers}"
96        )));
97    }
98
99    let (shares, pubkey_package) = frost::keys::generate_with_dealer(
100        max_signers,
101        min_signers,
102        frost::keys::IdentifierList::Default,
103        OsRng,
104    )
105    .map_err(threshold_err)?;
106
107    let mut out_shares = Vec::with_capacity(shares.len());
108    for (identifier, secret_share) in shares {
109        let key_package: frost::keys::KeyPackage =
110            secret_share.try_into().map_err(threshold_err)?;
111        out_shares.push(KeyShare {
112            identifier: identifier.serialize(),
113            key_package: key_package.serialize().map_err(threshold_err)?,
114        });
115    }
116
117    let verifying_key_bytes = pubkey_package
118        .verifying_key()
119        .serialize()
120        .map_err(threshold_err)?;
121    let verifying_key: [u8; 32] = verifying_key_bytes
122        .try_into()
123        .map_err(|_| CoreError::Threshold("group verifying key was not 32 bytes".into()))?;
124
125    Ok(GenerateKeyResult {
126        shares: out_shares,
127        group_public_key: GroupPublicKey {
128            verifying_key,
129            public_key_package: pubkey_package.serialize().map_err(threshold_err)?,
130        },
131    })
132}
133
134/// Round 1 output for one signer: secret nonces (kept locally, used exactly
135/// once) and a public commitment (sent to the coordinator).
136pub struct Round1 {
137    pub nonces: Vec<u8>,
138    pub commitments: Vec<u8>,
139}
140
141/// Round 1: a signer generates its single-use nonces and public commitment.
142/// `nonces` MUST be used for exactly one [`sign_share`] call and then
143/// discarded; reusing them leaks the signer's key share.
144pub fn commit(key_share: &KeyShare) -> Result<Round1> {
145    let key_package = deserialize_key_package(&key_share.key_package)?;
146    let mut rng = OsRng;
147    let (nonces, commitments) = frost::round1::commit(key_package.signing_share(), &mut rng);
148    Ok(Round1 {
149        nonces: nonces.serialize().map_err(threshold_err)?,
150        commitments: commitments.serialize().map_err(threshold_err)?,
151    })
152}
153
154/// Round 2: given the message and every participating signer's commitment,
155/// this signer produces its signature share using its own key share and its
156/// own (single-use) nonces from [`commit`]. `commitments_by_participant` must
157/// include an entry for every signer taking part in this signature, including
158/// this one.
159pub fn sign_share(
160    message: &[u8],
161    key_share: &KeyShare,
162    nonces: &[u8],
163    commitments_by_participant: &BTreeMap<Vec<u8>, Vec<u8>>,
164) -> Result<Vec<u8>> {
165    let key_package = deserialize_key_package(&key_share.key_package)?;
166    let signing_nonces =
167        frost::round1::SigningNonces::deserialize(nonces).map_err(threshold_err)?;
168    let signing_package = build_signing_package(message, commitments_by_participant)?;
169
170    let share = frost::round2::sign(&signing_package, &signing_nonces, &key_package)
171        .map_err(threshold_err)?;
172    Ok(share.serialize())
173}
174
175/// Combine `min_signers` (or more) signature shares into the final, standard
176/// Ed25519 signature. Verify the result with [`crate::keys::verify`] against
177/// `group_public_key.verifying_key`, exactly like any other Vouch credential.
178pub fn aggregate(
179    message: &[u8],
180    commitments_by_participant: &BTreeMap<Vec<u8>, Vec<u8>>,
181    shares_by_participant: &BTreeMap<Vec<u8>, Vec<u8>>,
182    group_public_key: &GroupPublicKey,
183) -> Result<[u8; 64]> {
184    let signing_package = build_signing_package(message, commitments_by_participant)?;
185
186    let mut shares = BTreeMap::new();
187    for (id_bytes, share_bytes) in shares_by_participant {
188        let identifier = frost::Identifier::deserialize(id_bytes).map_err(threshold_err)?;
189        let share =
190            frost::round2::SignatureShare::deserialize(share_bytes).map_err(threshold_err)?;
191        shares.insert(identifier, share);
192    }
193
194    let pubkey_package =
195        frost::keys::PublicKeyPackage::deserialize(&group_public_key.public_key_package)
196            .map_err(threshold_err)?;
197
198    let signature =
199        frost::aggregate(&signing_package, &shares, &pubkey_package).map_err(threshold_err)?;
200    let sig_bytes = signature.serialize().map_err(threshold_err)?;
201    let sig_arr: [u8; 64] = sig_bytes
202        .try_into()
203        .map_err(|_| CoreError::Threshold("aggregated signature was not 64 bytes".into()))?;
204
205    // Defense in depth: an aggregate signature that does not verify against
206    // the group's own public key indicates a bug or a misbehaving signer, and
207    // must never be returned to a caller as if it were valid.
208    let self_check = crate::keys::verify(&group_public_key.verifying_key, message, &sig_arr)
209        .map_err(threshold_err)?;
210    if !self_check {
211        return Err(CoreError::Threshold(
212            "aggregated signature failed self-verification".into(),
213        ));
214    }
215
216    Ok(sig_arr)
217}
218
219fn deserialize_key_package(bytes: &[u8]) -> Result<frost::keys::KeyPackage> {
220    frost::keys::KeyPackage::deserialize(bytes).map_err(threshold_err)
221}
222
223fn build_signing_package(
224    message: &[u8],
225    commitments_by_participant: &BTreeMap<Vec<u8>, Vec<u8>>,
226) -> Result<frost::SigningPackage> {
227    if commitments_by_participant.len() < 2 {
228        return Err(CoreError::Threshold(
229            "need commitments from at least 2 participants".into(),
230        ));
231    }
232    let mut commitments = BTreeMap::new();
233    for (id_bytes, commitment_bytes) in commitments_by_participant {
234        let identifier = frost::Identifier::deserialize(id_bytes).map_err(threshold_err)?;
235        let commitment = frost::round1::SigningCommitments::deserialize(commitment_bytes)
236            .map_err(threshold_err)?;
237        commitments.insert(identifier, commitment);
238    }
239    Ok(frost::SigningPackage::new(commitments, message))
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    fn generate_commit_sign_aggregate(
247        min_signers: u16,
248        max_signers: u16,
249        signer_indices: &[usize],
250        message: &[u8],
251    ) -> (GenerateKeyResult, [u8; 64]) {
252        let generated = generate_key(min_signers, max_signers).expect("generate_key");
253        assert_eq!(generated.shares.len(), max_signers as usize);
254
255        let chosen: Vec<&KeyShare> = signer_indices
256            .iter()
257            .map(|&i| &generated.shares[i])
258            .collect();
259
260        let mut nonces_by_signer = BTreeMap::new();
261        let mut commitments = BTreeMap::new();
262        for share in &chosen {
263            let round1 = commit(share).expect("commit");
264            commitments.insert(share.identifier.clone(), round1.commitments);
265            nonces_by_signer.insert(share.identifier.clone(), round1.nonces);
266        }
267
268        let mut shares_out = BTreeMap::new();
269        for share in &chosen {
270            let nonces = nonces_by_signer.get(&share.identifier).unwrap();
271            let sig_share = sign_share(message, share, nonces, &commitments).expect("sign_share");
272            shares_out.insert(share.identifier.clone(), sig_share);
273        }
274
275        let signature = aggregate(
276            message,
277            &commitments,
278            &shares_out,
279            &generated.group_public_key,
280        )
281        .expect("aggregate");
282
283        (generated, signature)
284    }
285
286    #[test]
287    fn two_of_three_signs_and_verifies_as_plain_ed25519() {
288        let message = b"charge api.bank invoices/42";
289        let (generated, signature) = generate_commit_sign_aggregate(2, 3, &[0, 2], message);
290
291        let ok = crate::keys::verify(
292            &generated.group_public_key.verifying_key,
293            message,
294            &signature,
295        )
296        .expect("verify");
297        assert!(
298            ok,
299            "FROST aggregate signature must verify as a plain Ed25519 signature"
300        );
301    }
302
303    #[test]
304    fn three_of_five_any_subset_works() {
305        let message = b"read did:web:files https://files/x";
306        let (generated, signature) = generate_commit_sign_aggregate(3, 5, &[1, 3, 4], message);
307        let ok = crate::keys::verify(
308            &generated.group_public_key.verifying_key,
309            message,
310            &signature,
311        )
312        .expect("verify");
313        assert!(ok);
314    }
315
316    #[test]
317    fn different_subset_of_same_group_also_verifies() {
318        // Any qualifying subset of signers produces a signature that verifies
319        // against the SAME group public key.
320        let message = b"same message, different signer subset";
321        let generated = generate_key(3, 5).expect("generate_key");
322
323        let sign_with = |indices: &[usize]| -> [u8; 64] {
324            let chosen: Vec<&KeyShare> = indices.iter().map(|&i| &generated.shares[i]).collect();
325            let mut nonces_by_signer = BTreeMap::new();
326            let mut commitments = BTreeMap::new();
327            for share in &chosen {
328                let round1 = commit(share).expect("commit");
329                commitments.insert(share.identifier.clone(), round1.commitments);
330                nonces_by_signer.insert(share.identifier.clone(), round1.nonces);
331            }
332            let mut shares_out = BTreeMap::new();
333            for share in &chosen {
334                let nonces = nonces_by_signer.get(&share.identifier).unwrap();
335                let sig_share =
336                    sign_share(message, share, nonces, &commitments).expect("sign_share");
337                shares_out.insert(share.identifier.clone(), sig_share);
338            }
339            aggregate(
340                message,
341                &commitments,
342                &shares_out,
343                &generated.group_public_key,
344            )
345            .expect("aggregate")
346        };
347
348        let sig_a = sign_with(&[0, 1, 2]);
349        let sig_b = sign_with(&[2, 3, 4]);
350        assert!(
351            crate::keys::verify(&generated.group_public_key.verifying_key, message, &sig_a)
352                .unwrap()
353        );
354        assert!(
355            crate::keys::verify(&generated.group_public_key.verifying_key, message, &sig_b)
356                .unwrap()
357        );
358    }
359
360    #[test]
361    fn wrong_message_fails_verification() {
362        let message = b"original message";
363        let (generated, signature) = generate_commit_sign_aggregate(2, 3, &[0, 1], message);
364        let ok = crate::keys::verify(
365            &generated.group_public_key.verifying_key,
366            b"tampered message",
367            &signature,
368        )
369        .expect("verify");
370        assert!(
371            !ok,
372            "a signature over one message must not verify a different message"
373        );
374    }
375
376    #[test]
377    fn different_groups_have_different_public_keys() {
378        let a = generate_key(2, 3).unwrap();
379        let b = generate_key(2, 3).unwrap();
380        assert_ne!(
381            a.group_public_key.verifying_key,
382            b.group_public_key.verifying_key
383        );
384    }
385
386    #[test]
387    fn generate_key_rejects_bad_threshold() {
388        assert!(generate_key(1, 3).is_err()); // min_signers must be >= 2
389        assert!(generate_key(4, 3).is_err()); // min_signers must be <= max_signers
390    }
391
392    #[test]
393    fn aggregate_rejects_single_commitment() {
394        let generated = generate_key(2, 3).unwrap();
395        let message = b"x";
396
397        let share0 = &generated.shares[0];
398        let round1 = commit(share0).unwrap();
399        let mut commitments = BTreeMap::new();
400        commitments.insert(share0.identifier.clone(), round1.commitments);
401
402        // Only one participant's commitment: below the 2-signer threshold.
403        let result = sign_share(message, share0, &round1.nonces, &commitments);
404        assert!(result.is_err());
405    }
406
407    /// Structural proof that this module cannot reconstruct the full private
408    /// key: there is no function anywhere in this module that takes key
409    /// shares and returns a seed, signing key, or private scalar of any kind.
410    /// `generate_key` only ever returns shares and a PUBLIC key, and every
411    /// other function in this module takes shares in and returns either a
412    /// public commitment, a signature share, or the final public signature.
413    #[test]
414    fn no_function_in_this_module_returns_a_private_scalar() {
415        let generated = generate_key(2, 3).unwrap();
416        // group_public_key.verifying_key is 32 bytes, the same length as a
417        // private seed elsewhere in this crate, so a naive size check would
418        // not catch a reassembled key; the real guarantee is structural: read
419        // the module source above, there is no reconstruct/combine-to-secret
420        // function. This assertion documents that the public key differs from
421        // every individual share's key_package bytes (which are secret and
422        // never returned as a combined whole).
423        for share in &generated.shares {
424            assert_ne!(
425                share.key_package,
426                generated.group_public_key.public_key_package
427            );
428        }
429    }
430}