Skip to main content

wsts/state_machine/coordinator/
fire.rs

1use hashbrown::{HashMap, HashSet};
2use std::{collections::BTreeMap, time::Instant};
3use tracing::{debug, error, info, warn};
4
5use crate::{
6    common::{check_public_shares, PolyCommitment, PublicNonce, Signature, SignatureShare},
7    compute,
8    curve::{
9        ecdsa,
10        point::{Point, G},
11        scalar::Scalar,
12    },
13    errors::AggregatorError,
14    net::{
15        DkgBegin, DkgEnd, DkgEndBegin, DkgFailure, DkgPrivateBegin, DkgPrivateShares,
16        DkgPrivateSharesDone, DkgPublicShares, DkgPublicSharesDone, DkgStatus, Message,
17        NonceRequest, NonceResponse, Packet, Signable, SignatureShareRequest, SignatureType,
18    },
19    state_machine::{
20        coordinator::{
21            Config, Coordinator as CoordinatorTrait, Error, SavedState, SignRoundInfo, State,
22        },
23        DkgError, OperationResult, SignError, StateMachine,
24    },
25    taproot::SchnorrProof,
26    traits::Aggregator as AggregatorTrait,
27    util::{decrypt, make_shared_secret_from_key},
28};
29
30/// The coordinator for the FIRE algorithm
31#[derive(Clone, Debug, PartialEq)]
32pub struct Coordinator<Aggregator: AggregatorTrait> {
33    /// common config fields
34    config: Config,
35    /// current DKG round ID
36    pub current_dkg_id: u64,
37    /// current signing round ID
38    pub current_sign_id: u64,
39    /// current signing iteration ID
40    pub current_sign_iter_id: u64,
41    dkg_public_shares: BTreeMap<u32, DkgPublicShares>,
42    dkg_private_shares: BTreeMap<u32, DkgPrivateShares>,
43    dkg_end_messages: BTreeMap<u32, DkgEnd>,
44    /// the current view of a successful DKG's participants' commitments
45    pub party_polynomials: HashMap<u32, PolyCommitment>,
46    signature_shares: BTreeMap<u32, Vec<SignatureShare>>,
47    message_nonces: BTreeMap<Vec<u8>, SignRoundInfo>,
48    /// aggregate public key
49    pub aggregate_public_key: Option<Point>,
50    signature: Option<Signature>,
51    schnorr_proof: Option<SchnorrProof>,
52    /// which signers we're currently waiting on for DKG
53    pub dkg_wait_signer_ids: HashSet<u32>,
54    /// the bytes that we're signing
55    pub message: Vec<u8>,
56    /// current state of the state machine
57    pub state: State,
58    /// Aggregator object
59    aggregator: Aggregator,
60    nonce_start: Option<Instant>,
61    dkg_public_start: Option<Instant>,
62    dkg_private_start: Option<Instant>,
63    dkg_end_start: Option<Instant>,
64    sign_start: Option<Instant>,
65    malicious_signer_ids: HashSet<u32>,
66    malicious_dkg_signer_ids: HashSet<u32>,
67    /// coordinator public key
68    pub coordinator_public_key: Option<ecdsa::PublicKey>,
69}
70
71impl<Aggregator: AggregatorTrait> Coordinator<Aggregator> {
72    /// Check the timeout
73    pub fn process_timeout(&mut self) -> Result<(Option<Packet>, Option<OperationResult>), Error> {
74        let now = Instant::now();
75        match self.state.clone() {
76            State::Idle => {}
77            State::DkgPublicDistribute => {}
78            State::DkgPublicGather => {
79                if let Some(start) = self.dkg_public_start {
80                    if let Some(timeout) = self.config.dkg_public_timeout {
81                        let elapsed = now.duration_since(start);
82                        if elapsed > timeout {
83                            // check dkg_threshold to determine if we can continue
84                            let dkg_size = self.compute_dkg_public_size()?;
85
86                            if self.config.dkg_threshold > dkg_size {
87                                error!("Timeout gathering DkgPublicShares for dkg round {} signing round {} iteration {}, dkg_threshold not met ({dkg_size}/{}), unable to continue ({:?} > {:?})", self.current_dkg_id, self.current_sign_id, self.current_sign_iter_id, self.config.dkg_threshold, elapsed, timeout);
88                                let wait = self.dkg_wait_signer_ids.iter().copied().collect();
89                                return Ok((
90                                    None,
91                                    Some(OperationResult::DkgError(DkgError::DkgPublicTimeout(
92                                        wait,
93                                    ))),
94                                ));
95                            } else {
96                                // we hit the timeout but met the threshold, continue
97                                warn!("Timeout gathering DkgPublicShares for dkg round {} signing round {} iteration {}, dkg_threshold was met ({dkg_size}/{}), continue ({:?} > {:?})", self.current_dkg_id, self.current_sign_id, self.current_sign_iter_id, self.config.dkg_threshold, elapsed, timeout);
98                                self.public_shares_gathered()?;
99                                let packet = self.send_public_shares_done()?;
100                                return Ok((Some(packet), None));
101                            }
102                        }
103                    }
104                }
105            }
106            State::DkgPublicSharesDoneDistribute => {}
107            State::DkgPublicSharesDoneGather => {
108                if let Some(start) = self.dkg_public_start {
109                    if let Some(timeout) = self.config.dkg_public_timeout {
110                        let elapsed = now.duration_since(start);
111                        if elapsed > timeout {
112                            error!("Timeout gathering DkgPublicSharesDoneAck for dkg round {}, not all signers responded  ({:?} > {:?})", self.current_dkg_id, elapsed, timeout);
113                            let wait = self.dkg_wait_signer_ids.iter().copied().collect();
114                            return Ok((
115                                None,
116                                Some(OperationResult::DkgError(DkgError::DkgPublicTimeout(wait))),
117                            ));
118                        }
119                    }
120                }
121            }
122            State::DkgPrivateDistribute => {}
123            State::DkgPrivateGather => {
124                if let Some(start) = self.dkg_private_start {
125                    if let Some(timeout) = self.config.dkg_private_timeout {
126                        let elapsed = now.duration_since(start);
127                        if elapsed > timeout {
128                            // check dkg_threshold to determine if we can continue
129                            let dkg_size = self.compute_dkg_private_size()?;
130
131                            if self.config.dkg_threshold > dkg_size {
132                                error!("Timeout gathering DkgPrivateShares for dkg round {} signing round {} iteration {}, dkg_threshold not met ({dkg_size}/{}), unable to continue ({:?} > {:?})", self.current_dkg_id, self.current_sign_id, self.current_sign_iter_id, self.config.dkg_threshold, elapsed, timeout);
133                                let wait = self.dkg_wait_signer_ids.iter().copied().collect();
134                                return Ok((
135                                    None,
136                                    Some(OperationResult::DkgError(DkgError::DkgPrivateTimeout(
137                                        wait,
138                                    ))),
139                                ));
140                            } else {
141                                // we hit the timeout but met the threshold, continue
142                                warn!("Timeout gathering DkgPrivateShares for dkg round {} signing round {} iteration {}, dkg_threshold was met ({dkg_size}/{}), continue ({:?} > {:?})", self.current_dkg_id, self.current_sign_id, self.current_sign_iter_id, self.config.dkg_threshold, elapsed, timeout);
143                                self.private_shares_gathered()?;
144                                let packet = self.send_private_shares_done()?;
145                                return Ok((Some(packet), None));
146                            }
147                        }
148                    }
149                }
150            }
151            State::DkgPrivateSharesDoneDistribute => {}
152            State::DkgPrivateSharesDoneGather => {
153                if let Some(start) = self.dkg_private_start {
154                    if let Some(timeout) = self.config.dkg_private_timeout {
155                        let elapsed = now.duration_since(start);
156                        if elapsed > timeout {
157                            error!("Timeout gathering DkgPrivateSharesDoneAck for dkg round {}, not all signers responded ({:?} > {:?})", self.current_dkg_id, elapsed, timeout);
158                            let wait = self.dkg_wait_signer_ids.iter().copied().collect();
159                            return Ok((
160                                None,
161                                Some(OperationResult::DkgError(DkgError::DkgPrivateTimeout(wait))),
162                            ));
163                        }
164                    }
165                }
166            }
167            State::DkgEndDistribute => {}
168            State::DkgEndGather => {
169                if let Some(start) = self.dkg_end_start {
170                    if let Some(timeout) = self.config.dkg_end_timeout {
171                        let elapsed = now.duration_since(start);
172                        if elapsed > timeout {
173                            error!("Timeout gathering DkgEnd for dkg round {} signing round {} iteration {}, unable to continue ({:?} > {:?})", self.current_dkg_id, self.current_sign_id, self.current_sign_iter_id, elapsed, timeout);
174                            let wait = self.dkg_wait_signer_ids.iter().copied().collect();
175                            return Ok((
176                                None,
177                                Some(OperationResult::DkgError(DkgError::DkgEndTimeout(wait))),
178                            ));
179                        }
180                    }
181                }
182            }
183            State::NonceRequest(_signature_type) => {}
184            State::SigShareRequest(_signature_type) => {}
185            State::NonceGather(_signature_type) => {
186                if let Some(start) = self.nonce_start {
187                    if let Some(timeout) = self.config.nonce_timeout {
188                        let elapsed = now.duration_since(start);
189                        if elapsed > timeout {
190                            error!("Timeout gathering nonces for signing round {} iteration {}, unable to continue ({:?} > {:?})", self.current_sign_id, self.current_sign_iter_id, elapsed, timeout);
191                            let recv = self
192                                .message_nonces
193                                .get(&self.message)
194                                .ok_or(Error::MissingMessageNonceInfo)?
195                                .sign_wait_signer_ids
196                                .iter()
197                                .copied()
198                                .collect();
199                            let mal = self.malicious_signer_ids.iter().copied().collect();
200                            return Ok((
201                                None,
202                                Some(OperationResult::SignError(SignError::NonceTimeout(
203                                    recv, mal,
204                                ))),
205                            ));
206                        }
207                    }
208                }
209            }
210            State::SigShareGather(signature_type) => {
211                if let Some(start) = self.sign_start {
212                    if let Some(timeout) = self.config.sign_timeout {
213                        let elapsed = now.duration_since(start);
214                        if elapsed > timeout {
215                            warn!("Timeout gathering signature shares for signing round {} iteration {} ({:?} > {:?})", self.current_sign_id, self.current_sign_iter_id, elapsed, timeout);
216                            for signer_id in &self
217                                .message_nonces
218                                .get(&self.message)
219                                .ok_or(Error::MissingMessageNonceInfo)?
220                                .sign_wait_signer_ids
221                            {
222                                warn!("Mark signer {signer_id} as malicious");
223                                self.malicious_signer_ids.insert(*signer_id);
224                            }
225
226                            let num_malicious_keys: u32 =
227                                self.compute_num_key_ids(self.malicious_signer_ids.iter())?;
228
229                            if self.config.num_keys - num_malicious_keys < self.config.threshold {
230                                error!("Insufficient non-malicious signers, unable to continue");
231                                let mal = self.malicious_signer_ids.iter().copied().collect();
232                                return Ok((
233                                    None,
234                                    Some(OperationResult::SignError(
235                                        SignError::InsufficientSigners(mal),
236                                    )),
237                                ));
238                            }
239
240                            self.move_to(State::NonceRequest(signature_type))?;
241                            let packet = self.request_nonces(signature_type)?;
242                            return Ok((Some(packet), None));
243                        }
244                    }
245                }
246            }
247        }
248        Ok((None, None))
249    }
250
251    /// Process the message inside the passed packet
252    pub fn process_message(
253        &mut self,
254        packet: &Packet,
255    ) -> Result<(Option<Packet>, Option<OperationResult>), Error> {
256        if self.config.verify_packet_sigs {
257            let Some(coordinator_public_key) = self.coordinator_public_key else {
258                return Err(Error::MissingCoordinatorPublicKey);
259            };
260            if !packet.verify(&self.config.public_keys, &coordinator_public_key) {
261                return Err(Error::InvalidPacketSignature);
262            }
263        }
264        loop {
265            match self.state.clone() {
266                State::Idle => {
267                    // Did we receive a coordinator message?
268                    if let Message::DkgBegin(dkg_begin) = &packet.msg {
269                        if self.current_dkg_id == dkg_begin.dkg_id {
270                            // We have already processed this DKG round
271                            return Ok((None, None));
272                        }
273                        // use dkg_id from DkgBegin
274                        let packet = self.start_dkg_round(Some(dkg_begin.dkg_id))?;
275                        return Ok((Some(packet), None));
276                    } else if let Message::NonceRequest(nonce_request) = &packet.msg {
277                        if self.current_sign_id == nonce_request.sign_id {
278                            // We have already processed this sign round
279                            return Ok((None, None));
280                        }
281                        self.current_sign_iter_id = nonce_request.sign_iter_id.wrapping_sub(1);
282                        // use sign_id from NonceRequest
283                        let packet = self.start_signing_round(
284                            nonce_request.message.as_slice(),
285                            nonce_request.signature_type,
286                            Some(nonce_request.sign_id),
287                        )?;
288                        return Ok((Some(packet), None));
289                    }
290                    return Ok((None, None));
291                }
292                State::DkgPublicDistribute => {
293                    let packet = self.start_public_shares()?;
294                    return Ok((Some(packet), None));
295                }
296                State::DkgPublicGather => {
297                    self.gather_public_shares(packet)?;
298                    if self.state == State::DkgPublicGather {
299                        // We need more data
300                        return Ok((None, None));
301                    }
302                }
303                State::DkgPublicSharesDoneDistribute => {
304                    let packet = self.send_public_shares_done()?;
305                    return Ok((Some(packet), None));
306                }
307                State::DkgPublicSharesDoneGather => {
308                    self.gather_public_shares_done_ack(packet)?;
309                    if self.state == State::DkgPublicSharesDoneGather {
310                        // We need more data
311                        return Ok((None, None));
312                    }
313                }
314                State::DkgPrivateDistribute => {
315                    let packet = self.start_private_shares()?;
316                    return Ok((Some(packet), None));
317                }
318                State::DkgPrivateGather => {
319                    self.gather_private_shares(packet)?;
320                    if self.state == State::DkgPrivateGather {
321                        // We need more data
322                        return Ok((None, None));
323                    }
324                }
325                State::DkgPrivateSharesDoneDistribute => {
326                    let packet = self.send_private_shares_done()?;
327                    return Ok((Some(packet), None));
328                }
329                State::DkgPrivateSharesDoneGather => {
330                    self.gather_private_shares_done_ack(packet)?;
331                    if self.state == State::DkgPrivateSharesDoneGather {
332                        // We need more data
333                        return Ok((None, None));
334                    }
335                }
336                State::DkgEndDistribute => {
337                    let packet = self.start_dkg_end()?;
338                    return Ok((Some(packet), None));
339                }
340                State::DkgEndGather => {
341                    if let Err(error) = self.gather_dkg_end(packet) {
342                        if let Error::DkgFailure {
343                            reported_failures,
344                            malicious_signers,
345                        } = error
346                        {
347                            return Ok((
348                                None,
349                                Some(OperationResult::DkgError(DkgError::DkgEndFailure {
350                                    reported_failures,
351                                    malicious_signers,
352                                })),
353                            ));
354                        } else {
355                            return Err(error);
356                        }
357                    }
358                    if self.state == State::DkgEndGather {
359                        // We need more data
360                        return Ok((None, None));
361                    } else if self.state == State::Idle {
362                        // We are done with the DKG round! Return the operation result
363                        return Ok((
364                            None,
365                            Some(OperationResult::Dkg(
366                                self.aggregate_public_key
367                                    .ok_or(Error::MissingAggregatePublicKey)?,
368                            )),
369                        ));
370                    }
371                }
372                State::NonceRequest(signature_type) => {
373                    let packet = self.request_nonces(signature_type)?;
374                    return Ok((Some(packet), None));
375                }
376                State::NonceGather(signature_type) => {
377                    self.gather_nonces(packet, signature_type)?;
378                    if self.state == State::NonceGather(signature_type) {
379                        // We need more data
380                        return Ok((None, None));
381                    }
382                }
383                State::SigShareRequest(signature_type) => {
384                    let packet = self.request_sig_shares(signature_type)?;
385                    return Ok((Some(packet), None));
386                }
387                State::SigShareGather(signature_type) => {
388                    if let Err(e) = self.gather_sig_shares(packet, signature_type) {
389                        return Ok((
390                            None,
391                            Some(OperationResult::SignError(SignError::Coordinator(e))),
392                        ));
393                    }
394                    if self.state == State::SigShareGather(signature_type) {
395                        // We need more data
396                        return Ok((None, None));
397                    } else if self.state == State::Idle {
398                        // We are done with the DKG round! Return the operation result
399                        if let SignatureType::Taproot(_) = signature_type {
400                            if let Some(schnorr_proof) = &self.schnorr_proof {
401                                return Ok((
402                                    None,
403                                    Some(OperationResult::SignTaproot(SchnorrProof {
404                                        r: schnorr_proof.r,
405                                        s: schnorr_proof.s,
406                                    })),
407                                ));
408                            } else {
409                                return Ok((
410                                    None,
411                                    Some(OperationResult::SignError(SignError::Coordinator(
412                                        Error::MissingSchnorrProof,
413                                    ))),
414                                ));
415                            }
416                        } else if let SignatureType::Schnorr = signature_type {
417                            if let Some(schnorr_proof) = &self.schnorr_proof {
418                                return Ok((
419                                    None,
420                                    Some(OperationResult::SignSchnorr(SchnorrProof {
421                                        r: schnorr_proof.r,
422                                        s: schnorr_proof.s,
423                                    })),
424                                ));
425                            } else {
426                                return Ok((
427                                    None,
428                                    Some(OperationResult::SignError(SignError::Coordinator(
429                                        Error::MissingSchnorrProof,
430                                    ))),
431                                ));
432                            }
433                        } else if let Some(signature) = &self.signature {
434                            return Ok((
435                                None,
436                                Some(OperationResult::Sign(Signature {
437                                    R: signature.R,
438                                    z: signature.z,
439                                })),
440                            ));
441                        } else {
442                            return Ok((
443                                None,
444                                Some(OperationResult::SignError(SignError::Coordinator(
445                                    Error::MissingSignature,
446                                ))),
447                            ));
448                        }
449                    }
450                }
451            }
452        }
453    }
454
455    /// Ask signers to send DKG public shares
456    pub fn start_public_shares(&mut self) -> Result<Packet, Error> {
457        self.dkg_public_shares.clear();
458        self.party_polynomials.clear();
459        self.dkg_wait_signer_ids = (0..self.config.num_signers).collect();
460        info!(
461            dkg_id = %self.current_dkg_id,
462            "Starting Public Share Distribution"
463        );
464        let dkg_begin = DkgBegin {
465            dkg_id: self.current_dkg_id,
466        };
467        let dkg_begin_packet = Packet {
468            sig: dkg_begin
469                .sign(&self.config.message_private_key)
470                .expect("Failed to sign DkgBegin"),
471            msg: Message::DkgBegin(dkg_begin),
472        };
473
474        self.move_to(State::DkgPublicGather)?;
475        self.dkg_public_start = Some(Instant::now());
476        Ok(dkg_begin_packet)
477    }
478
479    /// Ask signers to send DKG private shares
480    pub fn start_private_shares(&mut self) -> Result<Packet, Error> {
481        // only wait for signers that returned DkgPublicShares
482        self.dkg_wait_signer_ids = self
483            .dkg_public_shares
484            .keys()
485            .cloned()
486            .collect::<HashSet<u32>>();
487        info!(
488            dkg_id = %self.current_dkg_id,
489            "Starting Private Share Distribution"
490        );
491
492        let dkg_begin = DkgPrivateBegin {
493            dkg_id: self.current_dkg_id,
494            signer_ids: self.dkg_public_shares.keys().cloned().collect(),
495            key_ids: vec![],
496        };
497        let dkg_private_begin_msg = Packet {
498            sig: dkg_begin
499                .sign(&self.config.message_private_key)
500                .expect("Failed to sign DkgPrivateBegin"),
501            msg: Message::DkgPrivateBegin(dkg_begin),
502        };
503        self.move_to(State::DkgPrivateGather)?;
504        self.dkg_private_start = Some(Instant::now());
505        Ok(dkg_private_begin_msg)
506    }
507
508    /// Ask signers to compute shares and send DKG end
509    pub fn start_dkg_end(&mut self) -> Result<Packet, Error> {
510        // only wait for signers that returned DkgPublicShares
511        self.dkg_wait_signer_ids = self
512            .dkg_private_shares
513            .keys()
514            .cloned()
515            .collect::<HashSet<u32>>();
516        info!(
517            dkg_id = %self.current_dkg_id,
518            "Starting DkgEnd Distribution"
519        );
520
521        let dkg_end_begin = DkgEndBegin {
522            dkg_id: self.current_dkg_id,
523            signer_ids: self.dkg_private_shares.keys().cloned().collect(),
524            key_ids: vec![],
525        };
526        let dkg_end_begin_msg = Packet {
527            sig: dkg_end_begin
528                .sign(&self.config.message_private_key)
529                .expect("Failed to sign DkgPrivateBegin"),
530            msg: Message::DkgEndBegin(dkg_end_begin),
531        };
532        self.move_to(State::DkgEndGather)?;
533        self.dkg_end_start = Some(Instant::now());
534        Ok(dkg_end_begin_msg)
535    }
536
537    fn gather_public_shares(&mut self, packet: &Packet) -> Result<(), Error> {
538        if let Message::DkgPublicShares(dkg_public_shares) = &packet.msg {
539            if dkg_public_shares.dkg_id != self.current_dkg_id {
540                return Err(Error::BadDkgId(
541                    dkg_public_shares.dkg_id,
542                    self.current_dkg_id,
543                ));
544            }
545
546            // check that the signer_id exists in the config
547            let signer_public_keys = &self.config.public_keys.signers;
548            if !signer_public_keys.contains_key(&dkg_public_shares.signer_id) {
549                warn!(signer_id = %dkg_public_shares.signer_id, "No public key in config");
550                return Ok(());
551            };
552
553            let have_shares = self
554                .dkg_public_shares
555                .contains_key(&dkg_public_shares.signer_id);
556
557            if have_shares {
558                info!(signer_id = %dkg_public_shares.signer_id, "received duplicate DkgPublicShares");
559                return Ok(());
560            }
561
562            let waiting = self
563                .dkg_wait_signer_ids
564                .remove(&dkg_public_shares.signer_id);
565
566            if waiting {
567                self.dkg_public_shares
568                    .insert(dkg_public_shares.signer_id, dkg_public_shares.clone());
569                debug!(
570                    dkg_id = %dkg_public_shares.dkg_id,
571                    signer_id = %dkg_public_shares.signer_id,
572                    "DkgPublicShares received"
573                );
574            } else {
575                warn!(
576                    dkg_id = %dkg_public_shares.dkg_id,
577                    signer_id = %dkg_public_shares.signer_id,
578                    "Got DkgPublicShares from signer who we weren't waiting on"
579                );
580            }
581        }
582
583        if self.dkg_wait_signer_ids.is_empty() {
584            self.public_shares_gathered()?;
585        }
586        Ok(())
587    }
588
589    fn public_shares_gathered(&mut self) -> Result<(), Error> {
590        self.move_to(State::DkgPublicSharesDoneDistribute)?;
591        Ok(())
592    }
593
594    /// Notify signers that all public shares have been received
595    pub fn send_public_shares_done(&mut self) -> Result<Packet, Error> {
596        let signer_ids: Vec<u32> = self.dkg_public_shares.keys().cloned().collect();
597        self.dkg_wait_signer_ids = signer_ids.iter().cloned().collect();
598        info!(dkg_id = %self.current_dkg_id, "Sending DkgPublicSharesDone");
599        let msg = DkgPublicSharesDone {
600            dkg_id: self.current_dkg_id,
601            signer_ids,
602        };
603        let packet = Packet {
604            sig: msg
605                .sign(&self.config.message_private_key)
606                .expect("Failed to sign DkgPublicSharesDone"),
607            msg: Message::DkgPublicSharesDone(msg),
608        };
609        self.move_to(State::DkgPublicSharesDoneGather)?;
610        self.dkg_public_start = Some(Instant::now());
611        Ok(packet)
612    }
613
614    fn gather_public_shares_done_ack(&mut self, packet: &Packet) -> Result<(), Error> {
615        if let Message::DkgPublicSharesDoneAck(ack) = &packet.msg {
616            if ack.dkg_id != self.current_dkg_id {
617                return Err(Error::BadDkgId(ack.dkg_id, self.current_dkg_id));
618            }
619            if !self.config.public_keys.signers.contains_key(&ack.signer_id) {
620                warn!(signer_id = %ack.signer_id, "No public key in config");
621                return Ok(());
622            }
623            self.dkg_wait_signer_ids.remove(&ack.signer_id);
624            debug!(
625                dkg_id = %ack.dkg_id,
626                signer_id = %ack.signer_id,
627                "DkgPublicSharesDoneAck received"
628            );
629        }
630        if self.dkg_wait_signer_ids.is_empty() {
631            self.move_to(State::DkgPrivateDistribute)?;
632        }
633        Ok(())
634    }
635
636    fn gather_private_shares(&mut self, packet: &Packet) -> Result<(), Error> {
637        if let Message::DkgPrivateShares(dkg_private_shares) = &packet.msg {
638            if dkg_private_shares.dkg_id != self.current_dkg_id {
639                return Err(Error::BadDkgId(
640                    dkg_private_shares.dkg_id,
641                    self.current_dkg_id,
642                ));
643            }
644
645            // check that the signer_id exists in the config
646            let signer_public_keys = &self.config.public_keys.signers;
647            if !signer_public_keys.contains_key(&dkg_private_shares.signer_id) {
648                warn!(signer_id = %dkg_private_shares.signer_id, "No public key in config");
649                return Ok(());
650            };
651
652            let has_received_shares = self
653                .dkg_private_shares
654                .contains_key(&dkg_private_shares.signer_id);
655            if has_received_shares {
656                info!(signer_id = %dkg_private_shares.signer_id, "received duplicate DkgPrivateShares");
657                return Ok(());
658            }
659
660            let waiting = self
661                .dkg_wait_signer_ids
662                .remove(&dkg_private_shares.signer_id);
663
664            if waiting {
665                self.dkg_private_shares
666                    .insert(dkg_private_shares.signer_id, dkg_private_shares.clone());
667                info!(
668                    dkg_id = %dkg_private_shares.dkg_id,
669                    signer_id = %dkg_private_shares.signer_id,
670                    "DkgPrivateShares received"
671                );
672            } else {
673                warn!(
674                    dkg_id = %dkg_private_shares.dkg_id,
675                    signer_id = %dkg_private_shares.signer_id,
676                    "Got DkgPrivateShares from signer who we weren't waiting on"
677                );
678            }
679        }
680
681        if self.dkg_wait_signer_ids.is_empty() {
682            self.private_shares_gathered()?;
683        }
684        Ok(())
685    }
686
687    fn private_shares_gathered(&mut self) -> Result<(), Error> {
688        self.move_to(State::DkgPrivateSharesDoneDistribute)?;
689        Ok(())
690    }
691
692    /// Notify signers that all private shares have been received
693    pub fn send_private_shares_done(&mut self) -> Result<Packet, Error> {
694        let signer_ids: Vec<u32> = self.dkg_private_shares.keys().cloned().collect();
695        self.dkg_wait_signer_ids = signer_ids.iter().cloned().collect();
696        info!(dkg_id = %self.current_dkg_id, "Sending DkgPrivateSharesDone");
697        let msg = DkgPrivateSharesDone {
698            dkg_id: self.current_dkg_id,
699            signer_ids,
700        };
701        let packet = Packet {
702            sig: msg
703                .sign(&self.config.message_private_key)
704                .expect("Failed to sign DkgPrivateSharesDone"),
705            msg: Message::DkgPrivateSharesDone(msg),
706        };
707        self.move_to(State::DkgPrivateSharesDoneGather)?;
708        self.dkg_private_start = Some(Instant::now());
709        Ok(packet)
710    }
711
712    fn gather_private_shares_done_ack(&mut self, packet: &Packet) -> Result<(), Error> {
713        if let Message::DkgPrivateSharesDoneAck(ack) = &packet.msg {
714            if ack.dkg_id != self.current_dkg_id {
715                return Err(Error::BadDkgId(ack.dkg_id, self.current_dkg_id));
716            }
717            if !self.config.public_keys.signers.contains_key(&ack.signer_id) {
718                warn!(signer_id = %ack.signer_id, "No public key in config");
719                return Ok(());
720            }
721            self.dkg_wait_signer_ids.remove(&ack.signer_id);
722            debug!(
723                dkg_id = %ack.dkg_id,
724                signer_id = %ack.signer_id,
725                "DkgPrivateSharesDoneAck received"
726            );
727        }
728        if self.dkg_wait_signer_ids.is_empty() {
729            self.move_to(State::DkgEndDistribute)?;
730        }
731        Ok(())
732    }
733
734    fn gather_dkg_end(&mut self, packet: &Packet) -> Result<(), Error> {
735        debug!(
736            "DKG Round {}: waiting for Dkg End from signers {:?}",
737            self.current_dkg_id, self.dkg_wait_signer_ids
738        );
739        if let Message::DkgEnd(dkg_end) = &packet.msg {
740            if dkg_end.dkg_id != self.current_dkg_id {
741                return Err(Error::BadDkgId(dkg_end.dkg_id, self.current_dkg_id));
742            }
743            if self.dkg_wait_signer_ids.contains(&dkg_end.signer_id) {
744                self.dkg_wait_signer_ids.remove(&dkg_end.signer_id);
745                self.dkg_end_messages
746                    .insert(dkg_end.signer_id, dkg_end.clone());
747                debug!(
748                    dkg_id = %dkg_end.dkg_id,
749                    signer_id = %dkg_end.signer_id,
750                    waiting = ?self.dkg_wait_signer_ids,
751                    "DkgEnd received"
752                );
753            } else {
754                warn!(
755                    dkg_id = %dkg_end.dkg_id,
756                    signer_id = %dkg_end.signer_id,
757                    "Got DkgEnd from signer who we weren't waiting on"
758                );
759            }
760        }
761
762        let mut reported_failures = HashMap::new();
763        // this will be used to report signers who were malicious in this DKG round, as opposed to
764        // self.malicious_dkg_signer_ids which contains all DKG signers who were ever malicious
765        let mut malicious_signers = HashSet::new();
766        let threshold: usize = self
767            .config
768            .threshold
769            .try_into()
770            .map_err(Error::TryFromInt)?;
771        if self.dkg_wait_signer_ids.is_empty() {
772            // if there are any errors, mark signers malicious and retry
773            for (signer_id, dkg_end) in &self.dkg_end_messages {
774                if let DkgStatus::Failure(dkg_failure) = &dkg_end.status {
775                    warn!(%signer_id, ?dkg_failure, "DkgEnd failure");
776                    reported_failures.insert(*signer_id, dkg_failure.clone());
777
778                    match dkg_failure {
779                        DkgFailure::BadState => {
780                            // signer should not be in a bad state so treat as malicious
781                            malicious_signers.insert(*signer_id);
782                        }
783                        DkgFailure::Threshold => {
784                            // this shouldn't happen, maybe mark signer malicious?
785                        }
786                        DkgFailure::BadPublicShares(bad_shares) => {
787                            // bad_shares is a set of signer_ids
788                            for bad_signer_id in bad_shares {
789                                // verify public shares are bad
790                                let Some(dkg_public_shares) =
791                                    self.dkg_public_shares.get(bad_signer_id)
792                                else {
793                                    warn!("Signer {signer_id} reported BadPublicShares from {bad_signer_id} but there are no public shares from that signer, mark {signer_id} as malicious");
794                                    malicious_signers.insert(*signer_id);
795                                    continue;
796                                };
797                                let mut bad_party_ids = Vec::new();
798                                for (party_id, comm) in &dkg_public_shares.comms {
799                                    if !check_public_shares(
800                                        comm,
801                                        threshold,
802                                        &self.current_dkg_id.to_be_bytes(),
803                                    ) {
804                                        bad_party_ids.push(party_id);
805                                    }
806                                }
807
808                                // if none of the shares were bad sender was malicious
809                                if bad_party_ids.is_empty() {
810                                    warn!("Signer {signer_id} reported BadPublicShares from {bad_signer_id} but the shares were valid, mark {signer_id} as malicious");
811                                    malicious_signers.insert(*signer_id);
812                                } else {
813                                    warn!("Signer {signer_id} reported BadPublicShares from {bad_signer_id}, mark {bad_signer_id} as malicious");
814                                    malicious_signers.insert(*bad_signer_id);
815                                }
816                            }
817                        }
818                        DkgFailure::BadPrivateShares(bad_shares) => {
819                            // bad_shares is a map of signer_id to BadPrivateShare
820                            for (bad_signer_id, bad_private_share) in bad_shares {
821                                // verify the DH tuple proof first so we know the shared key is correct
822                                let Some(signer_key_ids) =
823                                    self.config.public_keys.signer_key_ids.get(signer_id)
824                                else {
825                                    warn!("No key IDs for signer_id {signer_id} DkgEnd");
826                                    continue;
827                                };
828                                let Some(signer_public_shares) =
829                                    self.dkg_public_shares.get(signer_id)
830                                else {
831                                    warn!("Signer {signer_id} reported BadPrivateShares from {bad_signer_id} but there are no public shares from {signer_id}");
832                                    continue;
833                                };
834                                let signer_public_key = signer_public_shares.kex_public_key;
835
836                                let Some(bad_signer_public_shares) =
837                                    self.dkg_public_shares.get(bad_signer_id)
838                                else {
839                                    warn!("Signer {signer_id} reported BadPrivateShares from {bad_signer_id} but there are no public shares from {bad_signer_id}, mark {signer_id} as malicious");
840                                    malicious_signers.insert(*signer_id);
841                                    continue;
842                                };
843                                let bad_signer_public_key = bad_signer_public_shares.kex_public_key;
844
845                                let mut is_bad = false;
846
847                                if bad_private_share.tuple_proof.verify(
848                                    &signer_public_key,
849                                    &bad_signer_public_key,
850                                    &bad_private_share.shared_key,
851                                ) {
852                                    // verify at least one bad private share for one of signer_id's key_ids
853                                    let shared_secret =
854                                        make_shared_secret_from_key(&bad_private_share.shared_key);
855
856                                    let polys = bad_signer_public_shares
857                                        .comms
858                                        .iter()
859                                        .cloned()
860                                        .collect::<HashMap<u32, PolyCommitment>>();
861                                    let Some(dkg_private_shares) =
862                                        self.dkg_private_shares.get(bad_signer_id)
863                                    else {
864                                        warn!("Signer {signer_id} reported BadPrivateShare from signer {bad_signer_id} who didn't send public shares, mark {signer_id} as malicious");
865                                        malicious_signers.insert(*signer_id);
866                                        continue;
867                                    };
868
869                                    for (src_party_id, key_shares) in &dkg_private_shares.shares {
870                                        let Some(poly) = polys.get(src_party_id) else {
871                                            warn!("Signer {signer_id} reported BadPrivateShares from {bad_signer_id} but the private shares from {bad_signer_id} dont have a polynomial for party {src_party_id}");
872                                            continue;
873                                        };
874                                        for key_id in signer_key_ids {
875                                            let Some(bytes) = key_shares.get(key_id) else {
876                                                warn!("DkgPrivateShares from party_id {src_party_id} did not include a share for key_id {key_id}");
877                                                continue;
878                                            };
879                                            match decrypt(&shared_secret, bytes) {
880                                                Ok(plain) => match Scalar::try_from(&plain[..]) {
881                                                    Ok(private_eval) => {
882                                                        let poly_eval = match compute::poly(
883                                                            &compute::id(*key_id),
884                                                            &poly.poly,
885                                                        ) {
886                                                            Ok(p) => p,
887                                                            Err(e) => {
888                                                                warn!("Failed to evaluate public poly from signer_id {bad_signer_id} to key_id {key_id}: {e:?}");
889                                                                is_bad = true;
890                                                                break;
891                                                            }
892                                                        };
893
894                                                        if private_eval * G != poly_eval {
895                                                            warn!("Invalid dkg private share from signer_id {bad_signer_id} to key_id {key_id}");
896
897                                                            is_bad = true;
898                                                            break;
899                                                        }
900                                                    }
901                                                    Err(e) => {
902                                                        warn!("Failed to parse Scalar for dkg private share from signer_id {bad_signer_id} to key_id {key_id}: {e:?}");
903
904                                                        is_bad = true;
905                                                        break;
906                                                    }
907                                                },
908                                                Err(e) => {
909                                                    warn!("Failed to decrypt dkg private share from signer_id {bad_signer_id} to key_id {key_id}: {e:?}");
910                                                    is_bad = true;
911                                                    break;
912                                                }
913                                            }
914                                        }
915                                    }
916                                } else {
917                                    warn!("TupleProof failed to verify, mark {signer_id} as malicious");
918                                    is_bad = false;
919                                }
920
921                                // if tuple proof failed or none of the shares were bad sender was malicious
922                                if !is_bad {
923                                    warn!("Signer {signer_id} reported BadPrivateShare from {bad_signer_id} but the shares were valid, mark {signer_id} as malicious");
924                                    malicious_signers.insert(*signer_id);
925                                } else {
926                                    warn!("Signer {signer_id} reported BadPrivateShare from {bad_signer_id}, mark {bad_signer_id} as malicious");
927                                    malicious_signers.insert(*bad_signer_id);
928                                }
929                            }
930                        }
931                        DkgFailure::MissingPublicShares(_) => {
932                            // this shouldn't happen, maybe mark signer malicious?
933                        }
934                        DkgFailure::MissingPrivateShares(_) => {
935                            // this shouldn't happen, maybe mark signer malicious?
936                        }
937                    }
938                }
939            }
940
941            for id in &malicious_signers {
942                self.malicious_dkg_signer_ids.insert(*id);
943            }
944
945            if reported_failures.is_empty() {
946                debug!("no dkg failures");
947                self.dkg_end_gathered()?;
948            } else {
949                // TODO: see if we have sufficient non-malicious signers to continue
950                warn!("got dkg failures");
951                return Err(Error::DkgFailure {
952                    reported_failures,
953                    malicious_signers,
954                });
955            }
956        }
957        Ok(())
958    }
959
960    fn dkg_end_gathered(&mut self) -> Result<(), Error> {
961        // Cache the polynomials used in DKG for the aggregator
962        for signer_id in self.dkg_private_shares.keys() {
963            if let Some(dkg_public_shares) = &self.dkg_public_shares.get(signer_id) {
964                for (party_id, comm) in &dkg_public_shares.comms {
965                    self.party_polynomials.insert(*party_id, comm.clone());
966                }
967            } else {
968                error!(
969                    signer_id = %signer_id,
970                    "No DkgPublicShares from signer who sent DkgPrivateShares"
971                );
972                return Err(Error::NoPublicSharesForSigner(*signer_id));
973            }
974        }
975
976        // Final sanity check on PolyComitments
977        let threshold: usize = self
978            .config
979            .threshold
980            .try_into()
981            .map_err(Error::TryFromInt)?;
982        let mut bad_ids = Vec::new();
983        for (party_id, comm) in &self.party_polynomials {
984            if !check_public_shares(comm, threshold, &self.current_dkg_id.to_be_bytes()) {
985                bad_ids.push(compute::id(*party_id));
986            }
987        }
988
989        if !bad_ids.is_empty() {
990            return Err(Error::Aggregator(AggregatorError::BadPolyCommitments(
991                bad_ids,
992            )));
993        }
994
995        // Calculate the aggregate public key
996        let key = self
997            .dkg_end_messages
998            .keys()
999            .flat_map(|signer_id| {
1000                if let Some(dkg_public_shares) = self.dkg_public_shares.get(signer_id) {
1001                    dkg_public_shares.comms.clone()
1002                } else {
1003                    warn!(
1004                        signer_id = %signer_id,
1005                        "No DkgPublicShares from signer who sent DkgEnd"
1006                    );
1007                    vec![]
1008                }
1009            })
1010            .fold(Point::default(), |s, (_, comm)| {
1011                if let Some(p) = comm.poly.first() {
1012                    s + p
1013                } else {
1014                    warn!("Empty polynomial when computing aggregate public key");
1015                    s
1016                }
1017            });
1018
1019        info!("Aggregate public key: {key}");
1020        self.aggregate_public_key = Some(key);
1021        self.move_to(State::Idle)
1022    }
1023
1024    fn request_nonces(&mut self, signature_type: SignatureType) -> Result<Packet, Error> {
1025        self.message_nonces.clear();
1026        self.current_sign_iter_id = self.current_sign_iter_id.wrapping_add(1);
1027        info!(
1028            sign_id = %self.current_sign_id,
1029            sign_iter_id = %self.current_sign_iter_id,
1030            "Requesting Nonces"
1031        );
1032        let nonce_request = NonceRequest {
1033            dkg_id: self.current_dkg_id,
1034            sign_id: self.current_sign_id,
1035            sign_iter_id: self.current_sign_iter_id,
1036            message: self.message.clone(),
1037            signature_type,
1038        };
1039        let nonce_request_msg = Packet {
1040            sig: nonce_request
1041                .sign(&self.config.message_private_key)
1042                .expect("Failed to sign NonceRequest"),
1043            msg: Message::NonceRequest(nonce_request),
1044        };
1045        self.move_to(State::NonceGather(signature_type))?;
1046        self.nonce_start = Some(Instant::now());
1047
1048        Ok(nonce_request_msg)
1049    }
1050
1051    fn gather_nonces(
1052        &mut self,
1053        packet: &Packet,
1054        signature_type: SignatureType,
1055    ) -> Result<(), Error> {
1056        if let Message::NonceResponse(nonce_response) = &packet.msg {
1057            if nonce_response.dkg_id != self.current_dkg_id {
1058                return Err(Error::BadDkgId(nonce_response.dkg_id, self.current_dkg_id));
1059            }
1060            if nonce_response.sign_id != self.current_sign_id {
1061                return Err(Error::BadSignId(
1062                    nonce_response.sign_id,
1063                    self.current_sign_id,
1064                ));
1065            }
1066            if nonce_response.sign_iter_id != self.current_sign_iter_id {
1067                return Err(Error::BadSignIterId(
1068                    nonce_response.sign_iter_id,
1069                    self.current_sign_iter_id,
1070                ));
1071            }
1072
1073            // check that the signer_id exists in the config
1074            let signer_public_keys = &self.config.public_keys.signers;
1075            if !signer_public_keys.contains_key(&nonce_response.signer_id) {
1076                warn!(signer_id = %nonce_response.signer_id, "No public key in config");
1077                return Ok(());
1078            };
1079
1080            // check that the signer participated in the current DKG round
1081            if !self
1082                .dkg_end_messages
1083                .contains_key(&nonce_response.signer_id)
1084            {
1085                warn!(signer_id = %nonce_response.signer_id, "NonceResponse rejected: signer not a DKG participant");
1086                return Ok(());
1087            }
1088
1089            // check that the key_ids match the config
1090            let Some(signer_key_ids) = self
1091                .config
1092                .public_keys
1093                .signer_key_ids
1094                .get(&nonce_response.signer_id)
1095            else {
1096                warn!(signer_id = %nonce_response.signer_id, "No keys IDs configured");
1097                return Ok(());
1098            };
1099
1100            let nonce_response_key_ids = nonce_response
1101                .key_ids
1102                .iter()
1103                .cloned()
1104                .collect::<HashSet<u32>>();
1105            if *signer_key_ids != nonce_response_key_ids {
1106                warn!(signer_id = %nonce_response.signer_id, "Nonce response key_ids didn't match config");
1107                return Ok(());
1108            }
1109
1110            for nonce in &nonce_response.nonces {
1111                if !nonce.is_valid() {
1112                    warn!(
1113                        sign_id = %nonce_response.sign_id,
1114                        sign_iter_id = %nonce_response.sign_iter_id,
1115                        signer_id = %nonce_response.signer_id,
1116                        "Received invalid nonce in NonceResponse"
1117                    );
1118                    return Ok(());
1119                }
1120            }
1121
1122            if self
1123                .malicious_signer_ids
1124                .contains(&nonce_response.signer_id)
1125            {
1126                warn!(
1127                    sign_id = %nonce_response.sign_id,
1128                    sign_iter_id = %nonce_response.sign_iter_id,
1129                    signer_id = %nonce_response.signer_id,
1130                    "Received malicious NonceResponse"
1131                );
1132                //return Err(Error::MaliciousSigner(nonce_response.signer_id));
1133                return Ok(());
1134            }
1135
1136            let nonce_info = self
1137                .message_nonces
1138                .entry(nonce_response.message.clone())
1139                .or_default();
1140
1141            let have_nonces = nonce_info
1142                .public_nonces
1143                .contains_key(&nonce_response.signer_id);
1144
1145            if have_nonces {
1146                info!(signer_id = %nonce_response.signer_id, "Received duplicate NonceResponse");
1147                return Ok(());
1148            }
1149
1150            nonce_info
1151                .public_nonces
1152                .insert(nonce_response.signer_id, nonce_response.clone());
1153
1154            // ignore the passed key_ids
1155            for key_id in signer_key_ids {
1156                nonce_info.nonce_recv_key_ids.insert(*key_id);
1157            }
1158
1159            nonce_info
1160                .sign_wait_signer_ids
1161                .insert(nonce_response.signer_id);
1162            // Because of entry call, it is safe to unwrap here
1163            info!(
1164                sign_id = %nonce_response.sign_id,
1165                sign_iter_id = %nonce_response.sign_iter_id,
1166                signer_id = %nonce_response.signer_id,
1167                recv_keys = %nonce_info.nonce_recv_key_ids.len(),
1168                threshold = %self.config.threshold,
1169                "Received NonceResponse"
1170            );
1171            if nonce_info.nonce_recv_key_ids.len() >= self.config.sign_threshold as usize {
1172                // We have a winning message!
1173                self.message.clone_from(&nonce_response.message);
1174                let aggregate_nonce = self.compute_aggregate_nonce()?;
1175                info!("Aggregate nonce: {aggregate_nonce}");
1176
1177                self.move_to(State::SigShareRequest(signature_type))?;
1178            }
1179        }
1180        Ok(())
1181    }
1182
1183    fn request_sig_shares(&mut self, signature_type: SignatureType) -> Result<Packet, Error> {
1184        self.signature_shares.clear();
1185        info!(
1186            sign_id = %self.current_sign_id,
1187            "Requesting Signature Shares"
1188        );
1189        let nonce_responses = self
1190            .message_nonces
1191            .get(&self.message)
1192            .ok_or(Error::MissingMessageNonceInfo)?
1193            .public_nonces
1194            .values()
1195            .cloned()
1196            .collect::<Vec<NonceResponse>>();
1197        let sig_share_request = SignatureShareRequest {
1198            dkg_id: self.current_dkg_id,
1199            sign_id: self.current_sign_id,
1200            sign_iter_id: self.current_sign_iter_id,
1201            nonce_responses,
1202            message: self.message.clone(),
1203            signature_type,
1204        };
1205        let sig_share_request_msg = Packet {
1206            sig: sig_share_request
1207                .sign(&self.config.message_private_key)
1208                .expect("Failed to sign SignatureShareRequest"),
1209            msg: Message::SignatureShareRequest(sig_share_request),
1210        };
1211        self.move_to(State::SigShareGather(signature_type))?;
1212        self.sign_start = Some(Instant::now());
1213
1214        Ok(sig_share_request_msg)
1215    }
1216
1217    fn gather_sig_shares(
1218        &mut self,
1219        packet: &Packet,
1220        signature_type: SignatureType,
1221    ) -> Result<(), Error> {
1222        let Message::SignatureShareResponse(sig_share_response) = &packet.msg else {
1223            return Ok(());
1224        };
1225
1226        let Some(response_info) = self.message_nonces.get_mut(&self.message) else {
1227            warn!(
1228                "Sign round {} SignatureShareResponse for round {} from signer {} no message nonces entry",
1229                self.current_sign_id, sig_share_response.sign_id, sig_share_response.signer_id,
1230            );
1231            return Ok(());
1232        };
1233
1234        let waiting = response_info
1235            .sign_wait_signer_ids
1236            .contains(&sig_share_response.signer_id);
1237
1238        if !waiting {
1239            warn!(
1240                "Sign round {} SignatureShareResponse for round {} from signer {} not in the wait list",
1241                self.current_sign_id, sig_share_response.sign_id, sig_share_response.signer_id,
1242            );
1243            return Ok(());
1244        }
1245
1246        if sig_share_response.dkg_id != self.current_dkg_id {
1247            return Err(Error::BadDkgId(
1248                sig_share_response.dkg_id,
1249                self.current_dkg_id,
1250            ));
1251        }
1252        if sig_share_response.sign_id != self.current_sign_id {
1253            return Err(Error::BadSignId(
1254                sig_share_response.sign_id,
1255                self.current_sign_id,
1256            ));
1257        }
1258
1259        // we were waiting on you, and you sent a packet for this sign round, so we won't take
1260        // another packet from you
1261        response_info
1262            .sign_wait_signer_ids
1263            .remove(&sig_share_response.signer_id);
1264
1265        // check that the signer_id exists in the config
1266        let signer_public_keys = &self.config.public_keys.signers;
1267        if !signer_public_keys.contains_key(&sig_share_response.signer_id) {
1268            warn!(signer_id = %sig_share_response.signer_id, "No public key in config");
1269            return Err(Error::MissingPublicKeyForSigner(
1270                sig_share_response.signer_id,
1271            ));
1272        };
1273
1274        // check that the signer participated in the current DKG round
1275        if !self
1276            .dkg_end_messages
1277            .contains_key(&sig_share_response.signer_id)
1278        {
1279            warn!(signer_id = %sig_share_response.signer_id, "SignatureShareResponse rejected: signer not a DKG participant");
1280            return Ok(());
1281        }
1282
1283        // check that the key_ids match the config
1284        let Some(signer_key_ids) = self
1285            .config
1286            .public_keys
1287            .signer_key_ids
1288            .get(&sig_share_response.signer_id)
1289        else {
1290            warn!(signer_id = %sig_share_response.signer_id, "No keys IDs configured");
1291            return Err(Error::MissingKeyIDsForSigner(sig_share_response.signer_id));
1292        };
1293
1294        let mut sig_share_response_key_ids = HashSet::new();
1295        for sig_share in &sig_share_response.signature_shares {
1296            for key_id in &sig_share.key_ids {
1297                sig_share_response_key_ids.insert(*key_id);
1298            }
1299        }
1300
1301        if *signer_key_ids != sig_share_response_key_ids {
1302            warn!(signer_id = %sig_share_response.signer_id, "SignatureShareResponse key_ids didn't match config");
1303            return Err(Error::BadKeyIDsForSigner(sig_share_response.signer_id));
1304        }
1305
1306        let have_shares = self
1307            .signature_shares
1308            .contains_key(&sig_share_response.signer_id);
1309
1310        if have_shares {
1311            info!(signer_id = %sig_share_response.signer_id, "received duplicate SignatureShareResponse");
1312            // XXX should this be an error?  We should have already removed signer from wait set
1313            return Ok(());
1314        }
1315
1316        self.signature_shares.insert(
1317            sig_share_response.signer_id,
1318            sig_share_response.signature_shares.clone(),
1319        );
1320
1321        for sig_share in &sig_share_response.signature_shares {
1322            for key_id in &sig_share.key_ids {
1323                response_info.sign_recv_key_ids.insert(*key_id);
1324            }
1325        }
1326
1327        debug!(
1328            "Sign round {} SignatureShareResponse for round {} from signer {} ({}/{} key_ids). Waiting on {:?}",
1329            self.current_sign_id,
1330            sig_share_response.sign_id,
1331            sig_share_response.signer_id,
1332            response_info.sign_recv_key_ids.len(),
1333            response_info.nonce_recv_key_ids.len(),
1334            response_info.sign_wait_signer_ids
1335        );
1336
1337        let message_nonce = self
1338            .message_nonces
1339            .get(&self.message)
1340            .ok_or(Error::MissingMessageNonceInfo)?;
1341        if message_nonce.sign_wait_signer_ids.is_empty() {
1342            // Calculate the aggregate signature
1343            let nonce_responses = message_nonce
1344                .public_nonces
1345                .values()
1346                .cloned()
1347                .collect::<Vec<NonceResponse>>();
1348
1349            let nonces = nonce_responses
1350                .iter()
1351                .flat_map(|nr| nr.nonces.clone())
1352                .collect::<Vec<PublicNonce>>();
1353
1354            let key_ids = nonce_responses
1355                .iter()
1356                .flat_map(|nr| nr.key_ids.clone())
1357                .collect::<Vec<u32>>();
1358
1359            let shares = message_nonce
1360                .public_nonces
1361                .keys()
1362                .flat_map(|i| {
1363                    if let Some(shares) = self.signature_shares.get(i) {
1364                        shares.clone()
1365                    } else {
1366                        warn!(sign_id = %self.current_sign_id, signer_id = %i, "Have nonces but no signature shares from signer");
1367                        vec![]
1368                    }
1369                })
1370                .collect::<Vec<SignatureShare>>();
1371
1372            debug!(
1373                "aggregator.sign({}, {:?}, {:?}, {})",
1374                bs58::encode(&self.message).into_string(),
1375                nonces.len(),
1376                shares.len(),
1377                self.party_polynomials.len(),
1378            );
1379
1380            self.aggregator.init(&self.party_polynomials)?;
1381
1382            if let SignatureType::Taproot(merkle_root) = signature_type {
1383                let schnorr_proof = self.aggregator.sign_taproot(
1384                    &self.message,
1385                    &nonces,
1386                    &shares,
1387                    &key_ids,
1388                    merkle_root,
1389                )?;
1390                debug!("SchnorrProof ({}, {})", schnorr_proof.r, schnorr_proof.s);
1391                self.schnorr_proof = Some(schnorr_proof);
1392            } else if let SignatureType::Schnorr = signature_type {
1393                let schnorr_proof =
1394                    self.aggregator
1395                        .sign_schnorr(&self.message, &nonces, &shares, &key_ids)?;
1396                debug!("SchnorrProof ({}, {})", schnorr_proof.r, schnorr_proof.s);
1397                self.schnorr_proof = Some(schnorr_proof);
1398            } else {
1399                let signature = self
1400                    .aggregator
1401                    .sign(&self.message, &nonces, &shares, &key_ids)?;
1402                debug!("Signature ({}, {})", signature.R, signature.z);
1403                self.signature = Some(signature);
1404            }
1405
1406            self.move_to(State::Idle)?;
1407        }
1408        Ok(())
1409    }
1410
1411    #[allow(non_snake_case)]
1412    fn compute_aggregate_nonce(&self) -> Result<Point, Error> {
1413        // XXX this needs to be key_ids for v1 and signer_ids for v2
1414        let public_nonces = self
1415            .message_nonces
1416            .get(&self.message)
1417            .cloned()
1418            .unwrap_or_default()
1419            .public_nonces;
1420        let party_ids = public_nonces
1421            .values()
1422            .cloned()
1423            .flat_map(|pn| pn.key_ids)
1424            .collect::<Vec<u32>>();
1425        let nonces = public_nonces
1426            .values()
1427            .cloned()
1428            .flat_map(|pn| pn.nonces)
1429            .collect::<Vec<PublicNonce>>();
1430
1431        let Some(group_key) = self.aggregate_public_key else {
1432            return Err(Error::MissingAggregatePublicKey);
1433        };
1434        let (_, aggregate_nonce) =
1435            compute::intermediate(&self.message, group_key, &party_ids, &nonces);
1436
1437        Ok(aggregate_nonce)
1438    }
1439
1440    fn compute_num_key_ids<'a, I>(&self, signer_ids: I) -> Result<u32, Error>
1441    where
1442        I: Iterator<Item = &'a u32>,
1443    {
1444        signer_ids
1445            .map(
1446                |signer_id| match self.config.public_keys.signer_key_ids.get(signer_id) {
1447                    Some(key_ids) => key_ids.len(),
1448                    None => {
1449                        error!("No key_ids for signer {signer_id}");
1450                        0usize
1451                    }
1452                },
1453            )
1454            .sum::<usize>()
1455            .try_into()
1456            .map_err(Error::TryFromInt)
1457    }
1458
1459    fn compute_dkg_public_size(&self) -> Result<u32, Error> {
1460        self.compute_num_key_ids(self.dkg_public_shares.keys())
1461    }
1462
1463    fn compute_dkg_private_size(&self) -> Result<u32, Error> {
1464        self.compute_num_key_ids(self.dkg_private_shares.keys())
1465    }
1466}
1467
1468impl<Aggregator: AggregatorTrait> StateMachine<State, Error> for Coordinator<Aggregator> {
1469    fn move_to(&mut self, state: State) -> Result<(), Error> {
1470        self.can_move_to(&state)?;
1471        self.state = state;
1472        Ok(())
1473    }
1474
1475    fn can_move_to(&self, state: &State) -> Result<(), Error> {
1476        let prev_state = &self.state;
1477        let accepted = match state {
1478            State::Idle => true,
1479            State::DkgPublicDistribute => prev_state == &State::Idle,
1480            State::DkgPublicGather => {
1481                prev_state == &State::DkgPublicDistribute || prev_state == &State::DkgPublicGather
1482            }
1483            State::DkgPublicSharesDoneDistribute => prev_state == &State::DkgPublicGather,
1484            State::DkgPublicSharesDoneGather => {
1485                prev_state == &State::DkgPublicSharesDoneDistribute
1486                    || prev_state == &State::DkgPublicSharesDoneGather
1487            }
1488            State::DkgPrivateDistribute => prev_state == &State::DkgPublicSharesDoneGather,
1489            State::DkgPrivateGather => {
1490                prev_state == &State::DkgPrivateDistribute || prev_state == &State::DkgPrivateGather
1491            }
1492            State::DkgPrivateSharesDoneDistribute => prev_state == &State::DkgPrivateGather,
1493            State::DkgPrivateSharesDoneGather => {
1494                prev_state == &State::DkgPrivateSharesDoneDistribute
1495                    || prev_state == &State::DkgPrivateSharesDoneGather
1496            }
1497            State::DkgEndDistribute => prev_state == &State::DkgPrivateSharesDoneGather,
1498            State::DkgEndGather => prev_state == &State::DkgEndDistribute,
1499            State::NonceRequest(signature_type) => {
1500                prev_state == &State::Idle
1501                    || prev_state == &State::DkgEndGather
1502                    || prev_state == &State::SigShareGather(*signature_type)
1503            }
1504            State::NonceGather(signature_type) => {
1505                prev_state == &State::NonceRequest(*signature_type)
1506                    || prev_state == &State::NonceGather(*signature_type)
1507            }
1508            State::SigShareRequest(signature_type) => {
1509                prev_state == &State::NonceGather(*signature_type)
1510            }
1511            State::SigShareGather(signature_type) => {
1512                prev_state == &State::SigShareRequest(*signature_type)
1513                    || prev_state == &State::SigShareGather(*signature_type)
1514            }
1515        };
1516        if accepted {
1517            debug!("state change from {prev_state:?} to {state:?}");
1518            Ok(())
1519        } else {
1520            Err(Error::BadStateChange(format!(
1521                "{prev_state:?} to {state:?}"
1522            )))
1523        }
1524    }
1525}
1526
1527impl<Aggregator: AggregatorTrait> CoordinatorTrait for Coordinator<Aggregator> {
1528    /// Create a new coordinator
1529    fn new(config: Config) -> Self {
1530        Self {
1531            aggregator: Aggregator::new(config.num_keys, config.threshold),
1532            config,
1533            current_dkg_id: 0,
1534            current_sign_id: 0,
1535            current_sign_iter_id: 0,
1536            dkg_public_shares: Default::default(),
1537            dkg_private_shares: Default::default(),
1538            dkg_end_messages: Default::default(),
1539            party_polynomials: Default::default(),
1540            message_nonces: Default::default(),
1541            signature_shares: Default::default(),
1542            aggregate_public_key: None,
1543            signature: None,
1544            schnorr_proof: None,
1545            message: Default::default(),
1546            dkg_wait_signer_ids: Default::default(),
1547            state: State::Idle,
1548            dkg_public_start: None,
1549            dkg_private_start: None,
1550            dkg_end_start: None,
1551            nonce_start: None,
1552            sign_start: None,
1553            malicious_signer_ids: Default::default(),
1554            malicious_dkg_signer_ids: Default::default(),
1555            coordinator_public_key: None,
1556        }
1557    }
1558
1559    fn load(state: &SavedState) -> Self {
1560        Self {
1561            aggregator: Aggregator::new(state.config.num_keys, state.config.threshold),
1562            config: state.config.clone(),
1563            current_dkg_id: state.current_dkg_id,
1564            current_sign_id: state.current_sign_id,
1565            current_sign_iter_id: state.current_sign_iter_id,
1566            dkg_public_shares: state.dkg_public_shares.clone(),
1567            dkg_private_shares: state.dkg_private_shares.clone(),
1568            dkg_end_messages: state.dkg_end_messages.clone(),
1569            party_polynomials: state.party_polynomials.clone(),
1570            message_nonces: state.message_nonces.clone(),
1571            signature_shares: state.signature_shares.clone(),
1572            aggregate_public_key: state.aggregate_public_key,
1573            signature: state.signature.clone(),
1574            schnorr_proof: state.schnorr_proof.clone(),
1575            message: state.message.clone(),
1576            dkg_wait_signer_ids: state.dkg_wait_signer_ids.clone(),
1577            state: state.state.clone(),
1578            dkg_public_start: state.dkg_public_start,
1579            dkg_private_start: state.dkg_private_start,
1580            dkg_end_start: state.dkg_end_start,
1581            nonce_start: state.nonce_start,
1582            sign_start: state.sign_start,
1583            malicious_signer_ids: state.malicious_signer_ids.clone(),
1584            malicious_dkg_signer_ids: state.malicious_dkg_signer_ids.clone(),
1585            coordinator_public_key: state.coordinator_public_key,
1586        }
1587    }
1588
1589    fn save(&self) -> SavedState {
1590        SavedState {
1591            config: self.config.clone(),
1592            current_dkg_id: self.current_dkg_id,
1593            current_sign_id: self.current_sign_id,
1594            current_sign_iter_id: self.current_sign_iter_id,
1595            dkg_public_shares: self.dkg_public_shares.clone(),
1596            dkg_private_shares: self.dkg_private_shares.clone(),
1597            dkg_end_messages: self.dkg_end_messages.clone(),
1598            party_polynomials: self.party_polynomials.clone(),
1599            message_nonces: self.message_nonces.clone(),
1600            signature_shares: self.signature_shares.clone(),
1601            aggregate_public_key: self.aggregate_public_key,
1602            signature: self.signature.clone(),
1603            schnorr_proof: self.schnorr_proof.clone(),
1604            message: self.message.clone(),
1605            dkg_wait_signer_ids: self.dkg_wait_signer_ids.clone(),
1606            state: self.state.clone(),
1607            dkg_public_start: self.dkg_public_start,
1608            dkg_private_start: self.dkg_private_start,
1609            dkg_end_start: self.dkg_end_start,
1610            nonce_start: self.nonce_start,
1611            sign_start: self.sign_start,
1612            malicious_signer_ids: self.malicious_signer_ids.clone(),
1613            malicious_dkg_signer_ids: self.malicious_dkg_signer_ids.clone(),
1614            coordinator_public_key: self.coordinator_public_key,
1615        }
1616    }
1617
1618    /// Retrieve the config
1619    fn get_config(&self) -> Config {
1620        self.config.clone()
1621    }
1622
1623    fn set_coordinator_public_key(&mut self, key: Option<ecdsa::PublicKey>) {
1624        self.coordinator_public_key = key;
1625    }
1626
1627    /// Set the aggregate key and polynomial commitments used to form that key.
1628    ///  Check if the polynomial commitments match the key
1629    fn set_key_and_party_polynomials(
1630        &mut self,
1631        aggregate_key: Point,
1632        party_polynomials: Vec<(u32, PolyCommitment)>,
1633    ) -> Result<(), Error> {
1634        let mut computed_key = Point::default();
1635        let mut bad_poly_commitments = vec![];
1636        for (i, comm) in &party_polynomials {
1637            if let Some(p) = comm.poly.first() {
1638                computed_key += p;
1639            } else {
1640                bad_poly_commitments.push(compute::id(*i));
1641            }
1642        }
1643        if !bad_poly_commitments.is_empty() {
1644            return Err(Error::Aggregator(AggregatorError::BadPolyCommitments(
1645                bad_poly_commitments,
1646            )));
1647        }
1648        if computed_key != aggregate_key {
1649            return Err(Error::AggregateKeyPolynomialMismatch(
1650                computed_key,
1651                aggregate_key,
1652            ));
1653        }
1654        let party_polynomials_len = party_polynomials.len();
1655        let party_polynomials = HashMap::from_iter(party_polynomials);
1656        if party_polynomials.len() != party_polynomials_len {
1657            return Err(Error::DuplicatePartyId);
1658        }
1659        self.aggregate_public_key = Some(aggregate_key);
1660        self.party_polynomials = party_polynomials;
1661        Ok(())
1662    }
1663
1664    /// Retrieve the aggregate public key
1665    fn get_aggregate_public_key(&self) -> Option<Point> {
1666        self.aggregate_public_key
1667    }
1668
1669    /// Set the aggregate public key
1670    fn set_aggregate_public_key(&mut self, aggregate_public_key: Option<Point>) {
1671        self.aggregate_public_key = aggregate_public_key;
1672    }
1673
1674    /// Retrieve the current message bytes being signed
1675    fn get_message(&self) -> Vec<u8> {
1676        self.message.clone()
1677    }
1678
1679    /// Retrive the current state
1680    fn get_state(&self) -> State {
1681        self.state.clone()
1682    }
1683
1684    /// Start a DKG round, with an optional `dkg_id`
1685    fn start_dkg_round(&mut self, dkg_id: Option<u64>) -> Result<Packet, Error> {
1686        if let Some(id) = dkg_id {
1687            self.current_dkg_id = id;
1688        } else {
1689            self.current_dkg_id = self.current_dkg_id.wrapping_add(1);
1690        }
1691
1692        info!("Starting DKG round {}", self.current_dkg_id);
1693        self.move_to(State::DkgPublicDistribute)?;
1694        self.start_public_shares()
1695    }
1696
1697    /// Process the timeouts, and if none of them fire then process the passed packet
1698    /// If a timeout does fire, then the coordinator state has changed; this means the
1699    /// packet is now stale and must be dropped
1700    fn process(
1701        &mut self,
1702        packet: &Packet,
1703    ) -> Result<(Option<Packet>, Option<OperationResult>), Error> {
1704        let (outbound_packet, operation_result) = self.process_timeout()?;
1705        if outbound_packet.is_some() || operation_result.is_some() {
1706            return Ok((outbound_packet, operation_result));
1707        }
1708
1709        self.process_message(packet)
1710    }
1711
1712    /// Start a signing round
1713    fn start_signing_round(
1714        &mut self,
1715        message: &[u8],
1716        signature_type: SignatureType,
1717        sign_id: Option<u64>,
1718    ) -> Result<Packet, Error> {
1719        // We cannot sign if we haven't first set DKG (either manually or via DKG round).
1720        if self.aggregate_public_key.is_none() {
1721            return Err(Error::MissingAggregatePublicKey);
1722        }
1723        self.message = message.to_vec();
1724        if let Some(id) = sign_id {
1725            self.current_sign_id = id;
1726        } else {
1727            self.current_sign_id = self.current_sign_id.wrapping_add(1);
1728        }
1729        info!("Starting signing round {}", self.current_sign_id);
1730        self.move_to(State::NonceRequest(signature_type))?;
1731        self.request_nonces(signature_type)
1732    }
1733
1734    // Reset internal state
1735    fn reset(&mut self) {
1736        self.state = State::Idle;
1737        self.dkg_public_shares.clear();
1738        self.dkg_private_shares.clear();
1739        self.dkg_end_messages.clear();
1740        self.party_polynomials.clear();
1741        self.message_nonces.clear();
1742        self.signature_shares.clear();
1743        self.dkg_wait_signer_ids.clear();
1744        self.nonce_start = None;
1745        self.sign_start = None;
1746    }
1747}
1748
1749#[cfg(test)]
1750/// Test module for coordinator functionality
1751pub mod test {
1752    use super::*;
1753    #[cfg(feature = "with_v1")]
1754    use crate::v1;
1755    use crate::{
1756        curve::{point::Point, scalar::Scalar},
1757        net::{
1758            DkgBegin, DkgFailure, DkgPrivateShares, DkgPublicShares, Message, NonceRequest, Packet,
1759            SignatureShareResponse, SignatureType,
1760        },
1761        schnorr::{self, ID},
1762        state_machine::{
1763            coordinator::{
1764                fire::Coordinator as FireCoordinator,
1765                test::{
1766                    bad_signature_share_request, btc_sign_verify, check_signature_shares,
1767                    coordinator_state_machine, empty_private_shares, empty_public_shares,
1768                    equal_after_save_load, feedback_messages, feedback_mutated_messages,
1769                    gen_nonces, invalid_nonce, new_coordinator, run_dkg_sign, setup,
1770                    setup_with_timeouts, start_dkg_round, start_signing_round, verify_packet_sigs,
1771                },
1772                Config, Coordinator as CoordinatorTrait, State,
1773            },
1774            signer::Signer,
1775            DkgError, OperationResult, SignError,
1776        },
1777        traits::{Aggregator as AggregatorTrait, Signer as SignerTrait},
1778        util::create_rng,
1779        v2,
1780    };
1781    use hashbrown::HashMap;
1782    use std::{slice::from_ref, thread, time::Duration};
1783
1784    #[test]
1785    #[cfg(feature = "with_v1")]
1786    fn new_coordinator_v1() {
1787        new_coordinator::<FireCoordinator<v1::Aggregator>>();
1788    }
1789
1790    #[test]
1791    fn new_coordinator_v2() {
1792        new_coordinator::<FireCoordinator<v2::Aggregator>>();
1793    }
1794
1795    #[test]
1796    #[cfg(feature = "with_v1")]
1797    fn equal_after_save_load_v1() {
1798        equal_after_save_load::<FireCoordinator<v1::Aggregator>, v1::Signer>(2, 2);
1799    }
1800
1801    #[test]
1802    fn equal_after_save_load_v2() {
1803        equal_after_save_load::<FireCoordinator<v2::Aggregator>, v2::Signer>(2, 2);
1804    }
1805
1806    #[test]
1807    #[cfg(feature = "with_v1")]
1808    fn coordinator_state_machine_v1() {
1809        coordinator_state_machine::<FireCoordinator<v1::Aggregator>>();
1810    }
1811
1812    #[test]
1813    fn coordinator_state_machine_v2() {
1814        coordinator_state_machine::<FireCoordinator<v2::Aggregator>>();
1815    }
1816
1817    #[test]
1818    #[cfg(feature = "with_v1")]
1819    fn start_dkg_round_v1() {
1820        start_dkg_round::<FireCoordinator<v1::Aggregator>>(None);
1821        start_dkg_round::<FireCoordinator<v1::Aggregator>>(Some(12345u64));
1822    }
1823
1824    #[test]
1825    fn start_dkg_round_v2() {
1826        start_dkg_round::<FireCoordinator<v2::Aggregator>>(None);
1827        start_dkg_round::<FireCoordinator<v2::Aggregator>>(Some(12345u64));
1828    }
1829
1830    #[test]
1831    #[cfg(feature = "with_v1")]
1832    fn start_signing_round_v1() {
1833        start_signing_round::<FireCoordinator<v1::Aggregator>>(None);
1834        start_signing_round::<FireCoordinator<v1::Aggregator>>(Some(12345u64));
1835    }
1836
1837    #[test]
1838    fn start_signing_round_v2() {
1839        start_signing_round::<FireCoordinator<v2::Aggregator>>(None);
1840        start_signing_round::<FireCoordinator<v2::Aggregator>>(Some(12345u64));
1841    }
1842
1843    #[test]
1844    #[cfg(feature = "with_v1")]
1845    fn dkg_public_share_v1() {
1846        dkg_public_share::<v1::Aggregator, v1::Signer>();
1847    }
1848
1849    #[test]
1850    fn dkg_public_share_v2() {
1851        dkg_public_share::<v2::Aggregator, v2::Signer>();
1852    }
1853
1854    /// test basic insertion and detection of duplicates for DkgPublicShares
1855    fn dkg_public_share<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
1856        let ctx = 0u64.to_be_bytes();
1857        let mut rng = create_rng();
1858        let (coordinators, _) = setup::<FireCoordinator<Aggregator>, Signer>(2, 1);
1859        let mut coordinator: FireCoordinator<Aggregator> = coordinators[0].clone();
1860
1861        coordinator.state = State::DkgPublicGather;
1862        let comms = vec![(
1863            0,
1864            PolyCommitment {
1865                id: ID::new(&Scalar::new(), &Scalar::new(), &ctx, &mut rng),
1866                poly: vec![],
1867            },
1868        )];
1869        let kex_private_key = Scalar::random(&mut rng);
1870        let kex_proof = DkgPublicShares::kex_prove(0, 0, &comms, &kex_private_key, &mut rng);
1871        let public_shares = DkgPublicShares {
1872            dkg_id: 0,
1873            signer_id: 0,
1874            comms: comms.clone(),
1875            kex_public_key: Point::from(kex_private_key),
1876            kex_proof: kex_proof.clone(),
1877        };
1878        let packet = Packet {
1879            msg: Message::DkgPublicShares(public_shares.clone()),
1880            sig: Default::default(),
1881        };
1882
1883        // check that shares are ignored if not waiting on that signer
1884        coordinator.dkg_wait_signer_ids.insert(1);
1885        coordinator.gather_public_shares(&packet).unwrap();
1886        assert_eq!(0, coordinator.dkg_public_shares.len());
1887
1888        coordinator.dkg_wait_signer_ids.insert(0);
1889        coordinator.gather_public_shares(&packet).unwrap();
1890        assert_eq!(1, coordinator.dkg_public_shares.len());
1891
1892        // check that a duplicate public share is ignored even if the state machine is tricked into waiting on it
1893        let dup_public_shares = DkgPublicShares {
1894            dkg_id: 0,
1895            signer_id: 0,
1896            comms: comms.clone(),
1897            kex_public_key: Point::from(kex_private_key),
1898            kex_proof: kex_proof.clone(),
1899        };
1900        let dup_packet = Packet {
1901            msg: Message::DkgPublicShares(dup_public_shares.clone()),
1902            sig: Default::default(),
1903        };
1904
1905        coordinator.dkg_wait_signer_ids.insert(0);
1906        coordinator.gather_public_shares(&dup_packet).unwrap();
1907        assert_eq!(1, coordinator.dkg_public_shares.len());
1908        assert_eq!(
1909            public_shares,
1910            coordinator
1911                .dkg_public_shares
1912                .iter()
1913                .next()
1914                .unwrap()
1915                .1
1916                .clone()
1917        );
1918    }
1919
1920    #[test]
1921    #[cfg(feature = "with_v1")]
1922    fn dkg_private_share_v1() {
1923        dkg_private_share::<v1::Aggregator, v1::Signer>();
1924    }
1925
1926    #[test]
1927    fn dkg_private_share_v2() {
1928        dkg_private_share::<v2::Aggregator, v2::Signer>();
1929    }
1930
1931    /// test basic insertion and detection of duplicates for DkgPrivateShares
1932    fn dkg_private_share<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
1933        let (coordinators, _) = setup::<FireCoordinator<Aggregator>, Signer>(2, 1);
1934        let mut coordinator: FireCoordinator<Aggregator> = coordinators[0].clone();
1935
1936        coordinator.state = State::DkgPrivateGather;
1937
1938        let private_share = DkgPrivateShares {
1939            dkg_id: 0,
1940            signer_id: 0,
1941            shares: vec![(1, HashMap::new())],
1942        };
1943        let packet = Packet {
1944            msg: Message::DkgPrivateShares(private_share.clone()),
1945            sig: Default::default(),
1946        };
1947
1948        // check that shares are ignored if not waiting on that signer
1949        coordinator.dkg_wait_signer_ids.insert(1);
1950        coordinator.gather_private_shares(&packet).unwrap();
1951        assert_eq!(0, coordinator.dkg_private_shares.len());
1952
1953        coordinator.dkg_wait_signer_ids.insert(0);
1954        coordinator.gather_private_shares(&packet).unwrap();
1955        assert_eq!(1, coordinator.dkg_private_shares.len());
1956
1957        // check that a duplicate private share is ignored even if the state machine is tricked into waiting for it
1958        let dup_private_share = DkgPrivateShares {
1959            dkg_id: 0,
1960            signer_id: 0,
1961            shares: vec![(1, HashMap::new())],
1962        };
1963        let packet = Packet {
1964            msg: Message::DkgPrivateShares(dup_private_share.clone()),
1965            sig: Default::default(),
1966        };
1967        coordinator.dkg_wait_signer_ids.insert(0);
1968        coordinator.gather_private_shares(&packet).unwrap();
1969        assert_eq!(1, coordinator.dkg_private_shares.len());
1970        assert_eq!(
1971            private_share,
1972            coordinator
1973                .dkg_private_shares
1974                .iter()
1975                .next()
1976                .unwrap()
1977                .1
1978                .clone()
1979        );
1980    }
1981
1982    #[test]
1983    #[cfg(feature = "with_v1")]
1984    fn nonce_response_v1() {
1985        nonce_response::<v1::Aggregator, v1::Signer>();
1986    }
1987
1988    #[test]
1989    fn nonce_response_v2() {
1990        nonce_response::<v2::Aggregator, v2::Signer>();
1991    }
1992
1993    /// test basic insertion and detection of duplicates for NonceResponse
1994    fn nonce_response<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
1995        let mut rng = create_rng();
1996        let (coordinators, _) = setup::<FireCoordinator<Aggregator>, Signer>(2, 1);
1997        let mut coordinator: FireCoordinator<Aggregator> = coordinators[0].clone();
1998        let signature_type = SignatureType::Frost;
1999        let message = vec![0u8];
2000        coordinator.state = State::NonceGather(signature_type);
2001        coordinator.aggregate_public_key = Some(Point::from(Scalar::random(&mut rng)));
2002        // Populate dkg_end_messages so the DKG participation check passes
2003        for signer_id in 0..coordinator.config.num_signers {
2004            coordinator.dkg_end_messages.insert(
2005                signer_id,
2006                DkgEnd {
2007                    dkg_id: 0,
2008                    signer_id,
2009                    status: DkgStatus::Success,
2010                },
2011            );
2012        }
2013
2014        let nonce_response = NonceResponse {
2015            dkg_id: 0,
2016            sign_id: 0,
2017            sign_iter_id: 0,
2018            signer_id: 0,
2019            key_ids: vec![1u32],
2020            nonces: vec![PublicNonce {
2021                D: Point::from(Scalar::random(&mut rng)),
2022                E: Point::from(Scalar::random(&mut rng)),
2023            }],
2024            message: message.clone(),
2025        };
2026        let packet = Packet {
2027            msg: Message::NonceResponse(nonce_response.clone()),
2028            sig: Default::default(),
2029        };
2030        coordinator.gather_nonces(&packet, signature_type).unwrap();
2031        assert_eq!(1, coordinator.message_nonces[&message].public_nonces.len());
2032
2033        // check that a duplicate private share is ignored
2034        let dup_nonce_response = NonceResponse {
2035            dkg_id: 0,
2036            sign_id: 0,
2037            sign_iter_id: 0,
2038            signer_id: 0,
2039            key_ids: vec![1u32],
2040            nonces: vec![PublicNonce {
2041                D: Point::from(Scalar::random(&mut rng)),
2042                E: Point::from(Scalar::random(&mut rng)),
2043            }],
2044            message: message.clone(),
2045        };
2046        let packet = Packet {
2047            msg: Message::NonceResponse(dup_nonce_response.clone()),
2048            sig: Default::default(),
2049        };
2050        coordinator.gather_nonces(&packet, signature_type).unwrap();
2051        assert_eq!(1, coordinator.message_nonces[&message].public_nonces.len());
2052        assert_eq!(
2053            nonce_response,
2054            coordinator.message_nonces[&message]
2055                .public_nonces
2056                .iter()
2057                .next()
2058                .unwrap()
2059                .1
2060                .clone()
2061        );
2062    }
2063
2064    #[test]
2065    #[cfg(feature = "with_v1")]
2066    fn sig_share_v1() {
2067        sig_share::<v1::Aggregator, v1::Signer>();
2068    }
2069
2070    #[test]
2071    fn sig_share_v2() {
2072        sig_share::<v2::Aggregator, v2::Signer>();
2073    }
2074
2075    /// test basic insertion and detection of duplicates for SignatureShareResponse
2076    fn sig_share<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
2077        let mut rng = create_rng();
2078        let (coordinators, _) = setup::<FireCoordinator<Aggregator>, Signer>(2, 1);
2079        let mut coordinator = coordinators[0].clone();
2080        let signature_type = SignatureType::Frost;
2081
2082        coordinator.state = State::SigShareGather(signature_type);
2083        // Populate dkg_end_messages so the DKG participation check passes
2084        for signer_id in 0..coordinator.config.num_signers {
2085            coordinator.dkg_end_messages.insert(
2086                signer_id,
2087                DkgEnd {
2088                    dkg_id: 0,
2089                    signer_id,
2090                    status: DkgStatus::Success,
2091                },
2092            );
2093        }
2094
2095        let signature_share = SignatureShare {
2096            id: 1,
2097            z_i: Scalar::random(&mut rng),
2098            key_ids: vec![1],
2099        };
2100        let sig_share_response = SignatureShareResponse {
2101            dkg_id: 0,
2102            sign_id: 0,
2103            sign_iter_id: 0,
2104            signer_id: 0,
2105            signature_shares: vec![signature_share.clone()],
2106        };
2107        let packet = Packet {
2108            msg: Message::SignatureShareResponse(sig_share_response.clone()),
2109            sig: Default::default(),
2110        };
2111
2112        // check that a signature share is ignored due to not being on the wait list
2113        coordinator
2114            .gather_sig_shares(&packet, signature_type)
2115            .unwrap();
2116        assert_eq!(0, coordinator.signature_shares.len());
2117
2118        // add the signer to the wait list then verify that the signature share is accepted
2119        let response_info = coordinator
2120            .message_nonces
2121            .entry(coordinator.message.clone())
2122            .or_default();
2123        response_info.sign_wait_signer_ids.insert(0);
2124
2125        coordinator
2126            .gather_sig_shares(&packet, signature_type)
2127            .unwrap();
2128        assert_eq!(1, coordinator.signature_shares.len());
2129
2130        // check that a duplicate signature share is ignored even if on the wait list
2131        let response_info = coordinator
2132            .message_nonces
2133            .entry(coordinator.message.clone())
2134            .or_default();
2135        response_info.sign_wait_signer_ids.insert(0);
2136
2137        let dup_signature_share = SignatureShare {
2138            id: 1,
2139            z_i: Scalar::random(&mut rng),
2140            key_ids: vec![1],
2141        };
2142        let dup_sig_share_response = SignatureShareResponse {
2143            dkg_id: 0,
2144            sign_id: 0,
2145            sign_iter_id: 0,
2146            signer_id: 0,
2147            signature_shares: vec![dup_signature_share.clone()],
2148        };
2149        let packet = Packet {
2150            msg: Message::SignatureShareResponse(dup_sig_share_response.clone()),
2151            sig: Default::default(),
2152        };
2153        coordinator
2154            .gather_sig_shares(&packet, signature_type)
2155            .unwrap();
2156
2157        assert_eq!(1, coordinator.signature_shares.len());
2158        assert_eq!(
2159            vec![signature_share],
2160            coordinator
2161                .signature_shares
2162                .iter()
2163                .next()
2164                .unwrap()
2165                .1
2166                .clone()
2167        );
2168    }
2169
2170    #[test]
2171    #[cfg(feature = "with_v1")]
2172    fn start_public_shares_v1() {
2173        start_public_shares::<v1::Aggregator>();
2174    }
2175
2176    #[test]
2177    fn start_public_shares_v2() {
2178        start_public_shares::<v2::Aggregator>();
2179    }
2180
2181    fn start_public_shares<Aggregator: AggregatorTrait>() {
2182        let mut rng = create_rng();
2183        let config = Config::new(10, 40, 28, Scalar::random(&mut rng));
2184        let mut coordinator = FireCoordinator::<Aggregator>::new(config);
2185
2186        coordinator.state = State::DkgPublicDistribute; // Must be in this state before calling start public shares
2187
2188        let result = coordinator.start_public_shares().unwrap();
2189
2190        assert!(matches!(result.msg, Message::DkgBegin(_)));
2191        assert_eq!(coordinator.get_state(), State::DkgPublicGather);
2192        assert_eq!(coordinator.current_dkg_id, 0);
2193    }
2194
2195    #[test]
2196    #[cfg(feature = "with_v1")]
2197    fn start_private_shares_v1() {
2198        start_private_shares::<v1::Aggregator>();
2199    }
2200
2201    #[test]
2202    fn start_private_shares_v2() {
2203        start_private_shares::<v2::Aggregator>();
2204    }
2205
2206    fn start_private_shares<Aggregator: AggregatorTrait>() {
2207        let mut rng = create_rng();
2208        let config = Config::new(10, 40, 28, Scalar::random(&mut rng));
2209        let mut coordinator = FireCoordinator::<Aggregator>::new(config);
2210
2211        coordinator.state = State::DkgPrivateDistribute; // Must be in this state before calling start private shares
2212
2213        let message = coordinator.start_private_shares().unwrap();
2214        assert!(matches!(message.msg, Message::DkgPrivateBegin(_)));
2215        assert_eq!(coordinator.get_state(), State::DkgPrivateGather);
2216        assert_eq!(coordinator.current_dkg_id, 0);
2217    }
2218
2219    #[test]
2220    #[cfg(feature = "with_v1")]
2221    fn run_dkg_sign_v1() {
2222        for _ in 0..4 {
2223            run_dkg_sign::<FireCoordinator<v1::Aggregator>, v1::Signer>(5, 2);
2224        }
2225    }
2226
2227    #[test]
2228    fn run_dkg_sign_v2() {
2229        for _ in 0..4 {
2230            run_dkg_sign::<FireCoordinator<v2::Aggregator>, v2::Signer>(5, 2);
2231        }
2232    }
2233
2234    #[test]
2235    #[cfg(feature = "with_v1")]
2236    fn check_signature_shares_v1() {
2237        check_signature_shares::<FireCoordinator<v1::Aggregator>, v1::Signer>(
2238            5,
2239            2,
2240            SignatureType::Frost,
2241            vec![1, 2],
2242        );
2243        check_signature_shares::<FireCoordinator<v1::Aggregator>, v1::Signer>(
2244            5,
2245            2,
2246            SignatureType::Schnorr,
2247            vec![1, 2],
2248        );
2249        check_signature_shares::<FireCoordinator<v1::Aggregator>, v1::Signer>(
2250            5,
2251            2,
2252            SignatureType::Taproot(None),
2253            vec![1, 2],
2254        );
2255        check_signature_shares::<FireCoordinator<v1::Aggregator>, v1::Signer>(
2256            5,
2257            2,
2258            SignatureType::Taproot(Some([23u8; 32])),
2259            vec![1, 2],
2260        );
2261    }
2262
2263    #[test]
2264    fn check_signature_shares_v2() {
2265        check_signature_shares::<FireCoordinator<v2::Aggregator>, v2::Signer>(
2266            5,
2267            2,
2268            SignatureType::Frost,
2269            vec![0],
2270        );
2271        check_signature_shares::<FireCoordinator<v2::Aggregator>, v2::Signer>(
2272            5,
2273            2,
2274            SignatureType::Schnorr,
2275            vec![0],
2276        );
2277        check_signature_shares::<FireCoordinator<v2::Aggregator>, v2::Signer>(
2278            5,
2279            2,
2280            SignatureType::Taproot(None),
2281            vec![0],
2282        );
2283        check_signature_shares::<FireCoordinator<v2::Aggregator>, v2::Signer>(
2284            5,
2285            2,
2286            SignatureType::Taproot(Some([23u8; 32])),
2287            vec![0],
2288        );
2289    }
2290
2291    #[test]
2292    #[cfg(feature = "with_v1")]
2293    fn all_signers_dkg_v1() {
2294        all_signers_dkg::<v1::Aggregator, v1::Signer>(5, 2);
2295    }
2296
2297    #[test]
2298    fn all_signers_dkg_v2() {
2299        all_signers_dkg::<v2::Aggregator, v2::Signer>(5, 2);
2300    }
2301
2302    fn all_signers_dkg<Aggregator: AggregatorTrait, SignerType: SignerTrait>(
2303        num_signers: u32,
2304        keys_per_signer: u32,
2305    ) -> (Vec<FireCoordinator<Aggregator>>, Vec<Signer<SignerType>>) {
2306        let (mut coordinators, mut signers) =
2307            setup::<FireCoordinator<Aggregator>, SignerType>(num_signers, keys_per_signer);
2308
2309        // We have started a dkg round
2310        let message = coordinators
2311            .first_mut()
2312            .unwrap()
2313            .start_dkg_round(None)
2314            .unwrap();
2315        assert!(coordinators.first().unwrap().aggregate_public_key.is_none());
2316        assert_eq!(coordinators.first().unwrap().state, State::DkgPublicGather);
2317
2318        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinators
2319        let (outbound_messages, operation_results) =
2320            feedback_messages(&mut coordinators, &mut signers, &[message]);
2321        assert!(operation_results.is_empty());
2322        for coordinator in &coordinators {
2323            assert_eq!(coordinator.state, State::DkgPublicSharesDoneGather);
2324        }
2325
2326        assert_eq!(outbound_messages.len(), 1);
2327        assert!(
2328            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
2329            "Expected DkgPublicSharesDone message"
2330        );
2331
2332        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
2333        let (outbound_messages, operation_results) =
2334            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
2335        assert!(operation_results.is_empty());
2336        for coordinator in &coordinators {
2337            assert_eq!(coordinator.state, State::DkgPrivateGather);
2338        }
2339
2340        // Successfully got an Aggregate Public Key...
2341        assert_eq!(outbound_messages.len(), 1);
2342        assert!(
2343            matches!(&outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
2344            "Expected DkgPrivateBegin message"
2345        );
2346        // Send the DKG Private Begin message to all signers and share their responses with the coordinators and signers
2347        let (outbound_messages, operation_results) =
2348            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
2349        assert!(operation_results.is_empty());
2350        assert_eq!(outbound_messages.len(), 1);
2351        assert!(
2352            matches!(outbound_messages[0].msg, Message::DkgPrivateSharesDone(_)),
2353            "Expected DkgPrivateSharesDone message"
2354        );
2355
2356        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
2357        let (outbound_messages, operation_results) =
2358            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
2359        assert!(operation_results.is_empty());
2360        assert_eq!(outbound_messages.len(), 1);
2361        assert!(
2362            matches!(outbound_messages[0].msg, Message::DkgEndBegin(_)),
2363            "Expected DkgEndBegin message"
2364        );
2365
2366        // Send the DkgEndBegin message to all signers and share their responses with the coordinators and signers
2367        let (outbound_messages, operation_results) =
2368            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
2369        assert!(outbound_messages.is_empty());
2370        assert_eq!(operation_results.len(), 1);
2371        let OperationResult::Dkg(point) = operation_results[0] else {
2372            panic!("Expected Dkg Operation result");
2373        };
2374        assert_ne!(point, Point::default());
2375        for coordinator in coordinators.iter() {
2376            assert_eq!(coordinator.get_aggregate_public_key(), Some(point));
2377            assert_eq!(coordinator.get_state(), State::Idle);
2378        }
2379        (coordinators, signers)
2380    }
2381
2382    #[test]
2383    #[cfg(feature = "with_v1")]
2384    fn missing_public_keys_dkg_v1() {
2385        missing_public_keys_dkg::<v1::Aggregator, v1::Signer>(10, 1);
2386    }
2387
2388    #[test]
2389    fn missing_public_keys_dkg_v2() {
2390        missing_public_keys_dkg::<v2::Aggregator, v2::Signer>(10, 1);
2391    }
2392
2393    fn missing_public_keys_dkg<Aggregator: AggregatorTrait, SignerType: SignerTrait>(
2394        num_signers: u32,
2395        keys_per_signer: u32,
2396    ) -> (Vec<FireCoordinator<Aggregator>>, Vec<Signer<SignerType>>) {
2397        let timeout = Duration::from_millis(2048);
2398        let expire = Duration::from_millis(2222);
2399        let (mut coordinators, signers) =
2400            setup_with_timeouts::<FireCoordinator<Aggregator>, SignerType>(
2401                num_signers,
2402                keys_per_signer,
2403                Some(timeout),
2404                Some(timeout),
2405                Some(timeout),
2406                Some(timeout),
2407                Some(timeout),
2408                false,
2409            );
2410
2411        // Start a DKG round where we will not allow all signers to recv DkgBegin, so they will not respond with DkgPublicShares
2412        let message = coordinators
2413            .first_mut()
2414            .unwrap()
2415            .start_dkg_round(None)
2416            .unwrap();
2417        assert!(coordinators.first().unwrap().aggregate_public_key.is_none());
2418        assert_eq!(coordinators.first().unwrap().state, State::DkgPublicGather);
2419
2420        let mut minimum_coordinators = coordinators.clone();
2421        let mut minimum_signers = signers.clone();
2422
2423        // Let us also remove that signers public key from the config including all of its key ids
2424        let mut removed_signer = minimum_signers.pop().expect("Failed to pop signer");
2425        let public_key = removed_signer
2426            .public_keys
2427            .signers
2428            .remove(&removed_signer.signer_id)
2429            .expect("Failed to remove public key");
2430        removed_signer
2431            .public_keys
2432            .key_ids
2433            .retain(|_k, pk| pk.to_bytes() != public_key.to_bytes());
2434
2435        for signer in minimum_signers.iter_mut() {
2436            // Overwrite all other signers to use the new public keys missing the removed signers public key
2437            signer.public_keys = removed_signer.public_keys.clone();
2438        }
2439
2440        // Send the DKG Begin message to minimum signers and gather responses by sharing with signers and coordinator
2441        let (outbound_messages, operation_results) = feedback_messages(
2442            &mut minimum_coordinators,
2443            &mut minimum_signers,
2444            from_ref(&message),
2445        );
2446
2447        assert!(outbound_messages.is_empty());
2448        assert!(operation_results.is_empty());
2449        assert_eq!(coordinators.first().unwrap().state, State::DkgPublicGather,);
2450
2451        // Sleep long enough to hit the timeout
2452        thread::sleep(expire);
2453
2454        let (outbound_messages, operation_results) = minimum_coordinators
2455            .first_mut()
2456            .unwrap()
2457            .process_timeout()
2458            .unwrap();
2459
2460        assert!(outbound_messages.is_some());
2461        assert!(operation_results.is_none());
2462        assert_eq!(
2463            minimum_coordinators.first().unwrap().state,
2464            State::DkgPublicSharesDoneGather,
2465        );
2466
2467        // Feed DkgPublicSharesDone to signers, get acks back to coordinator
2468        let (outbound_messages, operation_results) = feedback_messages(
2469            &mut minimum_coordinators,
2470            &mut minimum_signers,
2471            &[outbound_messages.unwrap()],
2472        );
2473        assert!(operation_results.is_empty());
2474        assert_eq!(
2475            minimum_coordinators.first().unwrap().state,
2476            State::DkgPrivateGather,
2477        );
2478        assert_eq!(outbound_messages.len(), 1);
2479        assert!(
2480            matches!(&outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
2481            "Expected DkgPrivateBegin message"
2482        );
2483        (minimum_coordinators, minimum_signers)
2484    }
2485
2486    #[test]
2487    #[cfg(feature = "with_v1")]
2488    fn minimum_signers_dkg_v1() {
2489        minimum_signers_dkg::<v1::Aggregator, v1::Signer>(10, 2);
2490    }
2491
2492    #[test]
2493    fn minimum_signers_dkg_v2() {
2494        minimum_signers_dkg::<v2::Aggregator, v2::Signer>(10, 2);
2495    }
2496
2497    fn minimum_signers_dkg<Aggregator: AggregatorTrait, SignerType: SignerTrait>(
2498        num_signers: u32,
2499        keys_per_signer: u32,
2500    ) -> (Vec<FireCoordinator<Aggregator>>, Vec<Signer<SignerType>>) {
2501        let timeout = Duration::from_millis(2048);
2502        let expire = Duration::from_millis(2222);
2503        let (coordinators, signers) = setup_with_timeouts::<FireCoordinator<Aggregator>, SignerType>(
2504            num_signers,
2505            keys_per_signer,
2506            Some(timeout),
2507            Some(timeout),
2508            Some(timeout),
2509            Some(timeout),
2510            Some(timeout),
2511            false,
2512        );
2513
2514        // Start a DKG round where we will not allow all signers to recv DkgBegin, so they will not respond with DkgPublicShares
2515
2516        // DKG threshold is 9/10, so need to remove 1
2517        let num_signers_to_remove = 1;
2518
2519        let mut minimum_coordinators = coordinators.clone();
2520        let mut minimum_signers = signers.clone();
2521
2522        minimum_signers.truncate(minimum_signers.len().saturating_sub(num_signers_to_remove));
2523
2524        let message = minimum_coordinators
2525            .first_mut()
2526            .unwrap()
2527            .start_dkg_round(None)
2528            .unwrap();
2529        assert!(minimum_coordinators
2530            .first()
2531            .unwrap()
2532            .aggregate_public_key
2533            .is_none());
2534        assert_eq!(
2535            minimum_coordinators.first().unwrap().state,
2536            State::DkgPublicGather
2537        );
2538
2539        // Send the DKG Begin message to minimum signers and gather responses by sharing with signers and coordinator
2540        let (outbound_messages, operation_results) = feedback_messages(
2541            &mut minimum_coordinators,
2542            &mut minimum_signers,
2543            from_ref(&message),
2544        );
2545
2546        assert!(outbound_messages.is_empty());
2547        assert!(operation_results.is_empty());
2548        assert_eq!(
2549            minimum_coordinators.first().unwrap().state,
2550            State::DkgPublicGather,
2551        );
2552
2553        // Sleep long enough to hit the timeout
2554        thread::sleep(expire);
2555
2556        let (outbound_messages, operation_results) = minimum_coordinators
2557            .first_mut()
2558            .unwrap()
2559            .process_timeout()
2560            .unwrap();
2561
2562        assert!(outbound_messages.is_some());
2563        assert!(operation_results.is_none());
2564        assert_eq!(
2565            minimum_coordinators.first().unwrap().state,
2566            State::DkgPublicSharesDoneGather,
2567        );
2568
2569        // Feed DkgPublicSharesDone to signers, get acks back to coordinator
2570        let (_outbound_messages, operation_results) = feedback_messages(
2571            &mut minimum_coordinators,
2572            &mut minimum_signers,
2573            &[outbound_messages.unwrap()],
2574        );
2575        assert!(operation_results.is_empty());
2576        assert_eq!(
2577            minimum_coordinators.first().unwrap().state,
2578            State::DkgPrivateGather,
2579        );
2580
2581        // Run DKG again with fresh coordinator and signers, this time allow gathering DkgPublicShares but timeout getting DkgEnd
2582        let mut minimum_coordinators = coordinators.clone();
2583        let mut minimum_signers = signers.clone();
2584
2585        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinator
2586        let (outbound_messages, operation_results) =
2587            feedback_messages(&mut minimum_coordinators, &mut minimum_signers, &[message]);
2588        assert!(operation_results.is_empty());
2589        assert_eq!(
2590            minimum_coordinators.first().unwrap().state,
2591            State::DkgPublicSharesDoneGather
2592        );
2593
2594        assert_eq!(outbound_messages.len(), 1);
2595        assert!(
2596            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
2597            "Expected DkgPublicSharesDone message"
2598        );
2599
2600        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
2601        let (outbound_messages, operation_results) = feedback_messages(
2602            &mut minimum_coordinators,
2603            &mut minimum_signers,
2604            &outbound_messages,
2605        );
2606        assert!(operation_results.is_empty());
2607        assert_eq!(
2608            minimum_coordinators.first().unwrap().state,
2609            State::DkgPrivateGather
2610        );
2611
2612        assert_eq!(outbound_messages.len(), 1);
2613        assert!(
2614            matches!(outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
2615            "Expected DkgPrivateBegin message"
2616        );
2617
2618        // now remove signers so the set is minimum
2619        minimum_signers.truncate(minimum_signers.len().saturating_sub(num_signers_to_remove));
2620
2621        // Send the DKG Private Begin message to minimum signers and share their responses with the coordinator and signers
2622        let (outbound_messages, operation_results) = feedback_messages(
2623            &mut minimum_coordinators,
2624            &mut minimum_signers,
2625            &outbound_messages,
2626        );
2627        assert!(outbound_messages.is_empty());
2628        assert!(operation_results.is_empty());
2629        assert_eq!(
2630            minimum_coordinators.first().unwrap().state,
2631            State::DkgPrivateGather,
2632        );
2633
2634        // Sleep long enough to hit the timeout
2635        thread::sleep(expire);
2636
2637        let (outbound_message, operation_result) = minimum_coordinators
2638            .first_mut()
2639            .unwrap()
2640            .process_timeout()
2641            .unwrap();
2642
2643        assert!(outbound_message.is_some());
2644        assert!(operation_result.is_none());
2645        assert!(
2646            matches!(
2647                outbound_message.clone().unwrap().msg,
2648                Message::DkgPrivateSharesDone(_)
2649            ),
2650            "Expected DkgPrivateSharesDone message"
2651        );
2652        assert_eq!(
2653            minimum_coordinators.first().unwrap().state,
2654            State::DkgPrivateSharesDoneGather,
2655        );
2656
2657        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
2658        let (outbound_messages, operation_results) = feedback_messages(
2659            &mut minimum_coordinators,
2660            &mut minimum_signers,
2661            &[outbound_message.unwrap()],
2662        );
2663        assert!(operation_results.is_empty());
2664        assert_eq!(outbound_messages.len(), 1);
2665        assert!(
2666            matches!(outbound_messages[0].msg, Message::DkgEndBegin(_)),
2667            "Expected DkgEndBegin message"
2668        );
2669        assert_eq!(
2670            minimum_coordinators.first().unwrap().state,
2671            State::DkgEndGather,
2672        );
2673
2674        // Send the DkgEndBegin message to all signers and share their responses with the coordinator and signers
2675        let (outbound_messages, operation_results) = feedback_messages(
2676            &mut minimum_coordinators,
2677            &mut minimum_signers,
2678            &outbound_messages,
2679        );
2680        assert!(outbound_messages.is_empty());
2681        assert_eq!(operation_results.len(), 1);
2682        let OperationResult::Dkg(point) = operation_results[0] else {
2683            panic!("Expected Dkg Operation result");
2684        };
2685        assert_ne!(point, Point::default());
2686        for coordinator in minimum_coordinators.iter() {
2687            assert_eq!(coordinator.get_aggregate_public_key(), Some(point));
2688            assert_eq!(coordinator.get_state(), State::Idle);
2689        }
2690
2691        (minimum_coordinators, minimum_signers)
2692    }
2693
2694    #[test]
2695    #[cfg(feature = "with_v1")]
2696    fn insufficient_signers_dkg_v1() {
2697        insufficient_signers_dkg::<v1::Aggregator, v1::Signer>();
2698    }
2699
2700    #[test]
2701    fn insufficient_signers_dkg_v2() {
2702        insufficient_signers_dkg::<v2::Aggregator, v2::Signer>();
2703    }
2704
2705    fn insufficient_signers_dkg<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
2706        let timeout = Duration::from_millis(2048);
2707        let expire = Duration::from_millis(2222);
2708        let num_signers = 10;
2709        let keys_per_signer = 2;
2710        let (coordinators, signers) = setup_with_timeouts::<FireCoordinator<Aggregator>, Signer>(
2711            num_signers,
2712            keys_per_signer,
2713            Some(timeout),
2714            Some(timeout),
2715            Some(timeout),
2716            Some(timeout),
2717            Some(timeout),
2718            false,
2719        );
2720
2721        // Start a DKG round where we will not allow all signers to recv DkgBegin, so they will not respond with DkgPublicShares
2722
2723        // DKG threshold is 9/10, so need to remove 2
2724        let num_signers_to_remove = 2;
2725
2726        let mut insufficient_coordinators = coordinators.clone();
2727        let mut insufficient_signers = signers.clone();
2728
2729        insufficient_signers.truncate(
2730            insufficient_signers
2731                .len()
2732                .saturating_sub(num_signers_to_remove),
2733        );
2734
2735        let message = insufficient_coordinators
2736            .first_mut()
2737            .unwrap()
2738            .start_dkg_round(None)
2739            .unwrap();
2740        assert!(insufficient_coordinators
2741            .first()
2742            .unwrap()
2743            .aggregate_public_key
2744            .is_none());
2745        assert_eq!(
2746            insufficient_coordinators.first().unwrap().state,
2747            State::DkgPublicGather
2748        );
2749
2750        // Send the DKG Begin message to insufficient signers and gather responses by sharing with signers and coordinator
2751        let (outbound_messages, operation_results) = feedback_messages(
2752            &mut insufficient_coordinators,
2753            &mut insufficient_signers,
2754            from_ref(&message),
2755        );
2756
2757        // Failed to get an aggregate public key
2758        assert!(outbound_messages.is_empty());
2759        assert!(operation_results.is_empty());
2760        for coordinator in &insufficient_coordinators {
2761            assert_eq!(coordinator.state, State::DkgPublicGather);
2762        }
2763
2764        // Sleep long enough to hit the timeout
2765        thread::sleep(expire);
2766
2767        let (outbound_message, operation_result) = insufficient_coordinators
2768            .first_mut()
2769            .unwrap()
2770            .process_timeout()
2771            .unwrap();
2772
2773        assert!(outbound_message.is_none());
2774        assert!(operation_result.is_some());
2775        assert_eq!(
2776            insufficient_coordinators.first().unwrap().state,
2777            State::DkgPublicGather,
2778        );
2779        assert!(
2780            matches!(
2781                operation_result.unwrap(),
2782                OperationResult::DkgError(DkgError::DkgPublicTimeout(_))
2783            ),
2784            "Expected OperationResult::DkgError(DkgError::DkgPublicTimeout"
2785        );
2786
2787        // Run DKG again with fresh coordinator and signers, this time allow gathering DkgPublicShares but timeout getting DkgEnd
2788        let mut insufficient_coordinator = coordinators.clone();
2789        let mut insufficient_signers = signers.clone();
2790
2791        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinator
2792        let (outbound_messages, operation_results) = feedback_messages(
2793            &mut insufficient_coordinator,
2794            &mut insufficient_signers,
2795            &[message],
2796        );
2797        assert!(operation_results.is_empty());
2798        assert_eq!(
2799            insufficient_coordinator.first().unwrap().state,
2800            State::DkgPublicSharesDoneGather
2801        );
2802
2803        assert_eq!(outbound_messages.len(), 1);
2804        assert!(
2805            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
2806            "Expected DkgPublicSharesDone message"
2807        );
2808
2809        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
2810        let (outbound_messages, operation_results) = feedback_messages(
2811            &mut insufficient_coordinator,
2812            &mut insufficient_signers,
2813            &outbound_messages,
2814        );
2815        assert!(operation_results.is_empty());
2816        assert_eq!(
2817            insufficient_coordinator.first().unwrap().state,
2818            State::DkgPrivateGather
2819        );
2820
2821        // Successfully got an Aggregate Public Key...
2822        assert_eq!(outbound_messages.len(), 1);
2823        assert!(
2824            matches!(outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
2825            "Expected DkgPrivateBegin message"
2826        );
2827
2828        // now remove signers so the set is insufficient
2829        insufficient_signers.truncate(
2830            insufficient_signers
2831                .len()
2832                .saturating_sub(num_signers_to_remove),
2833        );
2834
2835        // Send the DKG Private Begin message to insufficient signers and share their responses with the coordinator and signers
2836        let (outbound_messages, operation_results) = feedback_messages(
2837            &mut insufficient_coordinator,
2838            &mut insufficient_signers,
2839            &outbound_messages,
2840        );
2841        assert!(outbound_messages.is_empty());
2842        assert!(operation_results.is_empty());
2843        assert_eq!(
2844            insufficient_coordinator.first().unwrap().state,
2845            State::DkgPrivateGather,
2846        );
2847
2848        // Sleep long enough to hit the timeout
2849        thread::sleep(expire);
2850
2851        let (outbound_message, operation_result) = insufficient_coordinator
2852            .first_mut()
2853            .unwrap()
2854            .process_timeout()
2855            .unwrap();
2856
2857        assert!(outbound_message.is_none());
2858        assert!(operation_result.is_some());
2859        assert_eq!(
2860            insufficient_coordinator.first().unwrap().state,
2861            State::DkgPrivateGather,
2862        );
2863        assert!(
2864            matches!(
2865                operation_result.unwrap(),
2866                OperationResult::DkgError(DkgError::DkgPrivateTimeout(_))
2867            ),
2868            "Expected OperationResult::DkgError(DkgError::DkgPrivateTimeout)"
2869        );
2870    }
2871
2872    #[test]
2873    #[cfg(feature = "with_v1")]
2874    fn malicious_signers_dkg_v1() {
2875        malicious_signers_dkg::<v1::Aggregator, v1::Signer>(5, 2);
2876    }
2877
2878    #[test]
2879    fn malicious_signers_dkg_v2() {
2880        malicious_signers_dkg::<v2::Aggregator, v2::Signer>(5, 2);
2881    }
2882
2883    fn malicious_signers_dkg<Aggregator: AggregatorTrait, SignerType: SignerTrait>(
2884        num_signers: u32,
2885        keys_per_signer: u32,
2886    ) -> (Vec<FireCoordinator<Aggregator>>, Vec<Signer<SignerType>>) {
2887        let (mut coordinators, mut signers) =
2888            setup::<FireCoordinator<Aggregator>, SignerType>(num_signers, keys_per_signer);
2889
2890        // We have started a dkg round
2891        let message = coordinators
2892            .first_mut()
2893            .unwrap()
2894            .start_dkg_round(None)
2895            .unwrap();
2896        assert!(coordinators.first().unwrap().aggregate_public_key.is_none());
2897        assert_eq!(coordinators.first().unwrap().state, State::DkgPublicGather);
2898
2899        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinators
2900        let (outbound_messages, operation_results) =
2901            feedback_messages(&mut coordinators, &mut signers, &[message]);
2902        assert!(operation_results.is_empty());
2903        for coordinator in &coordinators {
2904            assert_eq!(coordinator.state, State::DkgPublicSharesDoneGather);
2905        }
2906
2907        assert_eq!(outbound_messages.len(), 1);
2908        assert!(
2909            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
2910            "Expected DkgPublicSharesDone message"
2911        );
2912
2913        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
2914        let (outbound_messages, operation_results) =
2915            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
2916        assert!(operation_results.is_empty());
2917        for coordinator in &coordinators {
2918            assert_eq!(coordinator.state, State::DkgPrivateGather);
2919        }
2920
2921        assert_eq!(outbound_messages.len(), 1);
2922        assert!(
2923            matches!(outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
2924            "Expected DkgPrivateBegin message"
2925        );
2926
2927        // Send the DKG Private Begin message to all signers and share their responses with the coordinators and signers, but mutate one signer's DkgPrivateShares so it is marked malicious
2928        let (outbound_messages, operation_results) = feedback_mutated_messages(
2929            &mut coordinators,
2930            &mut signers,
2931            &outbound_messages,
2932            |signer, msgs| {
2933                if signer.signer_id != 0 {
2934                    return msgs;
2935                }
2936                msgs.iter()
2937                    .map(|packet| {
2938                        let Message::DkgPrivateShares(shares) = &packet.msg else {
2939                            return packet.clone();
2940                        };
2941                        // mutate one of the shares
2942                        let sshares: Vec<(u32, HashMap<u32, Vec<u8>>)> = shares
2943                            .shares
2944                            .iter()
2945                            .map(|(src_party_id, share_map)| {
2946                                (
2947                                    *src_party_id,
2948                                    share_map
2949                                        .iter()
2950                                        .map(|(dst_key_id, bytes)| {
2951                                            let mut bytes = bytes.clone();
2952                                            bytes.insert(0, 234);
2953                                            (*dst_key_id, bytes)
2954                                        })
2955                                        .collect(),
2956                                )
2957                            })
2958                            .collect();
2959
2960                        Packet {
2961                            msg: Message::DkgPrivateShares(DkgPrivateShares {
2962                                dkg_id: shares.dkg_id,
2963                                signer_id: shares.signer_id,
2964                                shares: sshares.clone(),
2965                            }),
2966                            sig: vec![],
2967                        }
2968                    })
2969                    .collect()
2970            },
2971        );
2972        assert!(operation_results.is_empty());
2973        assert_eq!(outbound_messages.len(), 1);
2974        assert!(
2975            matches!(outbound_messages[0].msg, Message::DkgPrivateSharesDone(_)),
2976            "Expected DkgPrivateSharesDone message"
2977        );
2978
2979        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
2980        let (outbound_messages, operation_results) =
2981            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
2982        assert!(operation_results.is_empty());
2983        assert_eq!(outbound_messages.len(), 1);
2984        assert!(
2985            matches!(outbound_messages[0].msg, Message::DkgEndBegin(_)),
2986            "Expected DkgEndBegin message"
2987        );
2988
2989        // Send the DkgEndBegin message to all signers and share their responses with the coordinators and signers
2990        let (outbound_messages, operation_results) =
2991            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
2992        assert!(outbound_messages.is_empty());
2993        assert_eq!(operation_results.len(), 1);
2994        let OperationResult::DkgError(DkgError::DkgEndFailure {
2995            reported_failures, ..
2996        }) = &operation_results[0]
2997        else {
2998            panic!("Expected OperationResult::DkgError(DkgError::DkgEndFailure");
2999        };
3000
3001        for (_signer_id, dkg_failure) in reported_failures {
3002            let DkgFailure::BadPrivateShares(bad_share_map) = dkg_failure else {
3003                panic!("Expected DkgFailure::BadPrivateShares");
3004            };
3005            for (bad_signer_id, _bad_private_share) in bad_share_map {
3006                assert_eq!(*bad_signer_id, 0u32);
3007            }
3008        }
3009        (coordinators, signers)
3010    }
3011
3012    #[test]
3013    #[cfg(feature = "with_v1")]
3014    fn bad_poly_length_dkg_v1() {
3015        bad_poly_length_dkg::<v1::Aggregator, v1::Signer>(5, 2);
3016    }
3017
3018    #[test]
3019    fn bad_poly_length_dkg_v2() {
3020        bad_poly_length_dkg::<v2::Aggregator, v2::Signer>(5, 2);
3021    }
3022
3023    fn bad_poly_length_dkg<Aggregator: AggregatorTrait, SignerType: SignerTrait>(
3024        num_signers: u32,
3025        keys_per_signer: u32,
3026    ) -> (Vec<FireCoordinator<Aggregator>>, Vec<Signer<SignerType>>) {
3027        let (mut coordinators, mut signers) =
3028            setup::<FireCoordinator<Aggregator>, SignerType>(num_signers, keys_per_signer);
3029
3030        // We have started a dkg round
3031        let message = coordinators
3032            .first_mut()
3033            .unwrap()
3034            .start_dkg_round(None)
3035            .unwrap();
3036        assert!(coordinators.first().unwrap().aggregate_public_key.is_none());
3037        assert_eq!(coordinators.first().unwrap().state, State::DkgPublicGather);
3038
3039        // Send the DkgBegin message to all signers and share their responses with the coordinators and signers, but mutate two signers' DkgPublicShares: make one polynomial larger than the threshold, and the other smaller
3040        let (outbound_messages, operation_results) = feedback_mutated_messages(
3041            &mut coordinators,
3042            &mut signers,
3043            &[message],
3044            |signer, msgs| {
3045                if signer.signer_id != 0 && signer.signer_id != 1 {
3046                    return msgs;
3047                }
3048                msgs.iter()
3049                    .map(|packet| {
3050                        let Message::DkgPublicShares(shares) = &packet.msg else {
3051                            return packet.clone();
3052                        };
3053                        let comms = shares
3054                            .comms
3055                            .iter()
3056                            .map(|(id, comm)| {
3057                                let mut c = comm.clone();
3058                                if signer.signer_id == 0 {
3059                                    c.poly.push(Point::new());
3060                                } else {
3061                                    c.poly.pop();
3062                                }
3063                                (*id, c)
3064                            })
3065                            .collect();
3066                        Packet {
3067                            msg: Message::DkgPublicShares(DkgPublicShares {
3068                                dkg_id: shares.dkg_id,
3069                                signer_id: shares.signer_id,
3070                                comms,
3071                                kex_public_key: Point::new(),
3072                                kex_proof: schnorr::Proof {
3073                                    R: Point::new(),
3074                                    s: Scalar::new(),
3075                                },
3076                            }),
3077                            sig: vec![],
3078                        }
3079                    })
3080                    .collect()
3081            },
3082        );
3083
3084        assert!(operation_results.is_empty());
3085        for coordinator in &coordinators {
3086            assert_eq!(coordinator.state, State::DkgPublicSharesDoneGather);
3087        }
3088
3089        assert_eq!(outbound_messages.len(), 1);
3090        assert!(
3091            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
3092            "Expected DkgPublicSharesDone message"
3093        );
3094
3095        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
3096        let (outbound_messages, operation_results) =
3097            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3098        assert!(operation_results.is_empty());
3099        for coordinator in &coordinators {
3100            assert_eq!(coordinator.state, State::DkgPrivateGather);
3101        }
3102
3103        assert_eq!(outbound_messages.len(), 1);
3104        assert!(
3105            matches!(outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
3106            "Expected DkgPrivateBegin message"
3107        );
3108
3109        let (outbound_messages, operation_results) =
3110            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3111        assert!(operation_results.is_empty());
3112        assert_eq!(outbound_messages.len(), 1);
3113        assert!(
3114            matches!(outbound_messages[0].msg, Message::DkgPrivateSharesDone(_)),
3115            "Expected DkgPrivateSharesDone message"
3116        );
3117
3118        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
3119        let (outbound_messages, operation_results) =
3120            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3121        assert!(operation_results.is_empty());
3122        assert_eq!(outbound_messages.len(), 1);
3123        assert!(
3124            matches!(outbound_messages[0].msg, Message::DkgEndBegin(_)),
3125            "Expected DkgEndBegin message"
3126        );
3127
3128        // Send the DkgEndBegin message to all signers and share their responses with the coordinators and signers
3129        let (outbound_messages, operation_results) =
3130            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3131        assert!(outbound_messages.is_empty());
3132        assert_eq!(operation_results.len(), 1);
3133        let OperationResult::DkgError(DkgError::DkgEndFailure {
3134            reported_failures, ..
3135        }) = &operation_results[0]
3136        else {
3137            panic!("Expected OperationResult::DkgError(DkgError::DkgEndFailure)");
3138        };
3139
3140        for (_signer_id, dkg_failure) in reported_failures {
3141            let DkgFailure::BadPublicShares(bad_shares) = dkg_failure else {
3142                panic!("Expected DkgFailure::BadPublicShares");
3143            };
3144            for bad_signer_id in bad_shares {
3145                assert!(*bad_signer_id == 0u32 || *bad_signer_id == 1u32);
3146            }
3147        }
3148        (coordinators, signers)
3149    }
3150
3151    #[test]
3152    #[cfg(feature = "with_v1")]
3153    fn all_signers_sign_v1() {
3154        all_signers_sign::<v1::Aggregator, v1::Signer>();
3155    }
3156
3157    #[test]
3158    fn all_signers_sign_v2() {
3159        all_signers_sign::<v2::Aggregator, v2::Signer>();
3160    }
3161
3162    fn all_signers_sign<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
3163        let (mut coordinators, mut signers) = all_signers_dkg::<Aggregator, Signer>(5, 2);
3164
3165        // We have started a signing round
3166        let msg = "It was many and many a year ago, in a kingdom by the sea"
3167            .as_bytes()
3168            .to_vec();
3169        let signature_type = SignatureType::Frost;
3170        let message = coordinators
3171            .first_mut()
3172            .unwrap()
3173            .start_signing_round(&msg, signature_type, None)
3174            .unwrap();
3175        assert_eq!(
3176            coordinators.first().unwrap().state,
3177            State::NonceGather(signature_type)
3178        );
3179
3180        // Send the message to all signers and gather responses by sharing with all other signers and coordinator
3181        let (outbound_messages, operation_results) =
3182            feedback_messages(&mut coordinators, &mut signers, &[message]);
3183        assert!(operation_results.is_empty());
3184        for coordinator in &coordinators {
3185            assert_eq!(coordinator.state, State::SigShareGather(signature_type));
3186        }
3187
3188        assert_eq!(outbound_messages.len(), 1);
3189        assert!(
3190            matches!(outbound_messages[0].msg, Message::SignatureShareRequest(_)),
3191            "Expected SignatureShareRequest message"
3192        );
3193        // Send the SignatureShareRequest message to all signers and share their responses with the coordinator and signers
3194        let (outbound_messages, operation_results) =
3195            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3196        assert!(outbound_messages.is_empty());
3197        assert_eq!(operation_results.len(), 1);
3198        let OperationResult::Sign(sig) = &operation_results[0] else {
3199            panic!("Expected Signature Operation result")
3200        };
3201        assert!(sig.verify(
3202            &coordinators
3203                .first()
3204                .unwrap()
3205                .aggregate_public_key
3206                .expect("No aggregate public key set!"),
3207            &msg
3208        ));
3209        for coordinator in &coordinators {
3210            assert_eq!(coordinator.state, State::Idle);
3211        }
3212    }
3213
3214    #[test]
3215    #[cfg(feature = "with_v1")]
3216    fn sign_threshold_sign_v1() {
3217        sign_threshold_sign::<v1::Aggregator, v1::Signer>();
3218    }
3219
3220    #[test]
3221    fn sign_threshold_sign_v2() {
3222        sign_threshold_sign::<v2::Aggregator, v2::Signer>();
3223    }
3224
3225    fn sign_threshold_sign<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
3226        let (mut coordinators, mut signers) = all_signers_dkg::<Aggregator, Signer>(5, 2);
3227
3228        // change the sign_threshold to num_keys
3229        for coordinator in &mut coordinators {
3230            coordinator.config.sign_threshold = coordinator.config.num_keys;
3231        }
3232
3233        // We have started a signing round
3234        let msg = "It was many and many a year ago, in a kingdom by the sea"
3235            .as_bytes()
3236            .to_vec();
3237        let signature_type = SignatureType::Frost;
3238        let message = coordinators
3239            .first_mut()
3240            .unwrap()
3241            .start_signing_round(&msg, signature_type, None)
3242            .unwrap();
3243        assert_eq!(
3244            coordinators.first().unwrap().state,
3245            State::NonceGather(signature_type)
3246        );
3247
3248        // Send the message to all signers and gather responses by sharing with all other signers and coordinator
3249        let (outbound_messages, operation_results) =
3250            feedback_messages(&mut coordinators, &mut signers, &[message]);
3251        assert!(operation_results.is_empty());
3252        for coordinator in &coordinators {
3253            assert_eq!(coordinator.state, State::SigShareGather(signature_type));
3254        }
3255
3256        // check to see that we have nonces from all signers
3257        for coordinator in &coordinators {
3258            let sign_round_info = &coordinator.message_nonces[&msg];
3259            assert_eq!(sign_round_info.public_nonces.len(), signers.len());
3260        }
3261
3262        assert_eq!(outbound_messages.len(), 1);
3263        assert!(
3264            matches!(outbound_messages[0].msg, Message::SignatureShareRequest(_)),
3265            "Expected SignatureShareRequest message"
3266        );
3267        // Send the SignatureShareRequest message to all signers and share their responses with the coordinator and signers
3268        let (outbound_messages, operation_results) =
3269            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3270
3271        // check to see that we have signature shares from all signers
3272        for coordinator in &coordinators {
3273            assert_eq!(coordinator.signature_shares.len(), signers.len());
3274        }
3275
3276        assert!(outbound_messages.is_empty());
3277        assert_eq!(operation_results.len(), 1);
3278        let OperationResult::Sign(sig) = &operation_results[0] else {
3279            panic!("Expected Signature Operation result")
3280        };
3281        assert!(sig.verify(
3282            &coordinators
3283                .first()
3284                .unwrap()
3285                .aggregate_public_key
3286                .expect("No aggregate public key set!"),
3287            &msg
3288        ));
3289        for coordinator in &coordinators {
3290            assert_eq!(coordinator.state, State::Idle);
3291        }
3292    }
3293
3294    #[test]
3295    #[cfg(feature = "with_v1")]
3296    fn minimum_signers_sign_v1() {
3297        minimum_signers_sign::<v1::Aggregator, v1::Signer>();
3298    }
3299
3300    #[test]
3301    fn minimum_signers_sign_v2() {
3302        minimum_signers_sign::<v2::Aggregator, v2::Signer>();
3303    }
3304
3305    fn minimum_signers_sign<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
3306        let num_signers = 10;
3307        let keys_per_signer = 2;
3308
3309        let (mut coordinators, mut signers) =
3310            minimum_signers_dkg::<Aggregator, Signer>(num_signers, keys_per_signer);
3311        let config = coordinators.first().unwrap().get_config();
3312
3313        // Figure out how many signers we can remove and still be above the threshold
3314        let num_keys = config.num_keys as f64;
3315        let threshold = config.threshold as f64;
3316        let mut num_signers_to_remove =
3317            ((num_keys - threshold) / keys_per_signer as f64).floor() as usize;
3318        if num_signers as usize > signers.len() {
3319            num_signers_to_remove -= (num_signers - signers.len() as u32) as usize;
3320        }
3321
3322        signers.truncate(signers.len().saturating_sub(num_signers_to_remove));
3323
3324        // Start a signing round
3325        let msg = "It was many and many a year ago, in a kingdom by the sea"
3326            .as_bytes()
3327            .to_vec();
3328        let signature_type = SignatureType::Frost;
3329        let message = coordinators
3330            .first_mut()
3331            .unwrap()
3332            .start_signing_round(&msg, signature_type, None)
3333            .unwrap();
3334        assert_eq!(
3335            coordinators.first().unwrap().state,
3336            State::NonceGather(signature_type)
3337        );
3338
3339        // Send the message to all signers and gather responses by sharing with all other signers and coordinator
3340        let (outbound_messages, operation_results) =
3341            feedback_messages(&mut coordinators, &mut signers, &[message]);
3342        assert!(operation_results.is_empty());
3343        for coordinator in &coordinators {
3344            assert_eq!(coordinator.state, State::SigShareGather(signature_type));
3345        }
3346
3347        assert_eq!(outbound_messages.len(), 1);
3348        assert!(
3349            matches!(outbound_messages[0].msg, Message::SignatureShareRequest(_)),
3350            "Expected SignatureShareRequest message"
3351        );
3352        // Send the SignatureShareRequest message to all signers and share their responses with the coordinator and signers
3353        let (outbound_messages, operation_results) =
3354            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3355        assert!(outbound_messages.is_empty());
3356        assert_eq!(operation_results.len(), 1);
3357        let OperationResult::Sign(sig) = &operation_results[0] else {
3358            panic!("Expected Signature Operation result");
3359        };
3360        assert!(sig.verify(
3361            &coordinators
3362                .first()
3363                .unwrap()
3364                .aggregate_public_key
3365                .expect("No aggregate public key set!"),
3366            &msg
3367        ));
3368
3369        for coordinator in &coordinators {
3370            assert_eq!(coordinator.state, State::Idle);
3371        }
3372    }
3373
3374    #[test]
3375    #[cfg(feature = "with_v1")]
3376    fn missing_public_keys_sign_v1() {
3377        missing_public_keys_sign::<v1::Aggregator, v1::Signer>();
3378    }
3379
3380    #[test]
3381    fn missing_public_keys_sign_v2() {
3382        missing_public_keys_sign::<v2::Aggregator, v2::Signer>();
3383    }
3384
3385    fn missing_public_keys_sign<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
3386        let num_signers = 10;
3387        let keys_per_signer = 2;
3388
3389        let (mut coordinators, mut signers) =
3390            all_signers_dkg::<Aggregator, Signer>(num_signers, keys_per_signer);
3391
3392        // Let us also remove that signers public key from the config including all of its key ids
3393        let mut removed_signer = signers.pop().expect("Failed to pop signer");
3394        let public_key = removed_signer
3395            .public_keys
3396            .signers
3397            .remove(&removed_signer.signer_id)
3398            .expect("Failed to remove public key");
3399        removed_signer
3400            .public_keys
3401            .key_ids
3402            .retain(|_k, pk| pk.to_bytes() != public_key.to_bytes());
3403
3404        for signer in signers.iter_mut() {
3405            signer.public_keys = removed_signer.public_keys.clone();
3406        }
3407
3408        // Start a signing round
3409        let msg = "It was many and many a year ago, in a kingdom by the sea"
3410            .as_bytes()
3411            .to_vec();
3412        let signature_type = SignatureType::Frost;
3413        let message = coordinators
3414            .first_mut()
3415            .unwrap()
3416            .start_signing_round(&msg, signature_type, None)
3417            .unwrap();
3418        assert_eq!(
3419            coordinators.first().unwrap().state,
3420            State::NonceGather(signature_type)
3421        );
3422
3423        // Send the message to all signers and gather responses by sharing with all other signers and coordinator
3424        let (outbound_messages, operation_results) =
3425            feedback_messages(&mut coordinators, &mut signers, &[message]);
3426        assert!(operation_results.is_empty());
3427        for coordinator in &coordinators {
3428            assert_eq!(coordinator.state, State::SigShareGather(signature_type));
3429        }
3430
3431        assert_eq!(outbound_messages.len(), 1);
3432        assert!(
3433            matches!(&outbound_messages[0].msg, Message::SignatureShareRequest(_)),
3434            "Expected SignatureShareRequest message"
3435        );
3436        // Send the SignatureShareRequest message to all signers and share their responses with the coordinator and signers
3437        let (outbound_messages, operation_results) =
3438            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3439        assert!(outbound_messages.is_empty());
3440        assert_eq!(operation_results.len(), 1);
3441        let OperationResult::Sign(sig) = &operation_results[0] else {
3442            panic!("Expected Signature Operation result");
3443        };
3444        assert!(sig.verify(
3445            &coordinators
3446                .first()
3447                .unwrap()
3448                .aggregate_public_key
3449                .expect("No aggregate public key set!"),
3450            &msg
3451        ));
3452
3453        for coordinator in &coordinators {
3454            assert_eq!(coordinator.state, State::Idle);
3455        }
3456    }
3457
3458    #[test]
3459    #[cfg(feature = "with_v1")]
3460    fn insufficient_signers_sign_v1() {
3461        insufficient_signers_sign::<v1::Aggregator, v1::Signer>();
3462    }
3463
3464    #[test]
3465    fn insufficient_signers_sign_v2() {
3466        insufficient_signers_sign::<v2::Aggregator, v2::Signer>();
3467    }
3468
3469    fn insufficient_signers_sign<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
3470        let num_signers = 5;
3471        let keys_per_signer = 2;
3472        let (mut coordinators, mut signers) =
3473            setup_with_timeouts::<FireCoordinator<Aggregator>, Signer>(
3474                num_signers,
3475                keys_per_signer,
3476                None,
3477                None,
3478                None,
3479                Some(Duration::from_millis(128)),
3480                Some(Duration::from_millis(128)),
3481                false,
3482            );
3483        let config = coordinators.first().unwrap().get_config();
3484
3485        // We have started a dkg round
3486        let message = coordinators
3487            .first_mut()
3488            .unwrap()
3489            .start_dkg_round(None)
3490            .unwrap();
3491        assert!(coordinators.first().unwrap().aggregate_public_key.is_none());
3492        assert_eq!(coordinators.first().unwrap().state, State::DkgPublicGather);
3493
3494        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinator
3495        let (outbound_messages, operation_results) =
3496            feedback_messages(&mut coordinators, &mut signers, &[message]);
3497        assert!(operation_results.is_empty());
3498        for coordinator in &coordinators {
3499            assert_eq!(coordinator.state, State::DkgPublicSharesDoneGather);
3500        }
3501
3502        assert_eq!(outbound_messages.len(), 1);
3503        assert!(
3504            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
3505            "Expected DkgPublicSharesDone message"
3506        );
3507
3508        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
3509        let (outbound_messages, operation_results) =
3510            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3511        assert!(operation_results.is_empty());
3512        for coordinator in &coordinators {
3513            assert_eq!(coordinator.state, State::DkgPrivateGather);
3514        }
3515
3516        assert_eq!(outbound_messages.len(), 1);
3517        assert!(
3518            matches!(&outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
3519            "Expected DkgPrivateBegin message"
3520        );
3521
3522        // Send the DKG Private Begin message to all signers and share their responses with the coordinators and signers
3523        let (outbound_messages, operation_results) =
3524            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3525        assert!(operation_results.is_empty());
3526        assert_eq!(outbound_messages.len(), 1);
3527        assert!(
3528            matches!(&outbound_messages[0].msg, Message::DkgPrivateSharesDone(_)),
3529            "Expected DkgPrivateSharesDone message"
3530        );
3531
3532        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
3533        let (outbound_messages, operation_results) =
3534            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3535        assert!(operation_results.is_empty());
3536        assert_eq!(outbound_messages.len(), 1);
3537        assert!(
3538            matches!(&outbound_messages[0].msg, Message::DkgEndBegin(_)),
3539            "Expected DkgEndBegin message"
3540        );
3541
3542        // Send the DKG End Begin message to all signers and share their responses with the coordinator and signers
3543        let (outbound_messages, operation_results) =
3544            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
3545        assert!(outbound_messages.is_empty());
3546        assert_eq!(operation_results.len(), 1);
3547        let OperationResult::Dkg(point) = operation_results[0] else {
3548            panic!("Expected Dkg Operationr result");
3549        };
3550        assert_ne!(point, Point::default());
3551        for coordinator in &coordinators {
3552            assert_eq!(coordinator.aggregate_public_key, Some(point));
3553            assert_eq!(coordinator.state, State::Idle);
3554        }
3555
3556        // Figure out how many signers we can remove and still be above the threshold
3557        let num_keys = config.num_keys as f64;
3558        let threshold = config.threshold as f64;
3559        let num_signers_to_remove =
3560            (((num_keys - threshold) / keys_per_signer as f64).floor() + 1_f64) as usize;
3561        let mut insufficient_coordinators = coordinators.clone();
3562        let mut insufficient_signers = signers.clone();
3563
3564        insufficient_signers.truncate(
3565            insufficient_signers
3566                .len()
3567                .saturating_sub(num_signers_to_remove),
3568        );
3569
3570        // Start a signing round with an insufficient number of signers
3571        let msg = "It was many and many a year ago, in a kingdom by the sea"
3572            .as_bytes()
3573            .to_vec();
3574        let signature_type = SignatureType::Frost;
3575        let message = insufficient_coordinators
3576            .first_mut()
3577            .unwrap()
3578            .start_signing_round(&msg, signature_type, None)
3579            .unwrap();
3580        assert_eq!(
3581            insufficient_coordinators.first().unwrap().state,
3582            State::NonceGather(signature_type)
3583        );
3584
3585        // Send the message to all signers and gather responses by sharing with all other signers and coordinator
3586        let (outbound_messages, operation_results) = feedback_messages(
3587            &mut insufficient_coordinators,
3588            &mut insufficient_signers,
3589            &[message],
3590        );
3591        assert!(operation_results.is_empty());
3592        for coordinator in &insufficient_coordinators {
3593            assert_eq!(coordinator.state, State::NonceGather(signature_type));
3594        }
3595
3596        assert!(outbound_messages.is_empty());
3597
3598        // Sleep long enough to hit the timeout
3599        thread::sleep(Duration::from_millis(256));
3600
3601        let (outbound_message, operation_result) = insufficient_coordinators
3602            .first_mut()
3603            .unwrap()
3604            .process_timeout()
3605            .unwrap();
3606
3607        assert!(outbound_message.is_none());
3608        assert!(operation_result.is_some());
3609        for coordinator in &insufficient_coordinators {
3610            assert_eq!(coordinator.state, State::NonceGather(signature_type));
3611        }
3612
3613        assert!(
3614            matches!(
3615                operation_result.unwrap(),
3616                OperationResult::SignError(SignError::NonceTimeout(..))
3617            ),
3618            "Expected OperationResult::SignError(SignError::NonceTimeout)"
3619        );
3620
3621        // Start a new signing round with a sufficient number of signers for nonces but not sig shares
3622        let mut insufficient_coordinators = coordinators.clone();
3623        let mut insufficient_signers = signers.clone();
3624
3625        let message = insufficient_coordinators
3626            .first_mut()
3627            .unwrap()
3628            .start_signing_round(&msg, signature_type, None)
3629            .unwrap();
3630        assert_eq!(
3631            insufficient_coordinators.first().unwrap().state,
3632            State::NonceGather(signature_type)
3633        );
3634
3635        // Send the message to all signers and gather responses by sharing with all other signers and insufficient_coordinator
3636        let (outbound_messages, operation_results) = feedback_messages(
3637            &mut insufficient_coordinators,
3638            &mut insufficient_signers,
3639            &[message],
3640        );
3641        assert!(operation_results.is_empty());
3642        for coordinator in &insufficient_coordinators {
3643            assert_eq!(coordinator.state, State::SigShareGather(signature_type));
3644        }
3645
3646        assert_eq!(outbound_messages.len(), 1);
3647
3648        let mut malicious = Vec::new();
3649
3650        // now remove signers so the number is insufficient
3651        let num_signers_to_drain = insufficient_signers
3652            .len()
3653            .saturating_sub(num_signers_to_remove);
3654        malicious.extend(insufficient_signers.drain(num_signers_to_drain..));
3655
3656        // Send the SignatureShareRequest message to all signers and share their responses with the coordinator and signers
3657        let (outbound_messages, operation_results) = feedback_messages(
3658            &mut insufficient_coordinators,
3659            &mut insufficient_signers,
3660            &outbound_messages,
3661        );
3662        assert!(outbound_messages.is_empty());
3663        assert!(operation_results.is_empty());
3664
3665        for coordinator in &insufficient_coordinators {
3666            assert_eq!(coordinator.state, State::SigShareGather(signature_type));
3667        }
3668
3669        // Sleep long enough to hit the timeout
3670        thread::sleep(Duration::from_millis(256));
3671
3672        let (outbound_message, operation_result) = insufficient_coordinators
3673            .first_mut()
3674            .unwrap()
3675            .process_timeout()
3676            .unwrap();
3677
3678        assert!(outbound_message.is_some());
3679        assert!(operation_result.is_none());
3680        assert_eq!(
3681            insufficient_coordinators.first().unwrap().state,
3682            State::NonceGather(signature_type)
3683        );
3684
3685        // put the malicious signers back in
3686        insufficient_signers.append(&mut malicious);
3687
3688        // Send the NonceRequest message to all signers and share their responses with the coordinator and signers
3689        let (outbound_messages, operation_results) = feedback_messages(
3690            &mut insufficient_coordinators,
3691            &mut insufficient_signers,
3692            &[outbound_message.unwrap()],
3693        );
3694        assert_eq!(outbound_messages.len(), 1);
3695        assert!(operation_results.is_empty());
3696
3697        for coordinator in &insufficient_coordinators {
3698            assert_eq!(coordinator.state, State::SigShareGather(signature_type));
3699        }
3700
3701        // again remove signers so the number is insufficient
3702        let num_signers_to_drain = insufficient_signers
3703            .len()
3704            .saturating_sub(num_signers_to_remove);
3705        malicious.extend(insufficient_signers.drain(num_signers_to_drain..));
3706
3707        // Send the SignatureShareRequest message to all signers and share their responses with the coordinator and signers
3708        let (outbound_messages, operation_results) = feedback_messages(
3709            &mut insufficient_coordinators,
3710            &mut insufficient_signers,
3711            &outbound_messages,
3712        );
3713        assert!(outbound_messages.is_empty());
3714        assert!(operation_results.is_empty());
3715
3716        for coordinator in &insufficient_coordinators {
3717            assert_eq!(coordinator.state, State::SigShareGather(signature_type));
3718        }
3719
3720        // Sleep long enough to hit the timeout
3721        thread::sleep(Duration::from_millis(256));
3722
3723        let (outbound_message, operation_result) = insufficient_coordinators
3724            .first_mut()
3725            .unwrap()
3726            .process_timeout()
3727            .unwrap();
3728
3729        assert!(outbound_message.is_none());
3730        assert!(operation_result.is_some());
3731        assert_eq!(
3732            insufficient_coordinators.first_mut().unwrap().state,
3733            State::SigShareGather(signature_type)
3734        );
3735        assert!(
3736            matches!(
3737                operation_result.unwrap(),
3738                OperationResult::SignError(SignError::InsufficientSigners(_))
3739            ),
3740            "Expected OperationResult::SignError(SignError::InsufficientSigners)"
3741        );
3742    }
3743
3744    #[test]
3745    #[cfg(feature = "with_v1")]
3746    fn multiple_nonce_request_messages_sign_v1() {
3747        multiple_nonce_request_messages::<v1::Aggregator, v1::Signer>();
3748    }
3749
3750    #[test]
3751    fn multiple_nonce_request_messages_sign_v2() {
3752        multiple_nonce_request_messages::<v2::Aggregator, v2::Signer>();
3753    }
3754
3755    fn multiple_nonce_request_messages<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
3756        let num_signers = 12;
3757        let keys_per_signer = 1;
3758        let (mut coordinators, mut signers) =
3759            all_signers_dkg::<Aggregator, Signer>(num_signers, keys_per_signer);
3760
3761        // Start a signing round
3762        let orig_msg = "It was many and many a year ago, in a kingdom by the sea"
3763            .as_bytes()
3764            .to_vec();
3765        let signature_type = SignatureType::Frost;
3766        let message = coordinators
3767            .first_mut()
3768            .unwrap()
3769            .start_signing_round(&orig_msg, signature_type, None)
3770            .unwrap();
3771
3772        let mut alt_packet = message.clone();
3773        assert_eq!(
3774            coordinators.first().unwrap().state,
3775            State::NonceGather(signature_type)
3776        );
3777
3778        // Send the original message to the first 1/4 of the signers and gather responses by sharing with the rest of the signers and the coordinators
3779        let signers_len = signers.len();
3780        let (outbound_messages, operation_results) = feedback_messages(
3781            &mut coordinators,
3782            &mut signers[0..signers_len / 4],
3783            &[message],
3784        );
3785
3786        let alt_message = "It was many and many a year ago, in a kingdom by the hill"
3787            .as_bytes()
3788            .to_vec();
3789        let Message::NonceRequest(nonce_request) = &mut alt_packet.msg else {
3790            panic!("Expected NonceRequest message");
3791        };
3792        nonce_request.message = alt_message.clone();
3793
3794        // Send the alternative message to the last 3/4 of signers and gather responses by sharing with the rest of the signers and the coordinators
3795        let (alt_outbound_messages, alt_operation_results) = feedback_messages(
3796            &mut coordinators,
3797            &mut signers[signers_len / 4..],
3798            &[alt_packet],
3799        );
3800
3801        assert!(operation_results.is_empty());
3802        assert!(alt_operation_results.is_empty());
3803        for coordinator in &coordinators {
3804            assert_eq!(coordinator.state, State::SigShareGather(signature_type));
3805        }
3806        // Assert that the first 1/4 signers did not receive a result
3807        assert!(outbound_messages.is_empty());
3808        assert_eq!(alt_outbound_messages.len(), 1);
3809        assert!(
3810            matches!(
3811                &alt_outbound_messages[0].msg,
3812                Message::SignatureShareRequest(_)
3813            ),
3814            "Expected SignatureShareRequest message"
3815        );
3816
3817        // Send the SignatureShareRequest message to all signers and share their responses with the coordinator and signers
3818        let (outbound_messages, operation_results) =
3819            feedback_messages(&mut coordinators, &mut signers, &alt_outbound_messages);
3820        assert!(outbound_messages.is_empty());
3821        assert_eq!(operation_results.len(), 1);
3822        let OperationResult::Sign(sig) = &operation_results[0] else {
3823            panic!("Expected Signature Operation result");
3824        };
3825        // Verify that the winning message was the alternative message that had majority vote
3826        assert!(sig.verify(
3827            &coordinators
3828                .first()
3829                .unwrap()
3830                .aggregate_public_key
3831                .expect("No aggregate public key set!"),
3832            &alt_message
3833        ));
3834
3835        for coordinator in &coordinators {
3836            assert_eq!(coordinator.state, State::Idle);
3837        }
3838    }
3839
3840    #[test]
3841    #[cfg(feature = "with_v1")]
3842    fn old_round_ids_are_ignored_v1() {
3843        old_round_ids_are_ignored::<v1::Aggregator, v1::Signer>();
3844    }
3845
3846    #[test]
3847    fn old_round_ids_are_ignored_v2() {
3848        old_round_ids_are_ignored::<v2::Aggregator, v2::Signer>();
3849    }
3850
3851    fn old_round_ids_are_ignored<Aggregator: AggregatorTrait, Signer: SignerTrait>() {
3852        let (mut coordinators, _) = setup::<FireCoordinator<Aggregator>, Signer>(3, 10);
3853        for coordinator in &mut coordinators {
3854            let id: u64 = 10;
3855            let old_id = id;
3856            coordinator.current_dkg_id = id;
3857            coordinator.current_sign_id = id;
3858            // Attempt to start an old DKG round
3859            let (packets, results) = coordinator
3860                .process(&Packet {
3861                    sig: vec![],
3862                    msg: Message::DkgBegin(DkgBegin { dkg_id: old_id }),
3863                })
3864                .unwrap();
3865            assert!(packets.is_none());
3866            assert!(results.is_none());
3867            assert_eq!(coordinator.state, State::Idle);
3868            assert_eq!(coordinator.current_dkg_id, id);
3869
3870            // Attempt to start the same DKG round
3871            let (packets, results) = coordinator
3872                .process(&Packet {
3873                    sig: vec![],
3874                    msg: Message::DkgBegin(DkgBegin { dkg_id: id }),
3875                })
3876                .unwrap();
3877            assert!(packets.is_none());
3878            assert!(results.is_none());
3879            assert_eq!(coordinator.state, State::Idle);
3880            assert_eq!(coordinator.current_dkg_id, id);
3881
3882            // Attempt to start an old Sign round
3883            let (packets, results) = coordinator
3884                .process(&Packet {
3885                    sig: vec![],
3886                    msg: Message::NonceRequest(NonceRequest {
3887                        dkg_id: id,
3888                        sign_id: old_id,
3889                        message: vec![],
3890                        sign_iter_id: id,
3891                        signature_type: SignatureType::Frost,
3892                    }),
3893                })
3894                .unwrap();
3895            assert!(packets.is_none());
3896            assert!(results.is_none());
3897            assert_eq!(coordinator.state, State::Idle);
3898            assert_eq!(coordinator.current_sign_id, id);
3899
3900            // Attempt to start the same Sign round
3901            let (packets, results) = coordinator
3902                .process(&Packet {
3903                    sig: vec![],
3904                    msg: Message::NonceRequest(NonceRequest {
3905                        dkg_id: id,
3906                        sign_id: id,
3907                        message: vec![],
3908                        sign_iter_id: id,
3909                        signature_type: SignatureType::Frost,
3910                    }),
3911                })
3912                .unwrap();
3913            assert!(packets.is_none());
3914            assert!(results.is_none());
3915            assert_eq!(coordinator.state, State::Idle);
3916            assert_eq!(coordinator.current_sign_id, id);
3917        }
3918    }
3919
3920    #[test]
3921    #[cfg(feature = "with_v1")]
3922    fn gen_nonces_v1() {
3923        gen_nonces::<FireCoordinator<v1::Aggregator>, v1::Signer>(5, 1);
3924    }
3925
3926    #[test]
3927    fn gen_nonces_v2() {
3928        gen_nonces::<FireCoordinator<v2::Aggregator>, v2::Signer>(5, 1);
3929    }
3930
3931    #[test]
3932    #[cfg(feature = "with_v1")]
3933    fn bad_signature_share_request_v1() {
3934        bad_signature_share_request::<FireCoordinator<v1::Aggregator>, v1::Signer>(5, 2);
3935    }
3936
3937    #[test]
3938    fn bad_signature_share_request_v2() {
3939        bad_signature_share_request::<FireCoordinator<v2::Aggregator>, v2::Signer>(5, 2);
3940    }
3941
3942    #[test]
3943    #[cfg(feature = "with_v1")]
3944    fn invalid_nonce_v1() {
3945        invalid_nonce::<FireCoordinator<v1::Aggregator>, v1::Signer>(5, 2);
3946    }
3947
3948    #[test]
3949    fn invalid_nonce_v2() {
3950        invalid_nonce::<FireCoordinator<v2::Aggregator>, v2::Signer>(5, 2);
3951    }
3952
3953    #[test]
3954    #[cfg(feature = "with_v1")]
3955    fn one_signer_bad_threshold_v1() {
3956        one_signer_bad_threshold::<v1::Aggregator, v1::Signer>();
3957    }
3958
3959    #[test]
3960    fn one_signer_bad_threshold_v2() {
3961        one_signer_bad_threshold::<v2::Aggregator, v2::Signer>();
3962    }
3963
3964    fn one_signer_bad_threshold<Aggregator: AggregatorTrait, SignerType: SignerTrait>() {
3965        let mut rng = create_rng();
3966        let (mut coordinators, mut signers) =
3967            setup::<FireCoordinator<Aggregator>, SignerType>(10, 1);
3968
3969        // persist one signer, change the threshold, reset polys
3970        let mut state = signers[0].save();
3971
3972        state.threshold -= 1;
3973        state.signer.threshold -= 1;
3974
3975        signers[0] = Signer::<SignerType>::load(&state);
3976
3977        signers[0].signer.reset_polys(&mut rng);
3978
3979        // We have started a dkg round
3980        let message = coordinators
3981            .first_mut()
3982            .unwrap()
3983            .start_dkg_round(None)
3984            .unwrap();
3985        assert!(coordinators
3986            .first_mut()
3987            .unwrap()
3988            .get_aggregate_public_key()
3989            .is_none());
3990        assert_eq!(
3991            coordinators.first_mut().unwrap().get_state(),
3992            State::DkgPublicGather
3993        );
3994
3995        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinator
3996        let (outbound_messages, operation_results) =
3997            feedback_messages(&mut coordinators, &mut signers, &[message]);
3998        assert!(operation_results.is_empty());
3999        for coordinator in coordinators.iter() {
4000            assert_eq!(coordinator.get_state(), State::DkgPublicSharesDoneGather);
4001        }
4002
4003        assert_eq!(outbound_messages.len(), 1);
4004        assert!(
4005            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
4006            "Expected DkgPublicSharesDone message"
4007        );
4008
4009        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
4010        let (outbound_messages, operation_results) =
4011            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
4012        assert!(operation_results.is_empty());
4013        for coordinator in coordinators.iter() {
4014            assert_eq!(coordinator.get_state(), State::DkgPrivateGather);
4015        }
4016
4017        assert_eq!(outbound_messages.len(), 1);
4018        assert!(
4019            matches!(outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
4020            "Expected DkgPrivateBegin message"
4021        );
4022
4023        // Send the DKG Private Begin message to all signers and share their responses with the coordinator and signers
4024        let (outbound_messages, operation_results) =
4025            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
4026        assert!(operation_results.is_empty());
4027        assert_eq!(outbound_messages.len(), 1);
4028        assert!(
4029            matches!(outbound_messages[0].msg, Message::DkgPrivateSharesDone(_)),
4030            "Expected DkgPrivateSharesDone message"
4031        );
4032
4033        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
4034        let (outbound_messages, operation_results) =
4035            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
4036        assert!(operation_results.is_empty());
4037        assert_eq!(outbound_messages.len(), 1);
4038        assert!(
4039            matches!(outbound_messages[0].msg, Message::DkgEndBegin(_)),
4040            "Expected DkgEndBegin message"
4041        );
4042
4043        // Send the DkgEndBegin message to all signers and share their responses with the coordinator and signers
4044        let (outbound_messages, operation_results) =
4045            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
4046        assert!(outbound_messages.is_empty());
4047        assert_eq!(operation_results.len(), 1);
4048        let OperationResult::DkgError(DkgError::DkgEndFailure {
4049            reported_failures,
4050            malicious_signers,
4051        }) = &operation_results[0]
4052        else {
4053            panic!(
4054                "Expected OperationResult::DkgError(DkgError::DkgEndFailure), got {:?}",
4055                operation_results[0]
4056            );
4057        };
4058        for i in 1..10 {
4059            match reported_failures.get(&i) {
4060                Some(DkgFailure::BadPublicShares(set)) => {
4061                    if set.len() != 1 {
4062                        panic!("signer {i} should have reported a single BadPublicShares");
4063                    } else if !set.contains(&0) {
4064                        panic!("signer {i} should have reported BadPublicShares from signer 0");
4065                    }
4066                }
4067                Some(failure) => {
4068                    panic!("signer {i} should have reported BadPublicShares, instead reported {failure:?}");
4069                }
4070                None => {
4071                    panic!("signer {i} should have reported BadPublicShares");
4072                }
4073            }
4074        }
4075
4076        match reported_failures.get(&0) {
4077            Some(DkgFailure::BadPublicShares(set)) => {
4078                if set.len() != 9 {
4079                    panic!("signer 0 should have reported BadPublicShares from all others");
4080                } else if set.contains(&0) {
4081                    panic!("signer 0 should not have reported BadPublicShares from signer 0");
4082                }
4083            }
4084            Some(failure) => {
4085                panic!(
4086                    "signer 0 should have reported BadPublicShares, instead reported {failure:?}"
4087                );
4088            }
4089            None => {
4090                panic!("signer 0 should have reported BadPublicShares");
4091            }
4092        }
4093
4094        if !malicious_signers.len() == 1 || !malicious_signers.contains(&0) {
4095            panic!(
4096                "Coordinator should have marked signer 0 as malicious, instead marked {malicious_signers:?}",
4097            );
4098        }
4099    }
4100
4101    #[test]
4102    #[cfg(feature = "with_v1")]
4103    fn bad_dkg_threshold_v1() {
4104        bad_dkg_threshold::<v1::Aggregator, v1::Signer>();
4105    }
4106
4107    #[test]
4108    fn bad_dkg_threshold_v2() {
4109        bad_dkg_threshold::<v2::Aggregator, v2::Signer>();
4110    }
4111
4112    fn bad_dkg_threshold<Aggregator: AggregatorTrait, SignerType: SignerTrait>() {
4113        let (mut coordinators, mut signers) =
4114            setup::<FireCoordinator<Aggregator>, SignerType>(10, 1);
4115
4116        // We have started a dkg round
4117        let message = coordinators
4118            .first_mut()
4119            .unwrap()
4120            .start_dkg_round(None)
4121            .unwrap();
4122        assert!(coordinators
4123            .first_mut()
4124            .unwrap()
4125            .get_aggregate_public_key()
4126            .is_none());
4127        assert_eq!(
4128            coordinators.first_mut().unwrap().get_state(),
4129            State::DkgPublicGather
4130        );
4131
4132        // Send the DKG Begin message to all signers and gather responses by sharing with all other signers and coordinator
4133        let (outbound_messages, operation_results) =
4134            feedback_messages(&mut coordinators, &mut signers, &[message]);
4135        assert!(operation_results.is_empty());
4136        for coordinator in coordinators.iter() {
4137            assert_eq!(coordinator.get_state(), State::DkgPublicSharesDoneGather);
4138        }
4139
4140        assert_eq!(outbound_messages.len(), 1);
4141        assert!(
4142            matches!(&outbound_messages[0].msg, Message::DkgPublicSharesDone(_)),
4143            "Expected DkgPublicSharesDone message"
4144        );
4145
4146        // Send DkgPublicSharesDone to signers and collect their acks back to the coordinator
4147        let (outbound_messages, operation_results) =
4148            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
4149        assert!(operation_results.is_empty());
4150        for coordinator in coordinators.iter() {
4151            assert_eq!(coordinator.get_state(), State::DkgPrivateGather);
4152        }
4153
4154        assert_eq!(outbound_messages.len(), 1);
4155        assert!(
4156            matches!(outbound_messages[0].msg, Message::DkgPrivateBegin(_)),
4157            "Expected DkgPrivateBegin message"
4158        );
4159
4160        // Send the DKG Private Begin message to all signers and share their responses with the coordinator and signers
4161        let (outbound_messages, operation_results) =
4162            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
4163        assert!(operation_results.is_empty());
4164        assert_eq!(outbound_messages.len(), 1);
4165        assert!(
4166            matches!(&outbound_messages[0].msg, Message::DkgPrivateSharesDone(_)),
4167            "Expected DkgPrivateSharesDone message"
4168        );
4169
4170        // Send DkgPrivateSharesDone to signers and collect their acks back to the coordinator
4171        let (outbound_messages, operation_results) =
4172            feedback_messages(&mut coordinators, &mut signers, &outbound_messages);
4173        assert!(operation_results.is_empty());
4174        assert_eq!(outbound_messages.len(), 1);
4175        assert!(
4176            matches!(&outbound_messages[0].msg, Message::DkgEndBegin(_)),
4177            "Expected DkgEndBegin message"
4178        );
4179
4180        // alter the DkgEndBegin message
4181        let mut packet = outbound_messages[0].clone();
4182        if let Message::DkgEndBegin(ref mut dkg_end_begin) = packet.msg {
4183            dkg_end_begin.signer_ids = vec![0u32];
4184        }
4185
4186        // Send the DkgEndBegin message to all signers and share their responses with the coordinator and signers
4187        let (outbound_messages, operation_results) =
4188            feedback_messages(&mut coordinators, &mut signers, &[packet]);
4189        assert!(outbound_messages.is_empty());
4190        assert_eq!(operation_results.len(), 1);
4191        let OperationResult::DkgError(DkgError::DkgEndFailure {
4192            reported_failures, ..
4193        }) = &operation_results[0]
4194        else {
4195            panic!("Expected DkgEndFailure got {:?}", operation_results[0]);
4196        };
4197        for (signer_id, failure) in reported_failures {
4198            assert!(
4199                matches!(failure, DkgFailure::Threshold),
4200                "{signer_id} had wrong failure {failure:?}"
4201            );
4202        }
4203    }
4204
4205    #[test]
4206    #[cfg(feature = "with_v1")]
4207    fn empty_public_shares_v1() {
4208        empty_public_shares::<FireCoordinator<v1::Aggregator>, v1::Signer>(5, 2);
4209    }
4210
4211    #[test]
4212    fn empty_public_shares_v2() {
4213        empty_public_shares::<FireCoordinator<v2::Aggregator>, v2::Signer>(5, 2);
4214    }
4215
4216    #[test]
4217    #[cfg(feature = "with_v1")]
4218    fn empty_private_shares_v1() {
4219        empty_private_shares::<FireCoordinator<v1::Aggregator>, v1::Signer>(5, 2);
4220    }
4221
4222    #[test]
4223    fn empty_private_shares_v2() {
4224        empty_private_shares::<FireCoordinator<v2::Aggregator>, v2::Signer>(5, 2);
4225    }
4226
4227    #[test]
4228    #[cfg(feature = "with_v1")]
4229    fn verify_packet_sigs_v1() {
4230        verify_packet_sigs::<FireCoordinator<v1::Aggregator>, v1::Signer>();
4231    }
4232
4233    #[test]
4234    fn verify_packet_sigs_v2() {
4235        verify_packet_sigs::<FireCoordinator<v2::Aggregator>, v2::Signer>();
4236    }
4237
4238    #[test]
4239    #[cfg(feature = "with_v1")]
4240    fn btc_sign_verify_v1() {
4241        btc_sign_verify::<FireCoordinator<v1::Aggregator>, v1::Signer>(5, 2);
4242    }
4243
4244    #[test]
4245    fn btc_sign_verify_v2() {
4246        btc_sign_verify::<FireCoordinator<v2::Aggregator>, v2::Signer>(5, 2);
4247    }
4248}