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