1use core::{cmp::PartialEq, fmt::Debug};
2use hashbrown::{HashMap, HashSet};
3use polynomial::Polynomial;
4use rand_core::{CryptoRng, RngCore};
5use serde::{Deserialize, Serialize};
6use std::fmt;
7
8use crate::{
9 common::{MerkleRoot, Nonce, PolyCommitment, PublicNonce, Signature, SignatureShare},
10 curve::{point::Point, scalar::Scalar},
11 errors::{AggregatorError, DkgError},
12 taproot::SchnorrProof,
13};
14
15#[derive(Clone, Deserialize, Serialize, PartialEq)]
16pub struct PartyState {
18 pub polynomial: Option<Polynomial<Scalar>>,
20 pub private_keys: Vec<(u32, Scalar)>,
22 pub nonce: Nonce,
24}
25
26impl fmt::Debug for PartyState {
27 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28 f.debug_struct("PartyState").finish_non_exhaustive()
29 }
30}
31
32#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
33pub struct SignerState {
35 pub id: u32,
37 pub key_ids: Vec<u32>,
39 pub num_keys: u32,
41 pub num_parties: u32,
43 pub threshold: u32,
45 pub group_key: Point,
47 pub parties: Vec<(u32, PartyState)>,
49}
50
51pub trait Signer: Clone + Debug + PartialEq {
53 fn new<RNG: RngCore + CryptoRng>(
55 party_id: u32,
56 key_ids: &[u32],
57 num_signers: u32,
58 num_keys: u32,
59 threshold: u32,
60 rng: &mut RNG,
61 ) -> Self;
62
63 fn load(state: &SignerState) -> Self;
65
66 fn save(&self) -> SignerState;
68
69 fn get_id(&self) -> u32;
71
72 fn get_key_ids(&self) -> Vec<u32>;
74
75 fn get_num_parties(&self) -> u32;
77
78 fn get_poly_commitments<RNG: RngCore + CryptoRng>(
80 &self,
81 ctx: &[u8],
82 rng: &mut RNG,
83 ) -> Vec<PolyCommitment>;
84
85 fn reset_polys<RNG: RngCore + CryptoRng>(&mut self, rng: &mut RNG);
87
88 fn clear_polys(&mut self);
90
91 fn get_shares(&self) -> HashMap<u32, HashMap<u32, Scalar>>;
93
94 fn compute_secrets(
96 &mut self,
97 shares: &HashMap<u32, HashMap<u32, Scalar>>,
98 polys: &HashMap<u32, PolyCommitment>,
99 ctx: &[u8],
100 ) -> Result<(), HashMap<u32, DkgError>>;
101
102 fn gen_nonces<RNG: RngCore + CryptoRng>(
104 &mut self,
105 secret_key: &Scalar,
106 rng: &mut RNG,
107 ) -> Vec<PublicNonce>;
108
109 fn compute_intermediate(
111 &self,
112 msg: &[u8],
113 signer_ids: &[u32],
114 key_ids: &[u32],
115 nonces: &[PublicNonce],
116 ) -> (Vec<Point>, Point);
117
118 fn validate_party_id(
120 signer_id: u32,
121 party_id: u32,
122 signer_key_ids: &HashMap<u32, HashSet<u32>>,
123 ) -> bool;
124
125 fn sign(
127 &self,
128 msg: &[u8],
129 signer_ids: &[u32],
130 key_ids: &[u32],
131 nonces: &[PublicNonce],
132 ) -> Vec<SignatureShare>;
133
134 fn sign_schnorr(
136 &self,
137 msg: &[u8],
138 signer_ids: &[u32],
139 key_ids: &[u32],
140 nonces: &[PublicNonce],
141 ) -> Vec<SignatureShare>;
142
143 fn sign_taproot(
145 &self,
146 msg: &[u8],
147 signer_ids: &[u32],
148 key_ids: &[u32],
149 nonces: &[PublicNonce],
150 merkle_root: Option<MerkleRoot>,
151 ) -> Vec<SignatureShare>;
152}
153
154pub trait Aggregator: Clone + Debug + PartialEq {
156 fn new(num_keys: u32, threshold: u32) -> Self;
158
159 fn init(&mut self, poly_comms: &HashMap<u32, PolyCommitment>) -> Result<(), AggregatorError>;
161
162 fn sign(
164 &mut self,
165 msg: &[u8],
166 nonces: &[PublicNonce],
167 sig_shares: &[SignatureShare],
168 key_ids: &[u32],
169 ) -> Result<Signature, AggregatorError>;
170
171 fn sign_schnorr(
174 &mut self,
175 msg: &[u8],
176 nonces: &[PublicNonce],
177 sig_shares: &[SignatureShare],
178 key_ids: &[u32],
179 ) -> Result<SchnorrProof, AggregatorError>;
180
181 fn sign_taproot(
185 &mut self,
186 msg: &[u8],
187 nonces: &[PublicNonce],
188 sig_shares: &[SignatureShare],
189 key_ids: &[u32],
190 merkle_root: Option<MerkleRoot>,
191 ) -> Result<SchnorrProof, AggregatorError>;
192}
193
194#[cfg(any(test, feature = "testing"))]
196pub mod test_helpers {
197 use hashbrown::HashMap;
198 use rand_core::{CryptoRng, RngCore};
199
200 use crate::{common::PolyCommitment, errors::DkgError, traits::Scalar, util::create_rng};
201
202 pub fn dkg<RNG: RngCore + CryptoRng, Signer: super::Signer>(
204 signers: &mut [Signer],
205 rng: &mut RNG,
206 ) -> Result<HashMap<u32, PolyCommitment>, HashMap<u32, DkgError>> {
207 let ctx = 0u64.to_be_bytes();
208 let public_shares: HashMap<u32, PolyCommitment> = signers
209 .iter()
210 .flat_map(|s| s.get_poly_commitments(&ctx, rng))
211 .map(|comm| (comm.id.id.get_u32(), comm))
212 .collect();
213 let mut private_shares = HashMap::new();
214
215 for signer in signers.iter() {
216 for (signer_id, signer_shares) in signer.get_shares() {
217 private_shares.insert(signer_id, signer_shares);
218 }
219 }
220
221 let mut secret_errors = HashMap::new();
222 for signer in signers.iter_mut() {
223 if let Err(signer_secret_errors) =
224 signer.compute_secrets(&private_shares, &public_shares, &ctx)
225 {
226 secret_errors.extend(signer_secret_errors);
227 }
228 }
229
230 if secret_errors.is_empty() {
231 Ok(public_shares)
232 } else {
233 Err(secret_errors)
234 }
235 }
236
237 fn compute_secrets_missing_private_shares<RNG: RngCore + CryptoRng, Signer: super::Signer>(
239 signers: &mut [Signer],
240 rng: &mut RNG,
241 missing_key_ids: &[u32],
242 ) -> Result<HashMap<u32, PolyCommitment>, HashMap<u32, DkgError>> {
243 assert!(
244 !missing_key_ids.is_empty(),
245 "Cannot run a missing shares test without specificying at least one missing key id"
246 );
247 let ctx = 0u64.to_be_bytes();
248 let polys: HashMap<u32, PolyCommitment> = signers
249 .iter()
250 .flat_map(|s| s.get_poly_commitments(&ctx, rng))
251 .map(|comm| (comm.id.id.get_u32(), comm))
252 .collect();
253 let mut private_shares = HashMap::new();
254
255 for signer in signers.iter() {
256 for (signer_id, mut signer_shares) in signer.get_shares() {
257 for key_id in missing_key_ids {
258 if signer.get_key_ids().contains(key_id) {
259 signer_shares.remove(key_id);
260 }
261 }
262 private_shares.insert(signer_id, signer_shares);
263 }
264 }
265
266 let mut secret_errors = HashMap::new();
267 for signer in signers.iter_mut() {
268 if let Err(signer_secret_errors) = signer.compute_secrets(&private_shares, &polys, &ctx)
269 {
270 secret_errors.extend(signer_secret_errors);
271 }
272 }
273
274 if secret_errors.is_empty() {
275 Ok(polys)
276 } else {
277 Err(secret_errors)
278 }
279 }
280
281 #[allow(non_snake_case)]
282 pub fn run_compute_secrets_missing_private_shares<Signer: super::Signer>() {
284 let Nk: u32 = 10;
285 let Np: u32 = 4;
286 let T: u32 = 7;
287 let signer_ids: Vec<Vec<u32>> = vec![vec![1, 2, 3], vec![4, 5], vec![6, 7, 8], vec![9, 10]];
288 let missing_key_ids = vec![1, 7];
289 let mut rng = create_rng();
290 let mut signers: Vec<Signer> = signer_ids
291 .iter()
292 .enumerate()
293 .map(|(id, ids)| Signer::new(id.try_into().unwrap(), ids, Nk, Np, T, &mut rng))
294 .collect();
295
296 match compute_secrets_missing_private_shares(&mut signers, &mut rng, &missing_key_ids) {
297 Ok(polys) => panic!("Got a result with missing public shares: {polys:?}"),
298 Err(secret_errors) => {
299 for (_, error) in secret_errors {
300 assert!(matches!(error, DkgError::MissingPrivateShares(_)));
301 }
302 }
303 }
304 }
305
306 pub fn bad_polynomial_length<Signer: super::Signer, F: Fn(u32) -> u32>(func: F) {
308 let num_keys: u32 = 10;
309 let num_signers: u32 = 4;
310 let threshold: u32 = 7;
311 let signer_ids: Vec<Vec<u32>> = vec![vec![1, 2, 3, 4], vec![5, 6, 7], vec![8, 9], vec![10]];
312 let mut rng = create_rng();
313 let mut signers: Vec<Signer> = signer_ids
314 .iter()
315 .enumerate()
316 .map(|(id, ids)| {
317 if *ids == vec![10] {
318 Signer::new(
319 id.try_into().unwrap(),
320 ids,
321 num_signers,
322 num_keys,
323 func(threshold),
324 &mut rng,
325 )
326 } else {
327 Signer::new(
328 id.try_into().unwrap(),
329 ids,
330 num_signers,
331 num_keys,
332 threshold,
333 &mut rng,
334 )
335 }
336 })
337 .collect();
338
339 if dkg(&mut signers, &mut rng).is_ok() {
340 panic!("DKG should have failed")
341 }
342 }
343
344 pub fn bad_polynomial_commitment<Signer: super::Signer>() {
346 let num_keys: u32 = 10;
347 let num_signers: u32 = 4;
348 let threshold: u32 = 7;
349 let signer_ids: Vec<Vec<u32>> = vec![vec![1, 2, 3, 4], vec![5, 6, 7], vec![8, 9], vec![10]];
350 let mut rng = create_rng();
351 let mut signers: Vec<Signer> = signer_ids
352 .iter()
353 .enumerate()
354 .map(|(id, ids)| {
355 Signer::new(
356 id.try_into().unwrap(),
357 ids,
358 num_signers,
359 num_keys,
360 threshold,
361 &mut rng,
362 )
363 })
364 .collect();
365
366 let ctx = 0u64.to_be_bytes();
371 let bad_party_id = 2u32;
372 let public_shares: HashMap<u32, PolyCommitment> = signers
373 .iter()
374 .flat_map(|s| s.get_poly_commitments(&ctx, &mut rng))
375 .map(|comm| {
376 let party_id = comm.id.id.get_u32();
377 if party_id == bad_party_id {
378 let mut bad_comm = comm.clone();
380 bad_comm.id.proof.s += Scalar::from(1);
381 (party_id, bad_comm)
382 } else {
383 (party_id, comm)
384 }
385 })
386 .collect();
387 let mut private_shares = HashMap::new();
388
389 for signer in signers.iter() {
390 for (signer_id, signer_shares) in signer.get_shares() {
391 private_shares.insert(signer_id, signer_shares);
392 }
393 }
394
395 let mut secret_errors = HashMap::new();
396 for signer in signers.iter_mut() {
397 if let Err(signer_secret_errors) =
398 signer.compute_secrets(&private_shares, &public_shares, &ctx)
399 {
400 secret_errors.extend(signer_secret_errors);
401 }
402 }
403
404 assert!(!secret_errors.is_empty());
405 }
406}