1use std::fmt;
2
3use hashbrown::{HashMap, HashSet};
4use num_traits::{One, Zero};
5use polynomial::Polynomial;
6use rand_core::{CryptoRng, RngCore};
7use tracing::warn;
8
9use crate::{
10 common::{check_public_shares, Nonce, PolyCommitment, PublicNonce, Signature, SignatureShare},
11 compute,
12 curve::{
13 point::{Point, G},
14 scalar::Scalar,
15 },
16 errors::{AggregatorError, DkgError},
17 schnorr::ID,
18 taproot::SchnorrProof,
19 traits,
20 vss::VSS,
21};
22
23#[derive(Clone, Eq, PartialEq)]
24pub struct Party {
26 pub id: u32,
28 pub public_key: Point,
30 pub f: Option<Polynomial<Scalar>>,
32 num_keys: u32,
33 threshold: u32,
34 private_key: Scalar,
35 pub group_key: Point,
37 nonce: Nonce,
38}
39
40impl fmt::Debug for Party {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 f.debug_struct("Party")
43 .field("id", &self.id)
44 .field("public_key", &self.public_key)
45 .field("num_keys", &self.num_keys)
46 .field("threshold", &self.threshold)
47 .field("group_key", &self.group_key)
48 .finish_non_exhaustive()
49 }
50}
51
52impl Party {
53 pub fn new<RNG: RngCore + CryptoRng>(id: u32, n: u32, t: u32, rng: &mut RNG) -> Self {
55 let secret_key = Scalar::random(rng);
57 let nonce = Nonce::random(&secret_key, rng);
58
59 Self {
60 id,
61 num_keys: n,
62 threshold: t,
63 f: Some(VSS::random_poly(t - 1, rng)),
64 private_key: Scalar::zero(),
65 public_key: Point::zero(),
66 group_key: Point::zero(),
67 nonce,
68 }
69 }
70
71 pub fn load(id: u32, n: u32, t: u32, group_key: &Point, state: &traits::PartyState) -> Self {
73 assert_eq!(state.private_keys.len(), 1);
74 assert_eq!(state.private_keys[0].0, id);
75
76 let private_key = state.private_keys[0].1;
77
78 Self {
79 id,
80 num_keys: n,
81 threshold: t,
82 f: state.polynomial.clone(),
83 public_key: private_key * G,
84 private_key,
85 group_key: *group_key,
86 nonce: state.nonce.clone(),
87 }
88 }
89
90 pub fn save(&self) -> traits::PartyState {
92 traits::PartyState {
93 private_keys: vec![(self.id, self.private_key)],
94 polynomial: self.f.clone(),
95 nonce: self.nonce.clone(),
96 }
97 }
98
99 pub fn gen_nonce<RNG: RngCore + CryptoRng>(
101 &mut self,
102 secret_key: &Scalar,
103 rng: &mut RNG,
104 ) -> PublicNonce {
105 self.nonce = Nonce::random(secret_key, rng);
106
107 PublicNonce::from(&self.nonce)
108 }
109
110 pub fn get_poly_commitment<RNG: RngCore + CryptoRng>(
112 &self,
113 ctx: &[u8],
114 rng: &mut RNG,
115 ) -> Option<PolyCommitment> {
116 if let Some(poly) = &self.f {
117 Some(PolyCommitment {
118 id: ID::new(&self.id(), &poly.data()[0], ctx, rng),
119 poly: (0..poly.data().len())
120 .map(|i| &poly.data()[i] * G)
121 .collect(),
122 })
123 } else {
124 warn!("get_poly_commitment called with no polynomial");
125 None
126 }
127 }
128
129 pub fn reset_poly<RNG: RngCore + CryptoRng>(&mut self, rng: &mut RNG) {
131 self.f = Some(VSS::random_poly(self.threshold - 1, rng));
132 }
133
134 pub fn clear_poly(&mut self) {
136 self.f = None;
137 }
138
139 pub fn get_shares(&self) -> HashMap<u32, Scalar> {
141 if let Some(poly) = &self.f {
142 let mut shares = HashMap::new();
143 for i in 1..self.num_keys + 1 {
144 shares.insert(i, poly.eval(compute::id(i)));
145 }
146 shares
147 } else {
148 warn!("get_shares called with no polynomial");
149 Default::default()
150 }
151 }
152
153 pub fn compute_secret(
155 &mut self,
156 private_shares: HashMap<u32, Scalar>,
157 public_shares: &HashMap<u32, PolyCommitment>,
158 ctx: &[u8],
159 ) -> Result<(), DkgError> {
160 self.private_key = Scalar::zero();
161 self.group_key = Point::zero();
162
163 let threshold: usize = self.threshold.try_into()?;
164 let mut bad_ids = Vec::new(); for (i, comm) in public_shares.iter() {
166 if !check_public_shares(comm, threshold, ctx) {
167 bad_ids.push(*i);
168 } else {
169 self.group_key += comm.poly[0];
170 }
171 }
172 if !bad_ids.is_empty() {
173 return Err(DkgError::BadPublicShares(bad_ids));
174 }
175
176 let mut missing_shares = Vec::new();
177 for i in public_shares.keys() {
178 if private_shares.get(i).is_none() {
179 missing_shares.push((self.id, *i));
180 }
181 }
182 if !missing_shares.is_empty() {
183 return Err(DkgError::MissingPrivateShares(missing_shares));
184 }
185
186 let mut bad_shares = Vec::new();
195 for (i, s) in private_shares.iter() {
196 if let Some(comm) = public_shares.get(i) {
197 if s * G != compute::poly(&self.id(), &comm.poly)? {
198 bad_shares.push(*i);
199 }
200 } else {
201 warn!("unable to check private share from {}: no corresponding public share, even though we checked for it above", i);
202 }
203 }
204
205 if !bad_shares.is_empty() {
206 return Err(DkgError::BadPrivateShares(bad_shares));
207 }
208
209 self.private_key = private_shares.values().sum();
210 self.public_key = self.private_key * G;
211
212 Ok(())
213 }
214
215 fn id(&self) -> Scalar {
217 compute::id(self.id)
218 }
219
220 pub fn sign(&self, msg: &[u8], signers: &[u32], nonces: &[PublicNonce]) -> SignatureShare {
222 let (_, aggregate_nonce) = compute::intermediate(msg, self.group_key, signers, nonces);
223 let commitment_list: Vec<(Scalar, PublicNonce)> = signers
224 .iter()
225 .zip(nonces)
226 .map(|(id, nonce)| (Scalar::from(*id), nonce.clone()))
227 .collect();
228 let mut z = &self.nonce.d
229 + &self.nonce.e * compute::binding(&self.id(), self.group_key, &commitment_list, msg);
230 z += compute::challenge(&self.group_key, &aggregate_nonce, msg)
231 * &self.private_key
232 * compute::lambda(self.id, signers);
233
234 SignatureShare {
235 id: self.id,
236 z_i: z,
237 key_ids: vec![self.id],
238 }
239 }
240
241 pub fn sign_precomputed(
243 &self,
244 msg: &[u8],
245 signers: &[u32],
246 nonces: &[PublicNonce],
247 aggregate_nonce: &Point,
248 ) -> SignatureShare {
249 self.sign_precomputed_with_tweak(msg, signers, nonces, aggregate_nonce, None)
250 }
251
252 pub fn sign_precomputed_with_tweak(
257 &self,
258 msg: &[u8],
259 signers: &[u32],
260 nonces: &[PublicNonce],
261 aggregate_nonce: &Point,
262 tweak: Option<Scalar>,
263 ) -> SignatureShare {
264 let commitment_list: Vec<(Scalar, PublicNonce)> = signers
265 .iter()
266 .zip(nonces)
267 .map(|(id, nonce)| (Scalar::from(*id), nonce.clone()))
268 .collect();
269 let mut r = &self.nonce.d
270 + &self.nonce.e * compute::binding(&self.id(), self.group_key, &commitment_list, msg);
271 if tweak.is_some() && !aggregate_nonce.has_even_y() {
272 r = -r;
273 }
274
275 let mut cx_sign = Scalar::one();
280 let tweaked_public_key = if let Some(t) = tweak {
281 if t != Scalar::zero() {
282 let key = compute::tweaked_public_key_from_tweak(&self.group_key, t);
283 if key.has_even_y() ^ self.group_key.has_even_y() {
284 cx_sign = -cx_sign;
285 }
286
287 key
288 } else {
289 if !self.group_key.has_even_y() {
290 cx_sign = -cx_sign;
291 }
292 self.group_key
293 }
294 } else {
295 self.group_key
296 };
297
298 let c = compute::challenge(&tweaked_public_key, aggregate_nonce, msg);
299 let mut cx = c * &self.private_key * compute::lambda(self.id, signers);
300
301 cx = cx_sign * cx;
302
303 let z = r + cx;
304
305 SignatureShare {
306 id: self.id,
307 z_i: z,
308 key_ids: vec![self.id],
309 }
310 }
311}
312
313#[derive(Clone, Debug, PartialEq)]
315pub struct Aggregator {
316 pub num_keys: u32,
318 pub threshold: u32,
320 pub poly: Vec<Point>,
322}
323
324impl Aggregator {
325 #[allow(non_snake_case)]
326 pub fn sign_with_tweak(
331 &mut self,
332 msg: &[u8],
333 nonces: &[PublicNonce],
334 sig_shares: &[SignatureShare],
335 tweak: Option<Scalar>,
336 ) -> Result<(Point, Signature), AggregatorError> {
337 if nonces.len() != sig_shares.len() {
338 return Err(AggregatorError::BadNonceLen(nonces.len(), sig_shares.len()));
339 }
340
341 let signers: Vec<u32> = sig_shares.iter().map(|ss| ss.id).collect();
342 let mut z = Scalar::zero();
343 let mut cx_sign = Scalar::one();
344 let aggregate_public_key = self.poly[0];
345 let tweaked_public_key = match tweak {
346 Some(t) if t != Scalar::zero() => {
347 let key = compute::tweaked_public_key_from_tweak(&aggregate_public_key, t);
348 if !key.has_even_y() {
349 cx_sign = -cx_sign;
350 }
351 key
352 }
353 _ => aggregate_public_key,
354 };
355 let (_Rs, R) = compute::intermediate(msg, aggregate_public_key, &signers, nonces);
356 let c = compute::challenge(&tweaked_public_key, &R, msg);
357
358 for sig_share in sig_shares {
359 z += sig_share.z_i;
360 }
361
362 if let Some(t) = tweak {
364 z += cx_sign * c * t;
365 }
366
367 let sig = Signature { R, z };
368
369 Ok((tweaked_public_key, sig))
370 }
371
372 #[allow(non_snake_case)]
373 pub fn check_signature_shares(
378 &mut self,
379 msg: &[u8],
380 nonces: &[PublicNonce],
381 sig_shares: &[SignatureShare],
382 tweak: Option<Scalar>,
383 ) -> AggregatorError {
384 if nonces.len() != sig_shares.len() {
385 return AggregatorError::BadNonceLen(nonces.len(), sig_shares.len());
386 }
387
388 let signers: Vec<u32> = sig_shares.iter().map(|ss| ss.id).collect();
389 let mut bad_party_keys = Vec::new();
390 let mut bad_party_sigs = Vec::new();
391 let aggregate_public_key = self.poly[0];
392 let tweaked_public_key = match tweak {
393 Some(t) if t != Scalar::zero() => {
394 compute::tweaked_public_key_from_tweak(&aggregate_public_key, t)
395 }
396 _ => aggregate_public_key,
397 };
398 let (Rs, R) = compute::intermediate(msg, aggregate_public_key, &signers, nonces);
399 let c = compute::challenge(&tweaked_public_key, &R, msg);
400 let mut r_sign = Scalar::one();
401 let mut cx_sign = Scalar::one();
402 if let Some(t) = tweak {
403 if !R.has_even_y() {
404 r_sign = -Scalar::one();
405 }
406 if t != Scalar::zero() {
407 if !tweaked_public_key.has_even_y() ^ !aggregate_public_key.has_even_y() {
408 cx_sign = -Scalar::one();
409 }
410 } else if !aggregate_public_key.has_even_y() {
411 cx_sign = -Scalar::one();
412 }
413 }
414
415 for i in 0..sig_shares.len() {
416 let id = compute::id(sig_shares[i].id);
417 let public_key = match compute::poly(&id, &self.poly) {
418 Ok(p) => p,
419 Err(_) => {
420 bad_party_keys.push(sig_shares[i].id);
421 Point::zero()
422 }
423 };
424
425 let z_i = sig_shares[i].z_i;
426
427 if z_i * G
428 != r_sign * Rs[i]
429 + cx_sign * (compute::lambda(sig_shares[i].id, &signers) * c * public_key)
430 {
431 bad_party_sigs.push(sig_shares[i].id);
432 }
433 }
434
435 if !bad_party_keys.is_empty() {
436 AggregatorError::BadPartyKeys(bad_party_keys)
437 } else if !bad_party_sigs.is_empty() {
438 AggregatorError::BadPartySigs(bad_party_sigs)
439 } else {
440 AggregatorError::BadGroupSig
441 }
442 }
443}
444
445impl traits::Aggregator for Aggregator {
446 fn new(num_keys: u32, threshold: u32) -> Self {
448 Self {
449 num_keys,
450 threshold,
451 poly: Default::default(),
452 }
453 }
454
455 fn init(&mut self, comms: &HashMap<u32, PolyCommitment>) -> Result<(), AggregatorError> {
457 let threshold = self.threshold.try_into()?;
458 let mut poly = Vec::with_capacity(threshold);
459
460 for i in 0..poly.capacity() {
461 poly.push(Point::zero());
462 for (_, p) in comms {
463 poly[i] += &p.poly[i];
464 }
465 }
466
467 self.poly = poly;
468
469 Ok(())
470 }
471
472 fn sign(
474 &mut self,
475 msg: &[u8],
476 nonces: &[PublicNonce],
477 sig_shares: &[SignatureShare],
478 _key_ids: &[u32],
479 ) -> Result<Signature, AggregatorError> {
480 let (key, sig) = self.sign_with_tweak(msg, nonces, sig_shares, None)?;
481
482 if sig.verify(&key, msg) {
483 Ok(sig)
484 } else {
485 Err(self.check_signature_shares(msg, nonces, sig_shares, None))
486 }
487 }
488
489 fn sign_schnorr(
491 &mut self,
492 msg: &[u8],
493 nonces: &[PublicNonce],
494 sig_shares: &[SignatureShare],
495 _key_ids: &[u32],
496 ) -> Result<SchnorrProof, AggregatorError> {
497 let tweak = Scalar::from(0);
498 let (key, sig) = self.sign_with_tweak(msg, nonces, sig_shares, Some(tweak))?;
499 let proof = SchnorrProof::new(&sig);
500
501 if proof.verify(&key.x(), msg) {
502 Ok(proof)
503 } else {
504 Err(self.check_signature_shares(msg, nonces, sig_shares, Some(tweak)))
505 }
506 }
507
508 fn sign_taproot(
510 &mut self,
511 msg: &[u8],
512 nonces: &[PublicNonce],
513 sig_shares: &[SignatureShare],
514 _key_ids: &[u32],
515 merkle_root: Option<[u8; 32]>,
516 ) -> Result<SchnorrProof, AggregatorError> {
517 let tweak = compute::tweak(&self.poly[0], merkle_root);
518 let (key, sig) = self.sign_with_tweak(msg, nonces, sig_shares, Some(tweak))?;
519 let proof = SchnorrProof::new(&sig);
520
521 if proof.verify(&key.x(), msg) {
522 Ok(proof)
523 } else {
524 Err(self.check_signature_shares(msg, nonces, sig_shares, Some(tweak)))
525 }
526 }
527}
528
529#[derive(Clone, Debug, Eq, PartialEq)]
530pub struct Signer {
532 id: u32,
534 num_keys: u32,
536 threshold: u32,
538 group_key: Point,
540 parties: Vec<Party>,
542}
543
544impl Signer {
545 pub fn new<RNG: RngCore + CryptoRng>(
547 id: u32,
548 key_ids: &[u32],
549 num_keys: u32,
550 threshold: u32,
551 rng: &mut RNG,
552 ) -> Self {
553 let parties = key_ids
554 .iter()
555 .map(|id| Party::new(*id, num_keys, threshold, rng))
556 .collect();
557 Signer {
558 id,
559 num_keys,
560 threshold,
561 group_key: Point::zero(),
562 parties,
563 }
564 }
565}
566
567impl traits::Signer for Signer {
568 fn new<RNG: RngCore + CryptoRng>(
569 party_id: u32,
570 key_ids: &[u32],
571 _num_signers: u32,
572 num_keys: u32,
573 threshold: u32,
574 rng: &mut RNG,
575 ) -> Self {
576 Signer::new(party_id, key_ids, num_keys, threshold, rng)
577 }
578
579 fn load(state: &traits::SignerState) -> Self {
581 let parties = state
582 .parties
583 .iter()
584 .map(|(id, ps)| Party::load(*id, state.num_keys, state.threshold, &state.group_key, ps))
585 .collect();
586
587 Self {
588 id: state.id,
589 num_keys: state.num_keys,
590 threshold: state.threshold,
591 group_key: state.group_key,
592 parties,
593 }
594 }
595
596 fn save(&self) -> traits::SignerState {
598 let mut key_ids = Vec::new();
599 let mut parties = Vec::new();
600
601 for party in &self.parties {
602 key_ids.push(party.id);
603 parties.push((party.id, party.save()));
604 }
605
606 traits::SignerState {
607 id: self.id,
608 key_ids,
609 num_keys: self.num_keys,
610 num_parties: self.num_keys,
611 threshold: self.threshold,
612 group_key: self.group_key,
613 parties,
614 }
615 }
616
617 fn get_id(&self) -> u32 {
618 self.id
619 }
620
621 fn get_key_ids(&self) -> Vec<u32> {
622 self.parties.iter().map(|p| p.id).collect()
623 }
624
625 fn get_num_parties(&self) -> u32 {
626 self.num_keys
627 }
628
629 fn get_poly_commitments<RNG: RngCore + CryptoRng>(
630 &self,
631 ctx: &[u8],
632 rng: &mut RNG,
633 ) -> Vec<PolyCommitment> {
634 let mut polys = Vec::new();
635 for party in &self.parties {
636 let comm = party.get_poly_commitment(ctx, rng);
637 if let Some(poly) = &comm {
638 polys.push(poly.clone());
639 }
640 }
641 polys
642 }
643
644 fn reset_polys<RNG: RngCore + CryptoRng>(&mut self, rng: &mut RNG) {
645 for party in self.parties.iter_mut() {
646 party.reset_poly(rng);
647 }
648 }
649
650 fn clear_polys(&mut self) {
651 for party in self.parties.iter_mut() {
652 party.clear_poly();
653 }
654 }
655
656 fn get_shares(&self) -> HashMap<u32, HashMap<u32, Scalar>> {
657 let mut shares = HashMap::new();
658 for party in &self.parties {
659 shares.insert(party.id, party.get_shares());
660 }
661 shares
662 }
663
664 fn compute_secrets(
665 &mut self,
666 private_shares: &HashMap<u32, HashMap<u32, Scalar>>,
667 polys: &HashMap<u32, PolyCommitment>,
668 ctx: &[u8],
669 ) -> Result<(), HashMap<u32, DkgError>> {
670 let mut dkg_errors = HashMap::new();
671 for party in &mut self.parties {
672 let mut key_shares = HashMap::with_capacity(polys.len());
674 for (party_id, signer_shares) in private_shares.iter() {
675 if let Some(share) = signer_shares.get(&party.id) {
676 key_shares.insert(*party_id, *share);
677 }
678 }
679 if let Err(e) = party.compute_secret(key_shares, polys, ctx) {
680 dkg_errors.insert(party.id, e);
681 }
682 self.group_key = party.group_key;
683 }
684
685 if dkg_errors.is_empty() {
686 Ok(())
687 } else {
688 Err(dkg_errors)
689 }
690 }
691
692 fn gen_nonces<RNG: RngCore + CryptoRng>(
693 &mut self,
694 secret_key: &Scalar,
695 rng: &mut RNG,
696 ) -> Vec<PublicNonce> {
697 self.parties
698 .iter_mut()
699 .map(|p| p.gen_nonce(secret_key, rng))
700 .collect()
701 }
702
703 fn compute_intermediate(
704 &self,
705 msg: &[u8],
706 _signer_ids: &[u32],
707 key_ids: &[u32],
708 nonces: &[PublicNonce],
709 ) -> (Vec<Point>, Point) {
710 compute::intermediate(msg, self.group_key, key_ids, nonces)
711 }
712
713 fn validate_party_id(
714 signer_id: u32,
715 party_id: u32,
716 signer_key_ids: &HashMap<u32, HashSet<u32>>,
717 ) -> bool {
718 match signer_key_ids.get(&signer_id) {
719 Some(key_ids) => key_ids.contains(&party_id),
720 None => false,
721 }
722 }
723
724 fn sign(
725 &self,
726 msg: &[u8],
727 _signer_ids: &[u32],
728 key_ids: &[u32],
729 nonces: &[PublicNonce],
730 ) -> Vec<SignatureShare> {
731 let aggregate_nonce =
732 compute::aggregate_nonce(msg, self.group_key, key_ids, nonces).unwrap();
733 self.parties
734 .iter()
735 .map(|p| p.sign_precomputed(msg, key_ids, nonces, &aggregate_nonce))
736 .collect()
737 }
738
739 fn sign_taproot(
740 &self,
741 msg: &[u8],
742 _signer_ids: &[u32],
743 key_ids: &[u32],
744 nonces: &[PublicNonce],
745 merkle_root: Option<[u8; 32]>,
746 ) -> Vec<SignatureShare> {
747 let aggregate_nonce =
748 compute::aggregate_nonce(msg, self.group_key, key_ids, nonces).unwrap();
749 let tweak = compute::tweak(&self.parties[0].group_key, merkle_root);
750 self.parties
751 .iter()
752 .map(|p| {
753 p.sign_precomputed_with_tweak(msg, key_ids, nonces, &aggregate_nonce, Some(tweak))
754 })
755 .collect()
756 }
757
758 fn sign_schnorr(
759 &self,
760 msg: &[u8],
761 _signer_ids: &[u32],
762 key_ids: &[u32],
763 nonces: &[PublicNonce],
764 ) -> Vec<SignatureShare> {
765 let aggregate_nonce =
766 compute::aggregate_nonce(msg, self.group_key, key_ids, nonces).unwrap();
767 self.parties
768 .iter()
769 .map(|p| {
770 p.sign_precomputed_with_tweak(
771 msg,
772 key_ids,
773 nonces,
774 &aggregate_nonce,
775 Some(Scalar::from(0)),
776 )
777 })
778 .collect()
779 }
780}
781
782#[cfg(any(test, feature = "testing"))]
784pub mod test_helpers {
785 use super::Scalar;
786 use crate::common::{PolyCommitment, PublicNonce};
787 use crate::errors::DkgError;
788 use crate::traits::Signer;
789 use crate::v1;
790
791 use hashbrown::HashMap;
792 use rand_core::{CryptoRng, RngCore};
793
794 pub fn dkg<RNG: RngCore + CryptoRng>(
796 signers: &mut [v1::Signer],
797 rng: &mut RNG,
798 ) -> Result<HashMap<u32, PolyCommitment>, HashMap<u32, DkgError>> {
799 let ctx = 0u64.to_be_bytes();
800 let comms: HashMap<u32, PolyCommitment> = signers
801 .iter()
802 .flat_map(|s| s.get_poly_commitments(&ctx, rng))
803 .map(|comm| (comm.id.id.get_u32(), comm))
804 .collect();
805
806 let mut private_shares = HashMap::new();
807 for signer in signers.iter() {
808 for (signer_id, signer_shares) in signer.get_shares() {
809 private_shares.insert(signer_id, signer_shares);
810 }
811 }
812
813 let mut secret_errors = HashMap::new();
814 for signer in signers.iter_mut() {
815 if let Err(signer_secret_errors) = signer.compute_secrets(&private_shares, &comms, &ctx)
816 {
817 secret_errors.extend(signer_secret_errors);
818 }
819 }
820
821 if secret_errors.is_empty() {
822 Ok(comms)
823 } else {
824 Err(secret_errors)
825 }
826 }
827
828 pub fn sign<RNG: RngCore + CryptoRng>(
830 msg: &[u8],
831 signers: &mut [v1::Signer],
832 rng: &mut RNG,
833 ) -> (Vec<PublicNonce>, Vec<v1::SignatureShare>) {
834 let secret_key = Scalar::random(rng);
835 let ids: Vec<u32> = signers.iter().flat_map(|s| s.get_key_ids()).collect();
836 let nonces: Vec<PublicNonce> = signers
837 .iter_mut()
838 .flat_map(|s| s.gen_nonces(&secret_key, rng))
839 .collect();
840 let shares = signers
841 .iter()
842 .flat_map(|s| s.sign(msg, &ids, &ids, &nonces))
843 .collect();
844
845 (nonces, shares)
846 }
847}
848
849#[cfg(test)]
850mod tests {
851 use super::Scalar;
852 use crate::traits;
853 use crate::traits::test_helpers::run_compute_secrets_missing_private_shares;
854 use crate::traits::{Aggregator, Signer};
855 use crate::util::create_rng;
856 use crate::v1;
857
858 use hashbrown::{HashMap, HashSet};
859 use num_traits::Zero;
860
861 #[test]
862 fn signer_new() {
863 let mut rng = create_rng();
864 let id = 1;
865 let key_ids = [1, 2, 3];
866 let n: u32 = 10;
867 let t: u32 = 7;
868
869 let signer = v1::Signer::new(id, &key_ids, n, t, &mut rng);
870
871 assert_eq!(signer.parties.len(), key_ids.len());
872 }
873
874 #[test]
875 fn signer_gen_nonces() {
876 let mut rng = create_rng();
877 let secret_key = Scalar::random(&mut rng);
878 let id = 1;
879 let key_ids = [1, 2, 3];
880 let n: u32 = 10;
881 let t: u32 = 7;
882
883 let mut signer = v1::Signer::new(id, &key_ids, n, t, &mut rng);
884
885 for party in &signer.parties {
886 assert!(!party.nonce.is_zero());
887 assert!(party.nonce.is_valid());
888 }
889
890 let nonces = signer.gen_nonces(&secret_key, &mut rng);
891
892 assert_eq!(nonces.len(), key_ids.len());
893
894 for party in &signer.parties {
895 assert!(!party.nonce.is_zero());
896 assert!(party.nonce.is_valid());
897 }
898 }
899
900 #[test]
901 fn signer_save_load() {
902 let mut rng = create_rng();
903 let id = 1;
904 let key_ids = [1, 2, 3];
905 let n: u32 = 10;
906 let t: u32 = 7;
907
908 let signer = v1::Signer::new(id, &key_ids, n, t, &mut rng);
909
910 let state = signer.save();
911 let loaded = v1::Signer::load(&state);
912
913 assert_eq!(signer, loaded);
914 }
915
916 #[test]
917 fn clear_polys() {
918 let ctx = 0u64.to_be_bytes();
919 let mut rng = create_rng();
920 let id = 1;
921 let key_ids = [1, 2, 3];
922 let n: u32 = 10;
923 let t: u32 = 7;
924
925 let mut signer = v1::Signer::new(id, &key_ids, n, t, &mut rng);
926
927 assert_eq!(
928 signer.get_poly_commitments(&ctx, &mut rng).len(),
929 key_ids.len()
930 );
931 assert_eq!(signer.get_shares().len(), key_ids.len());
932 for (_id, shares) in signer.get_shares() {
933 assert_eq!(shares.len(), n.try_into().unwrap());
934 }
935
936 signer.clear_polys();
937
938 assert_eq!(signer.get_poly_commitments(&ctx, &mut rng).len(), 0);
939 assert_eq!(signer.get_shares().len(), 3);
940 for (_id, shares) in signer.get_shares() {
941 assert_eq!(shares.len(), 0);
942 }
943 }
944
945 #[allow(non_snake_case)]
946 #[test]
947 fn aggregator_sign() {
948 let mut rng = create_rng();
949 let msg = "It was many and many a year ago".as_bytes();
950 let N: u32 = 10;
951 let T: u32 = 7;
952 let signer_ids: Vec<Vec<u32>> = [
953 [1, 2, 3].to_vec(),
954 [4, 5].to_vec(),
955 [6, 7, 8].to_vec(),
956 [9, 10].to_vec(),
957 ]
958 .to_vec();
959 let mut signers: Vec<v1::Signer> = signer_ids
960 .iter()
961 .enumerate()
962 .map(|(id, ids)| v1::Signer::new(id.try_into().unwrap(), ids, N, T, &mut rng))
963 .collect();
964
965 let comms = match traits::test_helpers::dkg(&mut signers, &mut rng) {
966 Ok(comms) => comms,
967 Err(secret_errors) => {
968 panic!("Got secret errors from DKG: {secret_errors:?}");
969 }
970 };
971
972 {
974 let mut signers = [signers[0].clone(), signers[1].clone(), signers[3].clone()].to_vec();
975 let mut sig_agg = v1::Aggregator::new(N, T);
976 sig_agg.init(&comms).expect("aggregator init failed");
977
978 let (nonces, sig_shares) = v1::test_helpers::sign(msg, &mut signers, &mut rng);
979 if let Err(e) = sig_agg.sign(msg, &nonces, &sig_shares, &[]) {
980 panic!("Aggregator sign failed: {e:?}");
981 }
982 }
983 }
984
985 #[allow(non_snake_case)]
986 #[test]
987 pub fn run_compute_secrets_missing_shares() {
989 run_compute_secrets_missing_private_shares::<v1::Signer>()
990 }
991
992 #[allow(non_snake_case)]
993 #[test]
994 pub fn bad_polynomial_length() {
996 let gt = |t| t + 1;
997 let lt = |t| t - 1;
998 traits::test_helpers::bad_polynomial_length::<v1::Signer, _>(gt);
999 traits::test_helpers::bad_polynomial_length::<v1::Signer, _>(lt);
1000 }
1001
1002 #[test]
1003 pub fn bad_polynomial_commitment() {
1005 traits::test_helpers::bad_polynomial_commitment::<v1::Signer>();
1006 }
1007
1008 #[test]
1009 fn validate_party_id() {
1011 let mut signer_key_ids = HashMap::new();
1012 let mut key_ids = HashSet::new();
1013
1014 key_ids.insert(1);
1015 signer_key_ids.insert(0, key_ids);
1016
1017 assert!(v1::Signer::validate_party_id(0, 1, &signer_key_ids));
1018 assert!(!v1::Signer::validate_party_id(0, 0, &signer_key_ids));
1019 }
1020}