Skip to main content

wsts/state_machine/coordinator/
mod.rs

1use crate::{
2    common::{PolyCommitment, Signature, SignatureShare},
3    curve::{
4        ecdsa,
5        point::{Error as PointError, Point},
6        scalar::Scalar,
7    },
8    errors::AggregatorError,
9    net::{DkgEnd, DkgPrivateShares, DkgPublicShares, NonceResponse, Packet, SignatureType},
10    state_machine::{DkgFailure, OperationResult, PublicKeys, StateMachine},
11    taproot::SchnorrProof,
12};
13use core::{cmp::PartialEq, fmt::Debug, num::TryFromIntError};
14use hashbrown::{HashMap, HashSet};
15use std::{
16    collections::BTreeMap,
17    fmt,
18    time::{Duration, Instant},
19};
20
21#[derive(Clone, Default, Debug, PartialEq)]
22/// Coordinator states
23pub enum State {
24    /// The coordinator is idle
25    #[default]
26    Idle,
27    /// The coordinator is asking signers to send public shares
28    DkgPublicDistribute,
29    /// The coordinator is gathering public shares
30    DkgPublicGather,
31    /// The coordinator is notifying signers that all public shares are done
32    DkgPublicSharesDoneDistribute,
33    /// The coordinator is gathering acknowledgments of DkgPublicSharesDone
34    DkgPublicSharesDoneGather,
35    /// The coordinator is asking signers to send private shares
36    DkgPrivateDistribute,
37    /// The coordinator is gathering private shares
38    DkgPrivateGather,
39    /// The coordinator is notifying signers that all private shares are done
40    DkgPrivateSharesDoneDistribute,
41    /// The coordinator is gathering acknowledgments of DkgPrivateSharesDone
42    DkgPrivateSharesDoneGather,
43    /// The coordinator is asking signers to compute shares and send end
44    DkgEndDistribute,
45    /// The coordinator is gathering DKG End messages
46    DkgEndGather,
47    /// The coordinator is requesting nonces
48    NonceRequest(SignatureType),
49    /// The coordinator is gathering nonces
50    NonceGather(SignatureType),
51    /// The coordinator is requesting signature shares
52    SigShareRequest(SignatureType),
53    /// The coordinator is gathering signature shares
54    SigShareGather(SignatureType),
55}
56
57#[derive(thiserror::Error, Clone, Debug)]
58#[allow(clippy::large_enum_variant)]
59/// The error type for the coordinator
60pub enum Error {
61    /// A bad state change was made
62    #[error("Bad State Change: {0}")]
63    BadStateChange(String),
64    /// A bad dkg_id in received message
65    #[error("Bad dkg_id: got {0} expected {1}")]
66    BadDkgId(u64, u64),
67    /// A bad sign_id in received message
68    #[error("Bad sign_id: got {0} expected {1}")]
69    BadSignId(u64, u64),
70    /// A bad sign_iter_id in received message
71    #[error("Bad sign_iter_id: got {0} expected {1}")]
72    BadSignIterId(u64, u64),
73    /// A malicious signer sent the received message
74    #[error("Malicious signer {0}")]
75    MaliciousSigner(u32),
76    /// SignatureAggregator error
77    #[error("Aggregator: {0}")]
78    Aggregator(AggregatorError),
79    /// Schnorr proof failed to verify
80    #[error("Schnorr Proof failed to verify")]
81    SchnorrProofFailed,
82    /// No aggregate public key set
83    #[error("No aggregate public key set")]
84    MissingAggregatePublicKey,
85    /// No schnorr proof set
86    #[error("No schnorr proof set")]
87    MissingSchnorrProof,
88    /// No signature set
89    #[error("No signature set")]
90    MissingSignature,
91    /// Missing message response information for a signing round
92    #[error("Missing message nonce information")]
93    MissingMessageNonceInfo,
94    /// Missing public key for signer
95    #[error("Missing public key for signer {0}")]
96    MissingPublicKeyForSigner(u32),
97    /// Missing key IDs for signer
98    #[error("Missing key IDs for signer {0}")]
99    MissingKeyIDsForSigner(u32),
100    /// Bad key IDs for signer
101    #[error("Bad key IDs for signer {0}")]
102    BadKeyIDsForSigner(u32),
103    /// DKG failure from signers, with a map of signer_id to reported errors and new malicious signer_ids
104    #[error("DKG failure from signers")]
105    DkgFailure {
106        /// failures reported by signers during DkgEnd
107        reported_failures: HashMap<u32, DkgFailure>,
108        /// signers who were discovered to be malicious during this DKG round
109        malicious_signers: HashSet<u32>,
110    },
111    /// Aggregate key does not match supplied party polynomial
112    #[error(
113        "Aggregate key and computed key from party polynomials mismatch: got {0}, expected {1}"
114    )]
115    AggregateKeyPolynomialMismatch(Point, Point),
116    /// Supplied party polynomial contained duplicate party IDs
117    #[error("Supplied party polynomials contained a duplicate party ID")]
118    DuplicatePartyId,
119    #[error("Missing coordinator public key")]
120    /// Missing coordinator public key"
121    MissingCoordinatorPublicKey,
122    #[error("A packet had an invalid signature")]
123    /// A packet had an invalid signature
124    InvalidPacketSignature,
125    #[error("No public shares for signer {0}")]
126    /// No public shares for the signer who sent private shares
127    NoPublicSharesForSigner(u32),
128    #[error("A curve point error {0}")]
129    /// A curve point error
130    Point(#[from] PointError),
131    #[error("integer conversion error")]
132    /// An error during integer conversion operations
133    TryFromInt(#[from] TryFromIntError),
134}
135
136impl From<AggregatorError> for Error {
137    fn from(err: AggregatorError) -> Self {
138        Error::Aggregator(err)
139    }
140}
141
142/// Config fields common to all Coordinators
143#[derive(Default, Clone, PartialEq)]
144pub struct Config {
145    /// total number of signers
146    pub num_signers: u32,
147    /// total number of keys
148    pub num_keys: u32,
149    /// threshold of keys needed to form a valid signature
150    pub threshold: u32,
151    /// threshold of keys needed to complete DKG (must be >= threshold)
152    pub dkg_threshold: u32,
153    /// threshold of keys needed to start a signing round (must be >= threshold)
154    pub sign_threshold: u32,
155    /// private key used to sign network messages
156    pub message_private_key: Scalar,
157    /// timeout to gather DkgPublicShares messages
158    pub dkg_public_timeout: Option<Duration>,
159    /// timeout to gather DkgPrivateShares messages
160    pub dkg_private_timeout: Option<Duration>,
161    /// timeout to gather DkgEnd messages
162    pub dkg_end_timeout: Option<Duration>,
163    /// timeout to gather nonces
164    pub nonce_timeout: Option<Duration>,
165    /// timeout to gather signature shares
166    pub sign_timeout: Option<Duration>,
167    /// the public keys and key_ids for all signers
168    pub public_keys: PublicKeys,
169    /// whether to verify the signature on Packets
170    pub verify_packet_sigs: bool,
171}
172
173impl fmt::Debug for Config {
174    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
175        f.debug_struct("Config")
176            .field("num_signers", &self.num_signers)
177            .field("num_keys", &self.num_keys)
178            .field("dkg_threshold", &self.dkg_threshold)
179            .field("dkg_public_timeout", &self.dkg_public_timeout)
180            .field("dkg_private_timeout", &self.dkg_private_timeout)
181            .field("dkg_end_timeout", &self.dkg_end_timeout)
182            .field("nonce_timeout", &self.nonce_timeout)
183            .field("sign_timeout", &self.sign_timeout)
184            .field("signer_key_ids", &self.public_keys.signer_key_ids)
185            .field("signer_public_keys", &self.public_keys.signers)
186            .field("verify_packet_sigs", &self.verify_packet_sigs)
187            .finish_non_exhaustive()
188    }
189}
190
191impl Config {
192    /// Create a new config object with no timeouts
193    /// dkg_threshold defaults to num_keys
194    /// sign_threshold defaults to threshold, and must be >= threshold
195    pub fn new(
196        num_signers: u32,
197        num_keys: u32,
198        threshold: u32,
199        message_private_key: Scalar,
200    ) -> Self {
201        Config {
202            num_signers,
203            num_keys,
204            threshold,
205            dkg_threshold: num_keys,
206            sign_threshold: threshold,
207            message_private_key,
208            dkg_public_timeout: None,
209            dkg_private_timeout: None,
210            dkg_end_timeout: None,
211            nonce_timeout: None,
212            sign_timeout: None,
213            public_keys: Default::default(),
214            verify_packet_sigs: true,
215        }
216    }
217
218    #[allow(clippy::too_many_arguments)]
219    /// Create a new config object with the passed timeouts
220    /// sign_threshold defaults to threshold, and must be >= threshold
221    pub fn with_timeouts(
222        num_signers: u32,
223        num_keys: u32,
224        threshold: u32,
225        dkg_threshold: u32,
226        message_private_key: Scalar,
227        dkg_public_timeout: Option<Duration>,
228        dkg_private_timeout: Option<Duration>,
229        dkg_end_timeout: Option<Duration>,
230        nonce_timeout: Option<Duration>,
231        sign_timeout: Option<Duration>,
232        public_keys: PublicKeys,
233    ) -> Self {
234        Config {
235            num_signers,
236            num_keys,
237            threshold,
238            dkg_threshold,
239            sign_threshold: threshold,
240            message_private_key,
241            dkg_public_timeout,
242            dkg_private_timeout,
243            dkg_end_timeout,
244            nonce_timeout,
245            sign_timeout,
246            public_keys,
247            verify_packet_sigs: true,
248        }
249    }
250}
251
252#[derive(Clone, Debug, Default, PartialEq)]
253/// The info for a sign round over specific message bytes
254pub struct SignRoundInfo {
255    /// the nonce response of a signer id
256    pub public_nonces: BTreeMap<u32, NonceResponse>,
257    /// which key_ids we've received nonces for this iteration
258    pub nonce_recv_key_ids: HashSet<u32>,
259    /// which key_ids we're received sig shares for this iteration
260    pub sign_recv_key_ids: HashSet<u32>,
261    /// which signer_ids we're expecting sig shares from this iteration
262    pub sign_wait_signer_ids: HashSet<u32>,
263}
264
265/// The saved state required to reconstruct a coordinator
266#[derive(Default, Clone, Debug, PartialEq)]
267pub struct SavedState {
268    /// common config fields
269    pub config: Config,
270    /// current DKG round ID
271    pub current_dkg_id: u64,
272    /// current signing round ID
273    pub current_sign_id: u64,
274    /// current signing iteration ID
275    pub current_sign_iter_id: u64,
276    /// map of DkgPublicShares indexed by signer ID
277    pub dkg_public_shares: BTreeMap<u32, DkgPublicShares>,
278    /// map of DkgPrivateShares indexed by signer ID
279    pub dkg_private_shares: BTreeMap<u32, DkgPrivateShares>,
280    /// map of DkgEnd indexed by signer ID
281    pub dkg_end_messages: BTreeMap<u32, DkgEnd>,
282    /// the current view of a successful DKG's participants' commitments
283    pub party_polynomials: HashMap<u32, PolyCommitment>,
284    /// map of SignatureShare indexed by signer ID
285    pub signature_shares: BTreeMap<u32, Vec<SignatureShare>>,
286    /// map of SignRoundInfo indexed by message bytes
287    pub message_nonces: BTreeMap<Vec<u8>, SignRoundInfo>,
288    /// aggregate public key
289    pub aggregate_public_key: Option<Point>,
290    /// current Signature
291    pub signature: Option<Signature>,
292    /// current SchnorrProof
293    pub schnorr_proof: Option<SchnorrProof>,
294    /// which signers we're currently waiting on for DKG
295    pub dkg_wait_signer_ids: HashSet<u32>,
296    /// the bytes that we're signing
297    pub message: Vec<u8>,
298    /// current state of the state machine
299    pub state: State,
300    /// start time for NonceRequest
301    pub nonce_start: Option<Instant>,
302    /// start time for DkgBegin
303    pub dkg_public_start: Option<Instant>,
304    /// start time for DkgPrivateBegin
305    pub dkg_private_start: Option<Instant>,
306    /// start time for DkgEndBegin
307    pub dkg_end_start: Option<Instant>,
308    /// start time for SignatureShareRequest
309    pub sign_start: Option<Instant>,
310    /// set of malicious signers during signing round
311    pub malicious_signer_ids: HashSet<u32>,
312    /// set of malicious signers during dkg round
313    pub malicious_dkg_signer_ids: HashSet<u32>,
314    /// coordinator public key
315    pub coordinator_public_key: Option<ecdsa::PublicKey>,
316}
317
318/// Coordinator trait for handling the coordination of DKG and sign messages
319pub trait Coordinator: Clone + Debug + PartialEq + StateMachine<State, Error> {
320    /// Create a new Coordinator
321    fn new(config: Config) -> Self;
322
323    /// Load a coordinator from the previously saved `state`
324    fn load(state: &SavedState) -> Self;
325
326    /// Save the state required to reconstruct the coordinator
327    fn save(&self) -> SavedState;
328
329    /// Retrieve the config
330    fn get_config(&self) -> Config;
331
332    /// Set the coordinator public key
333    fn set_coordinator_public_key(&mut self, key: Option<ecdsa::PublicKey>);
334
335    /// Initialize Coordinator from partial saved state
336    fn set_key_and_party_polynomials(
337        &mut self,
338        aggregate_key: Point,
339        party_polynomials: Vec<(u32, PolyCommitment)>,
340    ) -> Result<(), Error>;
341
342    /// Process any timeouts, and if none of them fire then process the passed packet
343    /// If a timeout does fire, then the coordinator state has changed; this means the
344    /// packet is now stale and must be dropped
345    fn process(
346        &mut self,
347        packet: &Packet,
348    ) -> Result<(Option<Packet>, Option<OperationResult>), Error>;
349
350    /// Retrieve the aggregate public key
351    fn get_aggregate_public_key(&self) -> Option<Point>;
352
353    /// Set the aggregate public key
354    fn set_aggregate_public_key(&mut self, aggregate_public_key: Option<Point>);
355
356    /// Retrieve the current message bytes being signed
357    fn get_message(&self) -> Vec<u8>;
358
359    /// Retrieve the current state
360    fn get_state(&self) -> State;
361
362    /// Trigger a DKG round, with an optional `dkg_id`
363    fn start_dkg_round(&mut self, dkg_id: Option<u64>) -> Result<Packet, Error>;
364
365    /// Trigger a signing round
366    fn start_signing_round(
367        &mut self,
368        message: &[u8],
369        signature_type: SignatureType,
370        sign_id: Option<u64>,
371    ) -> Result<Packet, Error>;
372
373    /// Reset internal state
374    fn reset(&mut self);
375}
376
377/// The coordinator for the FROST algorithm
378pub mod frost;
379
380/// The coordinator for the FIRE algorithm
381pub mod fire;
382
383#[allow(missing_docs)]
384#[cfg(any(test, feature = "testing"))]
385pub mod test {
386    use hashbrown::{HashMap, HashSet};
387    use rand_core::OsRng;
388    use std::{sync::Once, time::Duration};
389    use tracing_subscriber::{fmt, prelude::*, EnvFilter};
390
391    use crate::{
392        common::SignatureShare,
393        compute,
394        curve::{ecdsa, point::Point, point::G, scalar::Scalar},
395        errors::AggregatorError,
396        net::{DkgFailure, Message, Packet, SignatureShareResponse, SignatureType},
397        schnorr,
398        state_machine::{
399            coordinator::{Config, Coordinator as CoordinatorTrait, Error, State},
400            signer::{Error as SignerError, Signer},
401            DkgError, Error as StateMachineError, OperationResult, PublicKeys, SignError,
402            StateMachine,
403        },
404        traits::Signer as SignerTrait,
405        util::create_rng,
406    };
407
408    static INIT: Once = Once::new();
409
410    pub fn new_coordinator<Coordinator: CoordinatorTrait>() {
411        let mut rng = create_rng();
412        let config = Config::new(10, 40, 28, Scalar::random(&mut rng));
413        let coordinator = Coordinator::new(config.clone());
414
415        assert_eq!(coordinator.get_config().num_signers, config.num_signers);
416        assert_eq!(coordinator.get_config().num_keys, config.num_keys);
417        assert_eq!(coordinator.get_config().threshold, config.threshold);
418        assert_eq!(
419            coordinator.get_config().message_private_key,
420            config.message_private_key
421        );
422        assert_eq!(coordinator.get_state(), State::Idle);
423    }
424
425    pub fn coordinator_state_machine<Coordinator: CoordinatorTrait + StateMachine<State, Error>>() {
426        let mut rng = create_rng();
427        let config = Config::new(3, 3, 3, Scalar::random(&mut rng));
428        let mut coordinator = Coordinator::new(config);
429        assert!(coordinator.can_move_to(&State::DkgPublicDistribute).is_ok());
430        assert!(coordinator.can_move_to(&State::DkgPublicGather).is_err());
431        assert!(coordinator
432            .can_move_to(&State::DkgPrivateDistribute)
433            .is_err());
434        assert!(coordinator.can_move_to(&State::DkgPrivateGather).is_err());
435        assert!(coordinator.can_move_to(&State::DkgEndDistribute).is_err());
436        assert!(coordinator.can_move_to(&State::DkgEndGather).is_err());
437        assert!(coordinator.can_move_to(&State::Idle).is_ok());
438
439        coordinator.move_to(State::DkgPublicDistribute).unwrap();
440        assert!(coordinator
441            .can_move_to(&State::DkgPublicDistribute)
442            .is_err());
443        assert!(coordinator.can_move_to(&State::DkgPublicGather).is_ok());
444        assert!(coordinator
445            .can_move_to(&State::DkgPrivateDistribute)
446            .is_err());
447        assert!(coordinator.can_move_to(&State::DkgPrivateGather).is_err());
448        assert!(coordinator.can_move_to(&State::DkgEndDistribute).is_err());
449        assert!(coordinator.can_move_to(&State::DkgEndGather).is_err());
450        assert!(coordinator.can_move_to(&State::Idle).is_ok());
451
452        coordinator.move_to(State::DkgPublicGather).unwrap();
453        assert!(coordinator
454            .can_move_to(&State::DkgPublicDistribute)
455            .is_err());
456        assert!(coordinator.can_move_to(&State::DkgPublicGather).is_ok());
457        assert!(coordinator
458            .can_move_to(&State::DkgPublicSharesDoneDistribute)
459            .is_ok());
460        assert!(coordinator
461            .can_move_to(&State::DkgPrivateDistribute)
462            .is_err());
463        assert!(coordinator.can_move_to(&State::DkgPrivateGather).is_err());
464        assert!(coordinator.can_move_to(&State::DkgEndDistribute).is_err());
465        assert!(coordinator.can_move_to(&State::DkgEndGather).is_err());
466        assert!(coordinator.can_move_to(&State::Idle).is_ok());
467
468        coordinator
469            .move_to(State::DkgPublicSharesDoneDistribute)
470            .unwrap();
471        assert!(coordinator
472            .can_move_to(&State::DkgPublicSharesDoneGather)
473            .is_ok());
474        assert!(coordinator
475            .can_move_to(&State::DkgPrivateDistribute)
476            .is_err());
477
478        coordinator
479            .move_to(State::DkgPublicSharesDoneGather)
480            .unwrap();
481        assert!(coordinator
482            .can_move_to(&State::DkgPublicSharesDoneGather)
483            .is_ok());
484        assert!(coordinator
485            .can_move_to(&State::DkgPrivateDistribute)
486            .is_ok());
487
488        coordinator.move_to(State::DkgPrivateDistribute).unwrap();
489        assert!(coordinator
490            .can_move_to(&State::DkgPublicDistribute)
491            .is_err());
492        assert!(coordinator.can_move_to(&State::DkgPublicGather).is_err());
493        assert!(coordinator
494            .can_move_to(&State::DkgPrivateDistribute)
495            .is_err());
496        assert!(coordinator.can_move_to(&State::DkgPrivateGather).is_ok());
497        assert!(coordinator.can_move_to(&State::DkgEndDistribute).is_err());
498        assert!(coordinator.can_move_to(&State::DkgEndGather).is_err());
499        assert!(coordinator.can_move_to(&State::Idle).is_ok());
500
501        coordinator.move_to(State::DkgPrivateGather).unwrap();
502        assert!(coordinator
503            .can_move_to(&State::DkgPublicDistribute)
504            .is_err());
505        assert!(coordinator.can_move_to(&State::DkgPublicGather).is_err());
506        assert!(coordinator
507            .can_move_to(&State::DkgPrivateDistribute)
508            .is_err());
509        assert!(coordinator.can_move_to(&State::DkgPrivateGather).is_ok());
510        assert!(coordinator
511            .can_move_to(&State::DkgPrivateSharesDoneDistribute)
512            .is_ok());
513        assert!(coordinator.can_move_to(&State::DkgEndDistribute).is_err());
514        assert!(coordinator.can_move_to(&State::DkgEndGather).is_err());
515        assert!(coordinator.can_move_to(&State::Idle).is_ok());
516
517        coordinator
518            .move_to(State::DkgPrivateSharesDoneDistribute)
519            .unwrap();
520        assert!(coordinator
521            .can_move_to(&State::DkgPrivateSharesDoneGather)
522            .is_ok());
523        assert!(coordinator.can_move_to(&State::DkgEndDistribute).is_err());
524
525        coordinator
526            .move_to(State::DkgPrivateSharesDoneGather)
527            .unwrap();
528        assert!(coordinator
529            .can_move_to(&State::DkgPrivateSharesDoneGather)
530            .is_ok());
531        assert!(coordinator.can_move_to(&State::DkgEndDistribute).is_ok());
532
533        coordinator.move_to(State::DkgEndDistribute).unwrap();
534        assert!(coordinator.can_move_to(&State::DkgEndGather).is_ok());
535
536        coordinator.move_to(State::DkgEndGather).unwrap();
537        assert!(coordinator.can_move_to(&State::Idle).is_ok());
538    }
539
540    pub fn start_dkg_round<Coordinator: CoordinatorTrait>(dkg_id: Option<u64>) {
541        let mut rng = create_rng();
542        let config = Config::new(10, 40, 28, Scalar::random(&mut rng));
543        let mut coordinator = Coordinator::new(config);
544        let result = coordinator.start_dkg_round(dkg_id);
545
546        assert!(result.is_ok());
547
548        if let Message::DkgBegin(dkg_begin) = result.unwrap().msg {
549            if let Some(id) = dkg_id {
550                assert_eq!(
551                    dkg_begin.dkg_id, id,
552                    "Bad dkg_id {} expected {id}",
553                    dkg_begin.dkg_id
554                );
555            } else {
556                assert_eq!(
557                    dkg_begin.dkg_id, 1,
558                    "Bad dkg_id {} expected 1",
559                    dkg_begin.dkg_id
560                );
561            }
562        } else {
563            panic!("coordinator.start_dkg_round didn't return DkgBegin");
564        };
565
566        assert_eq!(coordinator.get_state(), State::DkgPublicGather);
567    }
568
569    pub fn start_signing_round<Coordinator: CoordinatorTrait>(sign_id: Option<u64>) {
570        let mut rng = create_rng();
571        let config = Config::new(10, 40, 28, Scalar::random(&mut rng));
572        let mut coordinator = Coordinator::new(config);
573
574        coordinator.set_aggregate_public_key(Some(Point::new()));
575
576        let msg = "It was many and many a year ago, in a kingdom by the sea"
577            .as_bytes()
578            .to_vec();
579        let signature_type = SignatureType::Schnorr;
580        let result = coordinator.start_signing_round(&msg, signature_type, sign_id);
581
582        assert!(result.is_ok());
583
584        if let Message::NonceRequest(nonce_request) = result.unwrap().msg {
585            if let Some(id) = sign_id {
586                assert_eq!(
587                    nonce_request.sign_id, id,
588                    "Bad dkg_id {} expected {id}",
589                    nonce_request.sign_id
590                );
591            } else {
592                assert_eq!(
593                    nonce_request.sign_id, 1,
594                    "Bad dkg_id {} expected 1",
595                    nonce_request.sign_id
596                );
597            }
598        } else {
599            panic!("coordinator.start_signing_round didn't return NonceRequest");
600        };
601
602        assert_eq!(coordinator.get_state(), State::NonceGather(signature_type));
603    }
604
605    /// Set up coordinators and signers with packet signature verification off.
606    pub fn setup<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
607        num_signers: u32,
608        keys_per_signer: u32,
609    ) -> (Vec<Coordinator>, Vec<Signer<SignerType>>) {
610        setup_with_timeouts::<Coordinator, SignerType>(
611            num_signers,
612            keys_per_signer,
613            None,
614            None,
615            None,
616            None,
617            None,
618            false,
619        )
620    }
621
622    /// Set up coordinators and signers with packet signature verification on.
623    ///
624    /// Verification needs a coordinator public key as well, so callers still
625    /// have to set that; this only decides the flag at construction time, so
626    /// that no mutable accessor is needed afterwards.
627    pub fn setup_verifying<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
628        num_signers: u32,
629        keys_per_signer: u32,
630    ) -> (Vec<Coordinator>, Vec<Signer<SignerType>>) {
631        setup_with_timeouts::<Coordinator, SignerType>(
632            num_signers,
633            keys_per_signer,
634            None,
635            None,
636            None,
637            None,
638            None,
639            true,
640        )
641    }
642
643    // Eight positional parameters, five of them bare Option<Duration>. The
644    // right fix is to group the timeouts into a struct, but that churns an
645    // exported harness signature for its own reasons, so it is left as a
646    // follow-up rather than bundled in here.
647    #[allow(clippy::too_many_arguments)]
648    pub fn setup_with_timeouts<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
649        num_signers: u32,
650        keys_per_signer: u32,
651        dkg_public_timeout: Option<Duration>,
652        dkg_private_timeout: Option<Duration>,
653        dkg_end_timeout: Option<Duration>,
654        nonce_timeout: Option<Duration>,
655        sign_timeout: Option<Duration>,
656        verify_packet_sigs: bool,
657    ) -> (Vec<Coordinator>, Vec<Signer<SignerType>>) {
658        INIT.call_once(|| {
659            tracing_subscriber::registry()
660                .with(fmt::layer())
661                .with(EnvFilter::from_default_env())
662                .init();
663        });
664
665        let mut rng = create_rng();
666        let num_keys = num_signers * keys_per_signer;
667        let threshold = (num_keys * 7) / 10;
668        let dkg_threshold = (num_keys * 9) / 10;
669        let key_pairs = (0..num_signers)
670            .map(|_| {
671                let private_key = Scalar::random(&mut rng);
672                let public_key = ecdsa::PublicKey::new(&private_key).unwrap();
673                (private_key, public_key)
674            })
675            .collect::<Vec<(Scalar, ecdsa::PublicKey)>>();
676        let mut key_id: u32 = 1;
677        let mut signer_ids_map = HashMap::new();
678        let mut signer_key_ids = HashMap::new();
679        let mut signer_key_ids_set = HashMap::new();
680        let mut signer_public_keys = HashMap::new();
681        let mut key_ids_map = HashMap::new();
682        for (i, (private_key, public_key)) in key_pairs.iter().enumerate() {
683            let mut key_ids = Vec::new();
684            let mut key_ids_set = HashSet::new();
685            for _ in 0..keys_per_signer {
686                key_ids_map.insert(key_id, *public_key);
687                key_ids.push(key_id);
688                key_ids_set.insert(key_id);
689                key_id += 1;
690            }
691            signer_ids_map.insert(i as u32, *public_key);
692            signer_key_ids.insert(i as u32, key_ids);
693            signer_key_ids_set.insert(i as u32, key_ids_set);
694            signer_public_keys.insert(i as u32, Point::from(private_key));
695        }
696        let public_keys = PublicKeys {
697            signers: signer_ids_map,
698            key_ids: key_ids_map,
699            signer_key_ids: signer_key_ids_set.clone(),
700        };
701
702        let signers = key_pairs
703            .iter()
704            .enumerate()
705            .map(|(signer_id, (private_key, _public_key))| {
706                let mut signer = Signer::<SignerType>::new(
707                    threshold,
708                    dkg_threshold,
709                    num_signers,
710                    num_keys,
711                    signer_id as u32,
712                    signer_key_ids[&(signer_id as u32)].clone(),
713                    *private_key,
714                    public_keys.clone(),
715                    &mut rng,
716                )
717                .unwrap();
718                signer.verify_packet_sigs = verify_packet_sigs;
719                signer
720            })
721            .collect::<Vec<Signer<SignerType>>>();
722        let coordinators = key_pairs
723            .into_iter()
724            .map(|(private_key, _public_key)| {
725                let mut config = Config::with_timeouts(
726                    num_signers,
727                    num_keys,
728                    threshold,
729                    dkg_threshold,
730                    private_key,
731                    dkg_public_timeout,
732                    dkg_private_timeout,
733                    dkg_end_timeout,
734                    nonce_timeout,
735                    sign_timeout,
736                    public_keys.clone(),
737                );
738                config.verify_packet_sigs = verify_packet_sigs;
739                Coordinator::new(config)
740            })
741            .collect::<Vec<Coordinator>>();
742        (coordinators, signers)
743    }
744
745    /// Helper function for feeding messages back from the processor into the signing rounds and coordinators
746    pub fn feedback_messages<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
747        coordinators: &mut [Coordinator],
748        signers: &mut [Signer<SignerType>],
749        messages: &[Packet],
750    ) -> (Vec<Packet>, Vec<OperationResult>) {
751        feedback_mutated_messages(coordinators, signers, messages, |_signer, msgs| msgs)
752    }
753
754    /// Helper function for feeding mutated messages back from the processor into the signing rounds and coordinators
755    pub fn feedback_mutated_messages<
756        Coordinator: CoordinatorTrait,
757        SignerType: SignerTrait,
758        F: Fn(&Signer<SignerType>, Vec<Packet>) -> Vec<Packet>,
759    >(
760        coordinators: &mut [Coordinator],
761        signers: &mut [Signer<SignerType>],
762        messages: &[Packet],
763        signer_mutator: F,
764    ) -> (Vec<Packet>, Vec<OperationResult>) {
765        feedback_mutated_messages_with_errors(coordinators, signers, messages, signer_mutator)
766            .unwrap()
767    }
768
769    /// Helper function for feeding mutated messages back from the processor into the signing rounds and coordinators
770    pub fn feedback_messages_with_errors<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
771        coordinators: &mut [Coordinator],
772        signers: &mut [Signer<SignerType>],
773        messages: &[Packet],
774    ) -> Result<(Vec<Packet>, Vec<OperationResult>), StateMachineError> {
775        feedback_mutated_messages_with_errors(coordinators, signers, messages, |_signer, msgs| msgs)
776    }
777
778    /// Helper function for feeding mutated messages back from the processor into the signing rounds and coordinators
779    pub fn feedback_mutated_messages_with_errors<
780        Coordinator: CoordinatorTrait,
781        SignerType: SignerTrait,
782        F: Fn(&Signer<SignerType>, Vec<Packet>) -> Vec<Packet>,
783    >(
784        coordinators: &mut [Coordinator],
785        signers: &mut [Signer<SignerType>],
786        messages: &[Packet],
787        signer_mutator: F,
788    ) -> Result<(Vec<Packet>, Vec<OperationResult>), StateMachineError> {
789        let mut inbound_messages = vec![];
790        let mut feedback_messages = vec![];
791        let mut rng = create_rng();
792        for signer in signers.iter_mut() {
793            let outbound_messages = signer.process_inbound_messages(messages, &mut rng)?;
794            let outbound_messages = signer_mutator(signer, outbound_messages);
795            feedback_messages.extend_from_slice(outbound_messages.as_slice());
796            inbound_messages.extend(outbound_messages);
797        }
798        for signer in signers.iter_mut() {
799            let outbound_messages =
800                signer.process_inbound_messages(&feedback_messages, &mut rng)?;
801            inbound_messages.extend(outbound_messages);
802        }
803        for coordinator in coordinators.iter_mut() {
804            // Process all coordinator messages, but don't bother with propogating these results
805            for message in messages {
806                let _ = coordinator.process(message)?;
807            }
808        }
809        let mut results = vec![];
810        let mut messages = vec![];
811        for (i, coordinator) in coordinators.iter_mut().enumerate() {
812            for inbound_message in &inbound_messages {
813                let (outbound_message, outbound_result) = coordinator.process(inbound_message)?;
814                // Only propogate a single coordinator's messages and results
815                if i == 0 {
816                    messages.extend(outbound_message);
817                    results.extend(outbound_result);
818                }
819            }
820        }
821        Ok((messages, results))
822    }
823
824    pub fn run_dkg<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
825        num_signers: u32,
826        keys_per_signer: u32,
827    ) -> (Vec<Coordinator>, Vec<Signer<SignerType>>) {
828        let (mut coordinators, mut signers) =
829            setup::<Coordinator, SignerType>(num_signers, keys_per_signer);
830
831        // We have started a dkg round
832        let message = coordinators
833            .first_mut()
834            .unwrap()
835            .start_dkg_round(None)
836            .unwrap();
837        assert!(coordinators
838            .first_mut()
839            .unwrap()
840            .get_aggregate_public_key()
841            .is_none());
842        assert_eq!(
843            coordinators.first_mut().unwrap().get_state(),
844            State::DkgPublicGather
845        );
846
847        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinator
848        let (outbound_messages, operation_results) =
849            feedback_messages(&mut coordinators, &mut signers, &[message]);
850        assert!(operation_results.is_empty());
851        for coordinator in coordinators.iter() {
852            assert_eq!(coordinator.get_state(), State::DkgPublicSharesDoneGather);
853        }
854
855        assert_eq!(outbound_messages.len(), 1);
856        assert!(
857            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
858            "Expected DkgPublicSharesDone message"
859        );
860
861        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
862        let (outbound_messages, operation_results) =
863            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
864        assert!(operation_results.is_empty());
865        for coordinator in coordinators.iter() {
866            assert_eq!(coordinator.get_state(), State::DkgPrivateGather);
867        }
868
869        assert_eq!(outbound_messages.len(), 1);
870        assert!(
871            matches!(&outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
872            "Expected DkgPrivateBegin message"
873        );
874
875        // persist the state machines before continuing
876        let new_coordinators = coordinators
877            .iter()
878            .map(|c| Coordinator::load(&c.save()))
879            .collect::<Vec<Coordinator>>();
880
881        assert_eq!(coordinators, new_coordinators);
882
883        coordinators = new_coordinators;
884
885        let new_signers = signers
886            .iter()
887            .map(|s| Signer::<SignerType>::load(&s.save()))
888            .collect::<Vec<Signer<SignerType>>>();
889
890        assert_eq!(signers, new_signers);
891
892        signers = new_signers;
893
894        // Send the DKG Private Begin message to all signers and share their responses with the coordinator and signers
895        let (outbound_messages, operation_results) =
896            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
897        assert_eq!(operation_results.len(), 0);
898        assert_eq!(outbound_messages.len(), 1);
899        assert!(
900            matches!(outbound_messages[0].msg, Message::DkgPrivateSharesDone(_)),
901            "Expected DkgPrivateSharesDone message"
902        );
903
904        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
905        let (outbound_messages, operation_results) =
906            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
907        assert_eq!(operation_results.len(), 0);
908        assert_eq!(outbound_messages.len(), 1);
909        assert!(
910            matches!(outbound_messages[0].msg, Message::DkgEndBegin(_)),
911            "Expected DkgEndBegin message"
912        );
913
914        // persist the state machines before continuing
915        let new_coordinators = coordinators
916            .iter()
917            .map(|c| Coordinator::load(&c.save()))
918            .collect::<Vec<Coordinator>>();
919
920        assert_eq!(coordinators, new_coordinators);
921
922        coordinators = new_coordinators;
923
924        let new_signers = signers
925            .iter()
926            .map(|s| Signer::<SignerType>::load(&s.save()))
927            .collect::<Vec<Signer<SignerType>>>();
928
929        assert_eq!(signers, new_signers);
930
931        signers = new_signers;
932
933        // Send the DkgEndBegin message to all signers and share their responses with the coordinator and signers
934        let (outbound_messages, operation_results) =
935            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
936        assert_eq!(outbound_messages.len(), 0);
937        assert_eq!(operation_results.len(), 1);
938        let OperationResult::Dkg(point) = operation_results[0] else {
939            panic!("Expected Dkg Operation result");
940        };
941        assert_ne!(point, Point::default());
942        for coordinator in coordinators.iter() {
943            assert_eq!(coordinator.get_aggregate_public_key(), Some(point));
944            assert_eq!(coordinator.get_state(), State::Idle);
945        }
946
947        // clear the polynomials before persisting
948        for signer in &mut signers {
949            signer.signer.clear_polys();
950        }
951
952        // persist the state machines before continuing
953        let new_coordinators = coordinators
954            .iter()
955            .map(|c| Coordinator::load(&c.save()))
956            .collect::<Vec<Coordinator>>();
957
958        assert_eq!(coordinators, new_coordinators);
959
960        coordinators = new_coordinators;
961
962        let new_signers = signers
963            .iter()
964            .map(|s| Signer::<SignerType>::load(&s.save()))
965            .collect::<Vec<Signer<SignerType>>>();
966
967        assert_eq!(signers, new_signers);
968
969        signers = new_signers;
970
971        (coordinators, signers)
972    }
973
974    pub fn run_sign<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
975        coordinators: &mut [Coordinator],
976        signers: &mut Vec<Signer<SignerType>>,
977        msg: &[u8],
978        signature_type: SignatureType,
979    ) -> OperationResult {
980        // Start a signing round
981        let message = coordinators
982            .first_mut()
983            .unwrap()
984            .start_signing_round(msg, signature_type, None)
985            .unwrap();
986        assert_eq!(
987            coordinators.first_mut().unwrap().get_state(),
988            State::NonceGather(signature_type)
989        );
990
991        // Send the message to all signers and gather responses by sharing with all other signers and coordinator
992        let (outbound_messages, operation_results) =
993            feedback_messages(coordinators, signers, &[message]);
994        assert!(operation_results.is_empty());
995        assert_eq!(
996            coordinators.first_mut().unwrap().get_state(),
997            State::SigShareGather(signature_type)
998        );
999
1000        assert_eq!(outbound_messages.len(), 1);
1001        assert!(
1002            matches!(outbound_messages[0].msg, Message::SignatureShareRequest(_)),
1003            "Expected SignatureShareRequest message"
1004        );
1005
1006        // persist the coordinators before continuing
1007        let _new_coordinators = coordinators
1008            .iter()
1009            .map(|c| Coordinator::load(&c.save()))
1010            .collect::<Vec<Coordinator>>();
1011
1012        let new_signers = signers
1013            .iter()
1014            .map(|s| Signer::<SignerType>::load(&s.save()))
1015            .collect::<Vec<Signer<SignerType>>>();
1016
1017        assert_eq!(signers, &new_signers);
1018
1019        // Send the SignatureShareRequest message to all signers and share their responses with the coordinator and signers
1020        let (outbound_messages, operation_results) =
1021            feedback_messages(coordinators, signers, &outbound_messages);
1022        assert!(outbound_messages.is_empty());
1023        assert_eq!(operation_results.len(), 1);
1024        match &operation_results[0] {
1025            OperationResult::Sign(sig) => {
1026                let SignatureType::Frost = signature_type else {
1027                    panic!("Expected OperationResult::Sign");
1028                };
1029                for coordinator in coordinators.iter() {
1030                    assert!(sig.verify(
1031                        &coordinator
1032                            .get_aggregate_public_key()
1033                            .expect("No aggregate public key set!"),
1034                        msg
1035                    ));
1036                    assert_eq!(coordinator.get_state(), State::Idle);
1037                }
1038            }
1039            OperationResult::SignSchnorr(sig) => {
1040                let SignatureType::Schnorr = signature_type else {
1041                    panic!("Expected OperationResult::SignSchnorr");
1042                };
1043                for coordinator in coordinators.iter() {
1044                    assert!(sig.verify(
1045                        &coordinator
1046                            .get_aggregate_public_key()
1047                            .expect("No aggregate public key set!")
1048                            .x(),
1049                        msg
1050                    ));
1051                    assert_eq!(coordinator.get_state(), State::Idle);
1052                }
1053            }
1054            OperationResult::SignTaproot(sig) => {
1055                let SignatureType::Taproot(merkle_root) = signature_type else {
1056                    panic!("Expected OperationResult::SignTaproot");
1057                };
1058                for coordinator in coordinators.iter() {
1059                    let tweaked_public_key = compute::tweaked_public_key(
1060                        &coordinator
1061                            .get_aggregate_public_key()
1062                            .expect("No aggregate public key set!"),
1063                        merkle_root,
1064                    );
1065
1066                    assert!(sig.verify(&tweaked_public_key.x(), msg));
1067                    assert_eq!(coordinator.get_state(), State::Idle);
1068                }
1069            }
1070            _ => panic!("Expected OperationResult"),
1071        }
1072
1073        operation_results[0].clone()
1074    }
1075
1076    pub fn run_dkg_sign<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
1077        num_signers: u32,
1078        keys_per_signer: u32,
1079    ) {
1080        let (mut coordinators, mut signers) =
1081            run_dkg::<Coordinator, SignerType>(num_signers, keys_per_signer);
1082
1083        let msg = "It was many and many a year ago, in a kingdom by the sea"
1084            .as_bytes()
1085            .to_vec();
1086
1087        run_sign::<Coordinator, SignerType>(
1088            &mut coordinators,
1089            &mut signers,
1090            &msg,
1091            SignatureType::Frost,
1092        );
1093        run_sign::<Coordinator, SignerType>(
1094            &mut coordinators,
1095            &mut signers,
1096            &msg,
1097            SignatureType::Schnorr,
1098        );
1099        run_sign::<Coordinator, SignerType>(
1100            &mut coordinators,
1101            &mut signers,
1102            &msg,
1103            SignatureType::Taproot(None),
1104        );
1105        run_sign::<Coordinator, SignerType>(
1106            &mut coordinators,
1107            &mut signers,
1108            &msg,
1109            SignatureType::Taproot(Some([128u8; 32])),
1110        );
1111    }
1112
1113    pub fn verify_packet_sigs<Coordinator: CoordinatorTrait, SignerType: SignerTrait>() {
1114        verify_removed_coordinator_key_on_signers::<Coordinator, SignerType>();
1115        verify_removed_coordinator_key_on_coordinator::<Coordinator, SignerType>();
1116        verify_changed_coordinator_key_on_signers::<Coordinator, SignerType>();
1117        verify_changed_coordinator_key_on_coordinator::<Coordinator, SignerType>();
1118    }
1119
1120    pub fn verify_removed_coordinator_key_on_signers<
1121        Coordinator: CoordinatorTrait,
1122        SignerType: SignerTrait,
1123    >() {
1124        let (coordinators, mut signers) = setup_verifying::<Coordinator, SignerType>(5, 1);
1125        let mut coordinators = vec![coordinators[0].clone()];
1126
1127        for coordinator in coordinators.iter_mut() {
1128            let coordinator_public_key = coordinator.get_config().public_keys.signers[&0];
1129            coordinator.set_coordinator_public_key(Some(coordinator_public_key));
1130        }
1131
1132        for signer in signers.iter_mut() {
1133            let coordinator_public_key = signer.public_keys.signers[&0];
1134            signer.coordinator_public_key = Some(coordinator_public_key);
1135        }
1136
1137        // We have started a dkg round
1138        let message = coordinators
1139            .first_mut()
1140            .unwrap()
1141            .start_dkg_round(None)
1142            .unwrap();
1143        assert!(coordinators
1144            .first_mut()
1145            .unwrap()
1146            .get_aggregate_public_key()
1147            .is_none());
1148        assert_eq!(
1149            coordinators.first_mut().unwrap().get_state(),
1150            State::DkgPublicGather
1151        );
1152
1153        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinator
1154        let (outbound_messages, operation_results) =
1155            feedback_messages(&mut coordinators, &mut signers, &[message]);
1156        assert!(operation_results.is_empty());
1157        for coordinator in coordinators.iter() {
1158            assert_eq!(coordinator.get_state(), State::DkgPublicSharesDoneGather);
1159        }
1160
1161        assert_eq!(outbound_messages.len(), 1);
1162        assert!(
1163            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
1164            "Expected DkgPublicSharesDone message"
1165        );
1166
1167        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
1168        let (outbound_messages, operation_results) =
1169            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
1170        assert!(operation_results.is_empty());
1171        for coordinator in coordinators.iter() {
1172            assert_eq!(coordinator.get_state(), State::DkgPrivateGather);
1173        }
1174
1175        assert_eq!(outbound_messages.len(), 1);
1176        match &outbound_messages[0].msg {
1177            Message::DkgPrivateBegin(_) => {}
1178            _ => {
1179                panic!("Expected DkgPrivateBegin message");
1180            }
1181        }
1182
1183        // Send the DKG Private Begin message to all signers and share their responses with the coordinator and signers
1184        let (outbound_messages, operation_results) =
1185            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
1186        assert_eq!(operation_results.len(), 0);
1187        assert_eq!(outbound_messages.len(), 1);
1188        match &outbound_messages[0].msg {
1189            Message::DkgPrivateSharesDone(_) => {}
1190            _ => {
1191                panic!("Expected DkgPrivateSharesDone message");
1192            }
1193        }
1194
1195        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
1196        let (outbound_messages, operation_results) =
1197            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
1198        assert_eq!(operation_results.len(), 0);
1199        assert_eq!(outbound_messages.len(), 1);
1200        match &outbound_messages[0].msg {
1201            Message::DkgEndBegin(_) => {}
1202            _ => {
1203                panic!("Expected DkgEndBegin message");
1204            }
1205        }
1206
1207        // Send the DkgEndBegin message to all signers and share their responses with the coordinator and signers
1208        let (outbound_messages, operation_results) =
1209            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
1210        assert_eq!(outbound_messages.len(), 0);
1211        assert_eq!(operation_results.len(), 1);
1212        match operation_results[0] {
1213            OperationResult::Dkg(point) => {
1214                assert_ne!(point, Point::default());
1215                for coordinator in coordinators.iter() {
1216                    assert_eq!(coordinator.get_aggregate_public_key(), Some(point));
1217                    assert_eq!(coordinator.get_state(), State::Idle);
1218                }
1219            }
1220            _ => panic!("Expected Dkg Operation result"),
1221        }
1222
1223        // clear the polynomials before persisting
1224        for signer in &mut signers {
1225            signer.signer.clear_polys();
1226        }
1227
1228        let msg = "It was many and many a year ago, in a kingdom by the sea"
1229            .as_bytes()
1230            .to_vec();
1231
1232        run_sign::<Coordinator, SignerType>(
1233            &mut coordinators,
1234            &mut signers,
1235            &msg,
1236            SignatureType::Frost,
1237        );
1238
1239        // Remove the coordinator public key on the signers and show that signers fail to verify
1240        for signer in signers.iter_mut() {
1241            signer.coordinator_public_key = None;
1242        }
1243
1244        let message = coordinators
1245            .first_mut()
1246            .unwrap()
1247            .start_dkg_round(None)
1248            .unwrap();
1249        assert_eq!(
1250            coordinators.first_mut().unwrap().get_state(),
1251            State::DkgPublicGather
1252        );
1253
1254        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[message]);
1255        assert!(matches!(
1256            result,
1257            Err(StateMachineError::Signer(
1258                SignerError::MissingCoordinatorPublicKey
1259            ))
1260        ));
1261    }
1262
1263    // Remove the coordinator public key on the coordinator and show that signatures fail to verify
1264    pub fn verify_removed_coordinator_key_on_coordinator<
1265        Coordinator: CoordinatorTrait,
1266        SignerType: SignerTrait,
1267    >() {
1268        let (coordinators, mut signers) = setup_verifying::<Coordinator, SignerType>(5, 1);
1269        let mut coordinators = vec![coordinators[0].clone()];
1270
1271        for coordinator in coordinators.iter_mut() {
1272            coordinator.set_coordinator_public_key(None);
1273        }
1274
1275        for signer in signers.iter_mut() {
1276            let coordinator_public_key = signer.public_keys.signers[&0];
1277            signer.coordinator_public_key = Some(coordinator_public_key);
1278        }
1279
1280        let message = coordinators
1281            .first_mut()
1282            .unwrap()
1283            .start_dkg_round(None)
1284            .unwrap();
1285        assert_eq!(
1286            coordinators.first_mut().unwrap().get_state(),
1287            State::DkgPublicGather
1288        );
1289
1290        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[message]);
1291        assert!(matches!(
1292            result,
1293            Err(StateMachineError::Coordinator(
1294                Error::MissingCoordinatorPublicKey
1295            ))
1296        ));
1297    }
1298
1299    // Change the coordinator public key on the signers and show that signatures fail to verify
1300    pub fn verify_changed_coordinator_key_on_signers<
1301        Coordinator: CoordinatorTrait,
1302        SignerType: SignerTrait,
1303    >() {
1304        let (coordinators, mut signers) = setup_verifying::<Coordinator, SignerType>(5, 1);
1305        let mut coordinators = vec![coordinators[0].clone()];
1306
1307        for coordinator in coordinators.iter_mut() {
1308            let coordinator_public_key = coordinator.get_config().public_keys.signers[&0];
1309            coordinator.set_coordinator_public_key(Some(coordinator_public_key));
1310        }
1311
1312        for signer in signers.iter_mut() {
1313            let coordinator_public_key = signer.public_keys.signers[&1];
1314            signer.coordinator_public_key = Some(coordinator_public_key);
1315        }
1316
1317        let message = coordinators
1318            .first_mut()
1319            .unwrap()
1320            .start_dkg_round(None)
1321            .unwrap();
1322        assert_eq!(
1323            coordinators.first_mut().unwrap().get_state(),
1324            State::DkgPublicGather
1325        );
1326
1327        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[message]);
1328        assert!(matches!(
1329            result,
1330            Err(StateMachineError::Signer(
1331                SignerError::InvalidPacketSignature
1332            ))
1333        ));
1334    }
1335
1336    // Change the coordinator public key on the coordinator and show that signatures fail to verify
1337    pub fn verify_changed_coordinator_key_on_coordinator<
1338        Coordinator: CoordinatorTrait,
1339        SignerType: SignerTrait,
1340    >() {
1341        let (coordinators, mut signers) = setup_verifying::<Coordinator, SignerType>(5, 1);
1342        let mut coordinators = vec![coordinators[0].clone()];
1343
1344        for coordinator in coordinators.iter_mut() {
1345            let coordinator_public_key = coordinator.get_config().public_keys.signers[&1];
1346            coordinator.set_coordinator_public_key(Some(coordinator_public_key));
1347        }
1348
1349        for signer in signers.iter_mut() {
1350            let coordinator_public_key = signer.public_keys.signers[&0];
1351            signer.coordinator_public_key = Some(coordinator_public_key);
1352        }
1353
1354        let message = coordinators
1355            .first_mut()
1356            .unwrap()
1357            .start_dkg_round(None)
1358            .unwrap();
1359        assert_eq!(
1360            coordinators.first_mut().unwrap().get_state(),
1361            State::DkgPublicGather
1362        );
1363
1364        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[message]);
1365        assert!(matches!(
1366            result,
1367            Err(StateMachineError::Coordinator(
1368                Error::InvalidPacketSignature
1369            ))
1370        ));
1371    }
1372
1373    /// Run DKG then sign a message, but alter the signature shares for signer 0.  This should trigger the aggregator internal check_signature_shares function to run and determine which parties signatures were bad.
1374    /// Because of the differences between how parties are represented in v1 and v2, we need to pass in a vector of the expected bad parties.
1375    pub fn check_signature_shares<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
1376        num_signers: u32,
1377        keys_per_signer: u32,
1378        signature_type: SignatureType,
1379        bad_parties: Vec<u32>,
1380    ) {
1381        let (mut coordinators, mut signers) =
1382            run_dkg::<Coordinator, SignerType>(num_signers, keys_per_signer);
1383
1384        let msg = "It was many and many a year ago, in a kingdom by the sea"
1385            .as_bytes()
1386            .to_vec();
1387        // Start a signing round
1388        let message = coordinators
1389            .first_mut()
1390            .unwrap()
1391            .start_signing_round(&msg, signature_type, None)
1392            .unwrap();
1393        assert_eq!(
1394            coordinators.first_mut().unwrap().get_state(),
1395            State::NonceGather(signature_type)
1396        );
1397
1398        // Send the message to all signers and gather responses by sharing with all other signers and coordinator
1399        let (outbound_messages, operation_results) =
1400            feedback_messages(&mut coordinators, &mut signers, &[message]);
1401        assert!(operation_results.is_empty());
1402        assert_eq!(
1403            coordinators.first_mut().unwrap().get_state(),
1404            State::SigShareGather(signature_type)
1405        );
1406
1407        assert_eq!(outbound_messages.len(), 1);
1408        assert!(
1409            matches!(outbound_messages[0].msg, Message::SignatureShareRequest(_)),
1410            "Expected SignatureShareRequest message"
1411        );
1412
1413        // Send the SignatureShareRequest message to all signers and share their responses with the coordinator and signers
1414        let (outbound_messages, operation_results) = feedback_mutated_messages(
1415            &mut coordinators,
1416            &mut signers,
1417            &outbound_messages,
1418            |signer, packets| {
1419                if signer.signer_id != 0 {
1420                    return packets.clone();
1421                }
1422                packets
1423                    .iter()
1424                    .map(|packet| {
1425                        let Message::SignatureShareResponse(response) = &packet.msg else {
1426                            return packet.clone();
1427                        };
1428                        // mutate one of the shares
1429                        let sshares: Vec<SignatureShare> = response
1430                            .signature_shares
1431                            .iter()
1432                            .map(|share| SignatureShare {
1433                                id: share.id,
1434                                key_ids: share.key_ids.clone(),
1435                                z_i: share.z_i + Scalar::from(1),
1436                            })
1437                            .collect();
1438                        Packet {
1439                            msg: Message::SignatureShareResponse(SignatureShareResponse {
1440                                dkg_id: response.dkg_id,
1441                                sign_id: response.sign_id,
1442                                sign_iter_id: response.sign_iter_id,
1443                                signer_id: response.signer_id,
1444                                signature_shares: sshares,
1445                            }),
1446                            sig: vec![],
1447                        }
1448                    })
1449                    .collect()
1450            },
1451        );
1452        assert!(outbound_messages.is_empty());
1453        assert_eq!(operation_results.len(), 1);
1454        let OperationResult::SignError(SignError::Coordinator(Error::Aggregator(
1455            AggregatorError::BadPartySigs(parties),
1456        ))) = &operation_results[0]
1457        else {
1458            panic!("Expected OperationResult::SignError(SignError::Coordinator(Error::Aggregator(AggregatorError::BadPartySigs(parties))))");
1459        };
1460        assert_eq!(
1461            parties, &bad_parties,
1462            "Expected BadPartySigs from {bad_parties:?}, got {:?}",
1463            operation_results[0]
1464        );
1465    }
1466
1467    pub fn equal_after_save_load<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
1468        num_signers: u32,
1469        keys_per_signer: u32,
1470    ) {
1471        let (coordinators, signers) =
1472            setup::<Coordinator, SignerType>(num_signers, keys_per_signer);
1473
1474        let loaded_coordinators = coordinators
1475            .iter()
1476            .map(|c| Coordinator::load(&c.save()))
1477            .collect::<Vec<Coordinator>>();
1478
1479        assert_eq!(coordinators, loaded_coordinators);
1480
1481        let loaded_signers = signers
1482            .iter()
1483            .map(|s| Signer::<SignerType>::load(&s.save()))
1484            .collect::<Vec<Signer<SignerType>>>();
1485
1486        assert_eq!(signers, loaded_signers);
1487    }
1488
1489    /// Test if a signer will generate a new nonce after a signing round as a defense
1490    /// against a malicious coordinator who requests multiple signing rounds
1491    /// with no nonce round in between to generate a new nonce
1492    pub fn gen_nonces<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
1493        num_signers: u32,
1494        keys_per_signer: u32,
1495    ) {
1496        let mut rng = OsRng;
1497
1498        let (mut coordinators, mut signers) =
1499            run_dkg::<Coordinator, SignerType>(num_signers, keys_per_signer);
1500
1501        let msg = "It was many and many a year ago, in a kingdom by the sea"
1502            .as_bytes()
1503            .to_vec();
1504
1505        let signature_type = SignatureType::Frost;
1506
1507        // Start a signing round
1508        let message = coordinators
1509            .first_mut()
1510            .unwrap()
1511            .start_signing_round(&msg, signature_type, None)
1512            .unwrap();
1513        assert_eq!(
1514            coordinators.first_mut().unwrap().get_state(),
1515            State::NonceGather(signature_type)
1516        );
1517
1518        // Send the NonceRequest to all signers and gather NonceResponses
1519        // by sharing with all other signers and coordinator
1520        let (outbound_messages, operation_results) =
1521            feedback_messages(&mut coordinators, &mut signers, &[message]);
1522        assert!(operation_results.is_empty());
1523        assert_eq!(
1524            coordinators.first_mut().unwrap().get_state(),
1525            State::SigShareGather(signature_type)
1526        );
1527
1528        // Once the coordinator has received sufficient NonceResponses,
1529        // it should send out a SignatureShareRequest
1530        assert_eq!(outbound_messages.len(), 1);
1531        assert!(
1532            matches!(outbound_messages[0].msg, Message::SignatureShareRequest(_)),
1533            "Expected SignatureShareRequest message"
1534        );
1535
1536        // Pass the SignatureShareRequest to the first signer and get his SignatureShares
1537        // which should use the nonce generated before sending out NonceResponse above
1538        let messages1 = signers[0].process(&outbound_messages[0], &mut rng).unwrap();
1539
1540        // Pass the SignatureShareRequest to the second signer and get his SignatureShares
1541        // which should use the nonce generated just before sending out the previous SignatureShare
1542        let messages2 = signers[0].process(&outbound_messages[0], &mut rng).unwrap();
1543
1544        // iterate through the responses and collect the embedded shares
1545        // if the signer didn't generate a nonce after sending the first signature shares
1546        // then the shares should be the same, since the message and everything else is
1547        for (message1, message2) in messages1.into_iter().zip(messages2) {
1548            let share1 = if let Message::SignatureShareResponse(response) = message1 {
1549                response.signature_shares[0].clone()
1550            } else {
1551                panic!("Message should have been SignatureShareResponse");
1552            };
1553            let share2 = if let Message::SignatureShareResponse(response) = message2 {
1554                response.signature_shares[0].clone()
1555            } else {
1556                panic!("Message should have been SignatureShareResponse");
1557            };
1558
1559            assert_ne!(share1.z_i, share2.z_i);
1560        }
1561    }
1562
1563    pub fn bad_signature_share_request<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
1564        num_signers: u32,
1565        keys_per_signer: u32,
1566    ) {
1567        let (mut coordinators, mut signers) =
1568            run_dkg::<Coordinator, SignerType>(num_signers, keys_per_signer);
1569
1570        let msg = "It was many and many a year ago, in a kingdom by the sea"
1571            .as_bytes()
1572            .to_vec();
1573
1574        // Start a signing round
1575        let signature_type = SignatureType::Frost;
1576        let message = coordinators
1577            .first_mut()
1578            .unwrap()
1579            .start_signing_round(&msg, signature_type, None)
1580            .unwrap();
1581        assert_eq!(
1582            coordinators.first_mut().unwrap().get_state(),
1583            State::NonceGather(signature_type)
1584        );
1585
1586        // Send the message to all signers and gather responses by sharing with all other signers and coordinator
1587        let (outbound_messages, operation_results) =
1588            feedback_messages(&mut coordinators, &mut signers, &[message]);
1589        assert!(operation_results.is_empty());
1590        assert_eq!(
1591            coordinators.first_mut().unwrap().get_state(),
1592            State::SigShareGather(signature_type)
1593        );
1594
1595        assert_eq!(outbound_messages.len(), 1);
1596        assert!(
1597            matches!(outbound_messages[0].msg, Message::SignatureShareRequest(_)),
1598            "Expected SignatureShareRequest message"
1599        );
1600
1601        // test request with no NonceResponses — signers are in SignGather, errors before state change
1602        let mut packet = outbound_messages[0].clone();
1603        let Message::SignatureShareRequest(ref mut request) = packet.msg else {
1604            panic!("failed to match message");
1605        };
1606        request.nonce_responses.clear();
1607
1608        // Send the SignatureShareRequest message to all signers and share
1609        // their responses with the coordinator and signers
1610        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[packet]);
1611        assert!(
1612            matches!(
1613                result,
1614                Err(StateMachineError::Signer(SignerError::InvalidNonceResponse))
1615            ),
1616            "Should have received signer invalid nonce response error, got {result:?}"
1617        );
1618
1619        // test request with a duplicate NonceResponse
1620        let mut packet = outbound_messages[0].clone();
1621        let Message::SignatureShareRequest(ref mut request) = packet.msg else {
1622            panic!("failed to match message");
1623        };
1624        request
1625            .nonce_responses
1626            .push(request.nonce_responses[0].clone());
1627
1628        // Send the SignatureShareRequest message to all signers and share
1629        // their responses with the coordinator and signers
1630        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[packet]);
1631        assert!(
1632            matches!(
1633                result,
1634                Err(StateMachineError::Signer(SignerError::InvalidNonceResponse))
1635            ),
1636            "Should have received signer invalid nonce response error, got {result:?}"
1637        );
1638
1639        // test request with an out of range signer_id
1640        let mut packet = outbound_messages[0].clone();
1641        let Message::SignatureShareRequest(ref mut request) = packet.msg else {
1642            panic!("failed to match message");
1643        };
1644        request.nonce_responses[0].signer_id = num_signers;
1645
1646        // Send the SignatureShareRequest message to all signers and share
1647        // their responses with the coordinator and signers
1648        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[packet]);
1649        assert!(
1650            matches!(
1651                result,
1652                Err(StateMachineError::Signer(SignerError::InvalidNonceResponse))
1653            ),
1654            "Should have received signer invalid nonce response error, got {result:?}"
1655        );
1656
1657        // send valid SSR last — signers are still in SignGather after all error cases
1658        let messages = outbound_messages.clone();
1659        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &messages);
1660        assert!(result.is_ok());
1661    }
1662
1663    pub fn invalid_nonce<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
1664        num_signers: u32,
1665        keys_per_signer: u32,
1666    ) {
1667        let (mut coordinators, mut signers) =
1668            run_dkg::<Coordinator, SignerType>(num_signers, keys_per_signer);
1669
1670        let msg = "It was many and many a year ago, in a kingdom by the sea"
1671            .as_bytes()
1672            .to_vec();
1673
1674        // Start a signing round
1675        let signature_type = SignatureType::Frost;
1676        let message = coordinators
1677            .first_mut()
1678            .unwrap()
1679            .start_signing_round(&msg, signature_type, None)
1680            .unwrap();
1681        assert_eq!(
1682            coordinators.first_mut().unwrap().get_state(),
1683            State::NonceGather(signature_type)
1684        );
1685
1686        // Send the message to all signers and gather responses by sharing with all other signers and coordinator
1687        let (outbound_messages, operation_results) =
1688            feedback_messages(&mut coordinators, &mut signers, &[message]);
1689        assert!(operation_results.is_empty());
1690        assert_eq!(
1691            coordinators.first_mut().unwrap().get_state(),
1692            State::SigShareGather(signature_type)
1693        );
1694
1695        assert_eq!(outbound_messages.len(), 1);
1696        assert!(
1697            matches!(outbound_messages[0].msg, Message::SignatureShareRequest(_)),
1698            "Expected SignatureShareRequest message"
1699        );
1700
1701        // test request with NonceResponse having zero nonce — signers are in SignGather, errors before state change
1702        let mut packet = outbound_messages[0].clone();
1703        let Message::SignatureShareRequest(ref mut request) = packet.msg else {
1704            panic!("failed to match message");
1705        };
1706        for nonce_response in &mut request.nonce_responses {
1707            for nonce in &mut nonce_response.nonces {
1708                nonce.D = Point::new();
1709                nonce.E = Point::new();
1710            }
1711        }
1712
1713        // Send the SignatureShareRequest message to all signers and share
1714        // their responses with the coordinator and signers
1715        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[packet]);
1716        assert!(
1717            matches!(
1718                result,
1719                Err(StateMachineError::Signer(SignerError::InvalidNonceResponse))
1720            ),
1721            "Should have received signer invalid nonce response error, got {result:?}"
1722        );
1723
1724        // test request with NonceResponse having generator nonce
1725        let mut packet = outbound_messages[0].clone();
1726        let Message::SignatureShareRequest(ref mut request) = packet.msg else {
1727            panic!("failed to match message");
1728        };
1729        for nonce_response in &mut request.nonce_responses {
1730            for nonce in &mut nonce_response.nonces {
1731                nonce.D = G;
1732                nonce.E = G;
1733            }
1734        }
1735
1736        // Send the SignatureShareRequest message to all signers and share
1737        // their responses with the coordinator and signers
1738        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[packet]);
1739        assert!(
1740            matches!(
1741                result,
1742                Err(StateMachineError::Signer(SignerError::InvalidNonceResponse))
1743            ),
1744            "Should have received signer invalid nonce response error, got {result:?}"
1745        );
1746
1747        // test request with a duplicate NonceResponse
1748        let mut packet = outbound_messages[0].clone();
1749        let Message::SignatureShareRequest(ref mut request) = packet.msg else {
1750            panic!("failed to match message");
1751        };
1752        request
1753            .nonce_responses
1754            .push(request.nonce_responses[0].clone());
1755
1756        // Send the SignatureShareRequest message to all signers and share
1757        // their responses with the coordinator and signers
1758        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[packet]);
1759        assert!(
1760            matches!(
1761                result,
1762                Err(StateMachineError::Signer(SignerError::InvalidNonceResponse))
1763            ),
1764            "Should have received signer invalid nonce response error, got {result:?}"
1765        );
1766
1767        // test request with an out of range signer_id
1768        let mut packet = outbound_messages[0].clone();
1769        let Message::SignatureShareRequest(ref mut request) = packet.msg else {
1770            panic!("failed to match message");
1771        };
1772        request.nonce_responses[0].signer_id = num_signers;
1773
1774        // Send the SignatureShareRequest message to all signers and share
1775        // their responses with the coordinator and signers
1776        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &[packet]);
1777        assert!(
1778            matches!(
1779                result,
1780                Err(StateMachineError::Signer(SignerError::InvalidNonceResponse))
1781            ),
1782            "Should have received signer invalid nonce response error, got {result:?}"
1783        );
1784
1785        // send valid SSR last — signers are still in SignGather after all error cases
1786        let messages = outbound_messages.clone();
1787        let result = feedback_messages_with_errors(&mut coordinators, &mut signers, &messages);
1788        assert!(result.is_ok());
1789    }
1790
1791    pub fn empty_public_shares<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
1792        num_signers: u32,
1793        keys_per_signer: u32,
1794    ) {
1795        let (mut coordinators, mut signers) =
1796            setup::<Coordinator, SignerType>(num_signers, keys_per_signer);
1797
1798        // We have started a dkg round
1799        let message = coordinators
1800            .first_mut()
1801            .unwrap()
1802            .start_dkg_round(None)
1803            .unwrap();
1804        assert!(coordinators
1805            .first_mut()
1806            .unwrap()
1807            .get_aggregate_public_key()
1808            .is_none());
1809        assert_eq!(
1810            coordinators.first_mut().unwrap().get_state(),
1811            State::DkgPublicGather
1812        );
1813
1814        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinator
1815        let (outbound_messages, operation_results) = feedback_mutated_messages(
1816            &mut coordinators,
1817            &mut signers,
1818            &[message],
1819            |signer, packets| {
1820                if signer.signer_id != 0 {
1821                    return packets.clone();
1822                }
1823                packets
1824                    .iter()
1825                    .map(|packet| {
1826                        let Message::DkgPublicShares(shares) = &packet.msg else {
1827                            return packet.clone();
1828                        };
1829                        let public_shares = crate::net::DkgPublicShares {
1830                            dkg_id: shares.dkg_id,
1831                            signer_id: shares.signer_id,
1832                            comms: vec![],
1833                            kex_public_key: Point::new(),
1834                            kex_proof: schnorr::Proof {
1835                                R: Point::new(),
1836                                s: Scalar::new(),
1837                            },
1838                        };
1839                        Packet {
1840                            msg: Message::DkgPublicShares(public_shares),
1841                            sig: vec![],
1842                        }
1843                    })
1844                    .collect()
1845            },
1846        );
1847        assert!(operation_results.is_empty());
1848        for coordinator in coordinators.iter() {
1849            assert_eq!(coordinator.get_state(), State::DkgPublicSharesDoneGather);
1850        }
1851
1852        assert_eq!(outbound_messages.len(), 1);
1853        assert!(
1854            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
1855            "Expected DkgPublicSharesDone message"
1856        );
1857
1858        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
1859        let (outbound_messages, operation_results) =
1860            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
1861        assert!(operation_results.is_empty());
1862        for coordinator in coordinators.iter() {
1863            assert_eq!(coordinator.get_state(), State::DkgPrivateGather);
1864        }
1865
1866        assert_eq!(outbound_messages.len(), 1);
1867        assert!(
1868            matches!(outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
1869            "Expected DkgPrivateBegin message"
1870        );
1871        // Send the DKG Private Begin message to all signers and share their responses with the coordinator and signers
1872        let (outbound_messages, operation_results) =
1873            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
1874        assert_eq!(operation_results.len(), 0);
1875        assert_eq!(outbound_messages.len(), 1);
1876        assert!(
1877            matches!(outbound_messages[0].msg, Message::DkgPrivateSharesDone(_)),
1878            "Expected DkgPrivateSharesDone message"
1879        );
1880
1881        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
1882        let (outbound_messages, operation_results) =
1883            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
1884        assert_eq!(operation_results.len(), 0);
1885        assert_eq!(outbound_messages.len(), 1);
1886        assert!(
1887            matches!(outbound_messages[0].msg, Message::DkgEndBegin(_)),
1888            "Expected DkgEndBegin message"
1889        );
1890
1891        // Send the DkgEndBegin message to all signers and share their responses with the coordinator and signers
1892        let (outbound_messages, operation_results) =
1893            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
1894        assert_eq!(outbound_messages.len(), 0);
1895        assert_eq!(operation_results.len(), 1);
1896        let OperationResult::DkgError(DkgError::DkgEndFailure {
1897            reported_failures, ..
1898        }) = &operation_results[0]
1899        else {
1900            panic!(
1901                "Expected OperationResult::DkgError got {:?}",
1902                operation_results[0]
1903            );
1904        };
1905        assert_eq!(
1906            reported_failures.len(),
1907            num_signers as usize,
1908            "Expected {num_signers} DkgFailures got {}",
1909            reported_failures.len()
1910        );
1911        let expected_signer_ids = (0..1).collect::<HashSet<u32>>();
1912        for dkg_failure in reported_failures {
1913            let (_, DkgFailure::MissingPublicShares(signer_ids)) = dkg_failure else {
1914                panic!("Expected DkgFailure::MissingPublicShares got {dkg_failure:?}");
1915            };
1916            assert_eq!(
1917                expected_signer_ids, *signer_ids,
1918                "Expected signer_ids {expected_signer_ids:?} got {signer_ids:?}"
1919            );
1920        }
1921    }
1922
1923    pub fn empty_private_shares<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
1924        num_signers: u32,
1925        keys_per_signer: u32,
1926    ) {
1927        let (mut coordinators, mut signers) =
1928            setup::<Coordinator, SignerType>(num_signers, keys_per_signer);
1929
1930        // We have started a dkg round
1931        let message = coordinators
1932            .first_mut()
1933            .unwrap()
1934            .start_dkg_round(None)
1935            .unwrap();
1936        assert!(coordinators
1937            .first_mut()
1938            .unwrap()
1939            .get_aggregate_public_key()
1940            .is_none());
1941        assert_eq!(
1942            coordinators.first_mut().unwrap().get_state(),
1943            State::DkgPublicGather
1944        );
1945
1946        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinator
1947        let (outbound_messages, operation_results) =
1948            feedback_messages(&mut coordinators, &mut signers, &[message]);
1949        assert!(operation_results.is_empty());
1950        for coordinator in coordinators.iter() {
1951            assert_eq!(coordinator.get_state(), State::DkgPublicSharesDoneGather);
1952        }
1953
1954        assert_eq!(outbound_messages.len(), 1);
1955        assert!(
1956            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
1957            "Expected DkgPublicSharesDone message"
1958        );
1959
1960        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
1961        let (outbound_messages, operation_results) =
1962            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
1963        assert!(operation_results.is_empty());
1964        for coordinator in coordinators.iter() {
1965            assert_eq!(coordinator.get_state(), State::DkgPrivateGather);
1966        }
1967
1968        assert_eq!(outbound_messages.len(), 1);
1969        assert!(
1970            matches!(outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
1971            "Expected DkgPrivateBegin message"
1972        );
1973
1974        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinator
1975        let (outbound_messages, operation_results) = feedback_mutated_messages(
1976            &mut coordinators,
1977            &mut signers,
1978            &[outbound_messages[0].clone()],
1979            |signer, packets| {
1980                if signer.signer_id != 0 {
1981                    return packets.clone();
1982                }
1983                packets
1984                    .iter()
1985                    .map(|packet| {
1986                        let Message::DkgPrivateShares(shares) = &packet.msg else {
1987                            return packet.clone();
1988                        };
1989                        let private_shares = crate::net::DkgPrivateShares {
1990                            dkg_id: shares.dkg_id,
1991                            signer_id: shares.signer_id,
1992                            shares: vec![],
1993                        };
1994                        Packet {
1995                            msg: Message::DkgPrivateShares(private_shares),
1996                            sig: vec![],
1997                        }
1998                    })
1999                    .collect()
2000            },
2001        );
2002        assert_eq!(operation_results.len(), 0);
2003        assert_eq!(outbound_messages.len(), 1);
2004        assert!(
2005            matches!(&outbound_messages[0].msg, Message::DkgPrivateSharesDone(_)),
2006            "Expected DkgPrivateSharesDone message"
2007        );
2008
2009        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
2010        let (outbound_messages, operation_results) =
2011            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
2012        assert_eq!(operation_results.len(), 0);
2013        assert_eq!(outbound_messages.len(), 1);
2014        assert!(
2015            matches!(&outbound_messages[0].msg, Message::DkgEndBegin(_)),
2016            "Expected DkgEndBegin message"
2017        );
2018
2019        // Send the DkgEndBegin message to all signers and share their responses with the coordinator and signers
2020        let (outbound_messages, operation_results) =
2021            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
2022        assert_eq!(outbound_messages.len(), 0);
2023        assert_eq!(operation_results.len(), 1);
2024        let OperationResult::DkgError(DkgError::DkgEndFailure {
2025            reported_failures, ..
2026        }) = &operation_results[0]
2027        else {
2028            panic!(
2029                "Expected OperationResult::DkgError(DkgError::DkgEndFailure) got {:?}",
2030                operation_results[0]
2031            );
2032        };
2033        assert_eq!(
2034            reported_failures.len(),
2035            num_signers as usize,
2036            "Expected {num_signers} DkgFailures got {}",
2037            reported_failures.len()
2038        );
2039        let expected_signer_ids = (0..1).collect::<HashSet<u32>>();
2040        for dkg_failure in reported_failures {
2041            let (_, DkgFailure::MissingPrivateShares(signer_ids)) = dkg_failure else {
2042                panic!("Expected DkgFailure::MissingPublicShares got {dkg_failure:?}");
2043            };
2044            assert_eq!(
2045                expected_signer_ids, *signer_ids,
2046                "Expected signer_ids {expected_signer_ids:?} got {signer_ids:?}"
2047            );
2048        }
2049    }
2050
2051    use crate::btc::UnsignedTx;
2052
2053    use bitcoin::{
2054        blockdata::script::Builder,
2055        opcodes::all::*,
2056        secp256k1::{Secp256k1, XOnlyPublicKey},
2057        taproot::{self, LeafVersion, TaprootBuilder},
2058        TapSighashType, Witness,
2059    };
2060
2061    /// Create a taproot transaction with key and script spends, then sign/verify each spend path
2062    pub fn btc_sign_verify<Coordinator: CoordinatorTrait, SignerType: SignerTrait>(
2063        num_signers: u32,
2064        keys_per_signer: u32,
2065    ) {
2066        let (mut coordinators, mut signers) =
2067            run_dkg::<Coordinator, SignerType>(num_signers, keys_per_signer);
2068
2069        let aggregate_public_key = coordinators[0]
2070            .get_aggregate_public_key()
2071            .expect("public key");
2072        let aggregate_xonly_key = XOnlyPublicKey::from_slice(&aggregate_public_key.x().to_bytes())
2073            .expect("failed to create XOnlyPublicKey");
2074
2075        let secp = Secp256k1::new();
2076        let script = Builder::new()
2077            .push_x_only_key(&aggregate_xonly_key)
2078            .push_opcode(OP_CHECKSIG)
2079            .into_script();
2080        let spend_info = TaprootBuilder::new()
2081            .add_leaf(0, script.clone())
2082            .unwrap()
2083            .finalize(&secp, aggregate_xonly_key)
2084            .expect("failed to finalize taproot_spend_info");
2085        let merkle_root = spend_info.merkle_root();
2086        let internal_key = spend_info.internal_key();
2087        let unsigned = UnsignedTx::new(internal_key);
2088
2089        // test the key spend
2090        let sighash = unsigned
2091            .compute_sighash(&secp, merkle_root)
2092            .expect("failed to compute taproot sighash");
2093        let msg: &[u8] = sighash.as_ref();
2094
2095        let raw_merkle_root = merkle_root.map(|root| {
2096            let bytes: [u8; 32] = *root.to_raw_hash().as_ref();
2097            bytes
2098        });
2099
2100        let OperationResult::SignTaproot(proof) = run_sign::<Coordinator, SignerType>(
2101            &mut coordinators,
2102            &mut signers,
2103            msg,
2104            SignatureType::Taproot(raw_merkle_root),
2105        ) else {
2106            panic!("taproot signature failed");
2107        };
2108
2109        let schnorr_sig = bitcoin::secp256k1::schnorr::Signature::from_slice(&proof.to_bytes())
2110            .expect("Failed to parse Signature from slice");
2111        let taproot_sig = taproot::Signature {
2112            signature: schnorr_sig,
2113            sighash_type: TapSighashType::All,
2114        };
2115
2116        unsigned
2117            .verify_signature(&secp, &taproot_sig, merkle_root)
2118            .expect("signature verification failed");
2119
2120        // test the script spend
2121        let sighash = unsigned
2122            .compute_script_sighash(&secp, merkle_root, &script)
2123            .expect("failed to compute taproot sighash");
2124        let msg: &[u8] = sighash.as_ref();
2125
2126        let OperationResult::SignSchnorr(proof) = run_sign::<Coordinator, SignerType>(
2127            &mut coordinators,
2128            &mut signers,
2129            msg,
2130            SignatureType::Schnorr,
2131        ) else {
2132            panic!("schnorr signature failed");
2133        };
2134
2135        let schnorr_sig = bitcoin::secp256k1::schnorr::Signature::from_slice(&proof.to_bytes())
2136            .expect("Failed to parse Signature from slice");
2137        let taproot_sig = taproot::Signature {
2138            signature: schnorr_sig,
2139            sighash_type: TapSighashType::All,
2140        };
2141
2142        let control_block = spend_info
2143            .control_block(&(script.clone(), LeafVersion::TapScript))
2144            .expect("insert the accept script into the control block");
2145
2146        println!("ControlBlock {control_block:?}");
2147
2148        let mut witness = Witness::new();
2149        witness.push(taproot_sig.to_vec());
2150        witness.push(script.as_bytes());
2151        witness.push(control_block.serialize());
2152
2153        unsigned
2154            .verify_witness(&secp, witness, merkle_root)
2155            .expect("signature verification failed");
2156    }
2157}