frost-core 3.0.0

Types and traits to support implementing Flexible Round-Optimized Schnorr Threshold signature schemes (FROST).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
//! Ciphersuite-generic test functions.
#![allow(clippy::type_complexity)]
#![cfg(feature = "serialization")]

use alloc::{borrow::ToOwned, collections::BTreeMap, vec::Vec};
use rand_core::{CryptoRng, RngCore};

use crate as frost;
use crate::keys::dkg::{round1, round2};
use crate::keys::{SecretShare, SigningShare};
use crate::round1::SigningNonces;
use crate::round2::SignatureShare;
use crate::{
    keys::PublicKeyPackage, Error, Field, Group, Identifier, Signature, SigningKey, SigningPackage,
    VerifyingKey,
};

use crate::Ciphersuite;

/// Test if creating a zero SigningKey fails
pub fn check_zero_key_fails<C: Ciphersuite>() {
    let zero = <<<C as Ciphersuite>::Group as Group>::Field>::zero();
    let encoded_zero = <<<C as Ciphersuite>::Group as Group>::Field>::serialize(&zero);
    let r = SigningKey::<C>::deserialize(encoded_zero.as_ref());
    assert_eq!(r, Err(Error::MalformedSigningKey));
}

/// Test share generation with a Ciphersuite
pub fn check_share_generation<C: Ciphersuite, R: RngCore + CryptoRng>(mut rng: R) {
    let secret = crate::SigningKey::<C>::new(&mut rng);
    // Simulate serialization / deserialization to ensure it works
    let secret = SigningKey::deserialize(&secret.serialize()).unwrap();

    let max_signers = 5;
    let min_signers = 3;

    let coefficients =
        frost::keys::generate_coefficients::<C, _>(min_signers as usize - 1, &mut rng);

    let secret_shares = frost::keys::generate_secret_shares(
        &secret,
        max_signers,
        min_signers,
        coefficients,
        &frost::keys::default_identifiers(max_signers),
    )
    .unwrap();

    let key_packages: Vec<frost::keys::KeyPackage<C>> = secret_shares
        .iter()
        .cloned()
        .map(|s| s.try_into().unwrap())
        .collect();

    assert_eq!(
        frost::keys::reconstruct::<C>(&key_packages)
            .unwrap()
            .serialize(),
        secret.serialize()
    );

    // Test error cases

    assert_eq!(
        frost::keys::reconstruct::<C>(&[]).unwrap_err(),
        Error::IncorrectNumberOfShares
    );

    assert_eq!(
        frost::keys::reconstruct::<C>(&key_packages[0..1]).unwrap_err(),
        Error::IncorrectNumberOfShares
    );

    let mut key_packages = key_packages;
    key_packages[0] = key_packages[1].clone();

    assert_eq!(
        frost::keys::reconstruct::<C>(&key_packages).unwrap_err(),
        Error::DuplicatedIdentifier
    );
}

/// Test share generation with a Ciphersuite
pub fn check_share_generation_fails_with_invalid_signers<C: Ciphersuite, R: RngCore + CryptoRng>(
    min_signers: u16,
    max_signers: u16,
    error: Error<C>,
    mut rng: R,
) {
    let secret = crate::SigningKey::<C>::new(&mut rng);

    // Use arbitrary number of coefficients so tests don't fail for overflow reasons
    let coefficients = frost::keys::generate_coefficients::<C, _>(3, &mut rng);

    let secret_shares = frost::keys::generate_secret_shares(
        &secret,
        max_signers,
        min_signers,
        coefficients,
        &frost::keys::default_identifiers(max_signers),
    );

    assert!(secret_shares.is_err());
    assert!(secret_shares == Err(error))
}

/// Test FROST signing with trusted dealer with a Ciphersuite.
pub fn check_sign_with_dealer<C: Ciphersuite, R: RngCore + CryptoRng>(
    mut rng: R,
) -> (Vec<u8>, Signature<C>, VerifyingKey<C>) {
    ////////////////////////////////////////////////////////////////////////////
    // Key generation
    ////////////////////////////////////////////////////////////////////////////

    let max_signers = 5;
    let min_signers = 3;
    let (shares, pub_key_package) = frost::keys::generate_with_dealer(
        max_signers,
        min_signers,
        frost::keys::IdentifierList::Default,
        &mut rng,
    )
    .unwrap();
    // Simulate serialization / deserialization to ensure it works
    let pub_key_package =
        PublicKeyPackage::deserialize(&pub_key_package.serialize().unwrap()).unwrap();

    // Verifies the secret shares from the dealer
    let mut key_packages: BTreeMap<frost::Identifier<C>, frost::keys::KeyPackage<C>> =
        BTreeMap::new();

    for (k, v) in shares {
        // Simulate serialization / deserialization to ensure it works
        let v = SecretShare::<C>::deserialize(&v.serialize().unwrap()).unwrap();
        let key_package = frost::keys::KeyPackage::try_from(v).unwrap();
        // Simulate serialization / deserialization to ensure it works
        let key_package =
            frost::keys::KeyPackage::deserialize(&key_package.serialize().unwrap()).unwrap();
        key_packages.insert(k, key_package);
    }
    // Check if it fails with not enough signers. Both the KeyPackages and
    // the PublicKeyPackage have their min_signers decremented so that the
    // early validation check in aggregate() passes, and we can verify that
    // the cryptographic aggregation itself fails when too few shares are used.
    let mut pub_key_package_insufficient = pub_key_package.clone();
    pub_key_package_insufficient.min_signers = Some(min_signers - 1);
    let r = check_sign(
        min_signers - 1,
        key_packages
            .iter()
            .map(|(id, k)| {
                // Decrement `min_signers` as explained above and use
                // the updated `KeyPackage`.
                let mut k = k.clone();
                k.min_signers -= 1;
                (*id, k)
            })
            .collect(),
        &mut rng,
        pub_key_package_insufficient,
    );
    assert_eq!(r, Err(Error::InvalidSignature));

    check_sign(min_signers, key_packages, rng, pub_key_package).unwrap()
}

/// Test FROST signing with trusted dealer fails with invalid numbers of signers.
pub fn check_sign_with_dealer_fails_with_invalid_signers<C: Ciphersuite, R: RngCore + CryptoRng>(
    min_signers: u16,
    max_signers: u16,
    error: Error<C>,
    mut rng: R,
) {
    let out = frost::keys::generate_with_dealer(
        max_signers,
        min_signers,
        frost::keys::IdentifierList::Default::<C>,
        &mut rng,
    );

    assert!(out.is_err());
    assert!(out == Err(error))
}

/// Test DKG part1 fails with invalid numbers of signers.
pub fn check_dkg_part1_fails_with_invalid_signers<C: Ciphersuite, R: RngCore + CryptoRng>(
    min_signers: u16,
    max_signers: u16,
    error: Error<C>,
    mut rng: R,
) {
    let out = frost::keys::dkg::part1(
        Identifier::try_from(1).unwrap(),
        max_signers,
        min_signers,
        &mut rng,
    );

    assert!(out.is_err());
    assert!(out == Err(error))
}

/// Test FROST signing with the given shares.
pub fn check_sign<C: Ciphersuite + PartialEq, R: RngCore + CryptoRng>(
    min_signers: u16,
    key_packages: BTreeMap<frost::Identifier<C>, frost::keys::KeyPackage<C>>,
    mut rng: R,
    pubkey_package: PublicKeyPackage<C>,
) -> Result<(Vec<u8>, Signature<C>, VerifyingKey<C>), Error<C>> {
    let mut nonces_map: BTreeMap<frost::Identifier<C>, frost::round1::SigningNonces<C>> =
        BTreeMap::new();
    let mut commitments_map: BTreeMap<frost::Identifier<C>, frost::round1::SigningCommitments<C>> =
        BTreeMap::new();

    ////////////////////////////////////////////////////////////////////////////
    // Round 1: generating nonces and signing commitments for each participant
    ////////////////////////////////////////////////////////////////////////////

    for participant_identifier in key_packages.keys().take(min_signers as usize) {
        // Simulate serialization / deserialization to ensure it works
        let participant_identifier =
            Identifier::deserialize(&participant_identifier.serialize()).unwrap();
        // Generate one (1) nonce and one SigningCommitments instance for each
        // participant, up to _min_signers_.
        let (nonces, commitments) = frost::round1::commit(
            key_packages
                .get(&participant_identifier)
                .unwrap()
                .signing_share(),
            &mut rng,
        );
        // Simulate serialization / deserialization to ensure it works
        let nonces = SigningNonces::deserialize(&nonces.serialize().unwrap()).unwrap();
        let commitments =
            frost::round1::SigningCommitments::deserialize(&commitments.serialize().unwrap())
                .unwrap();
        nonces_map.insert(participant_identifier, nonces);
        commitments_map.insert(participant_identifier, commitments);
    }

    // This is what the signature aggregator / coordinator needs to do:
    // - decide what message to sign
    // - take one (unused) commitment per signing participant
    let mut signature_shares = BTreeMap::new();
    let message = "message to sign".as_bytes();
    let signing_package = SigningPackage::new(commitments_map, message);
    // Simulate serialization / deserialization to ensure it works
    let signing_package =
        SigningPackage::deserialize(&signing_package.serialize().unwrap()).unwrap();

    ////////////////////////////////////////////////////////////////////////////
    // Round 2: each participant generates their signature share
    ////////////////////////////////////////////////////////////////////////////

    for participant_identifier in nonces_map.keys() {
        let key_package = key_packages.get(participant_identifier).unwrap();

        let nonces_to_use = nonces_map.get(participant_identifier).unwrap();

        check_sign_errors(
            signing_package.clone(),
            nonces_to_use.clone(),
            key_package.clone(),
        );

        // Each participant generates their signature share.
        let signature_share = frost::round2::sign(&signing_package, nonces_to_use, key_package)?;
        // Simulate serialization / deserialization to ensure it works
        let signature_share = SignatureShare::deserialize(&signature_share.serialize()).unwrap();
        signature_shares.insert(*participant_identifier, signature_share);
    }

    ////////////////////////////////////////////////////////////////////////////
    // Aggregation: collects the signing shares from all participants,
    // generates the final signature.
    ////////////////////////////////////////////////////////////////////////////

    check_aggregate_errors(
        signing_package.clone(),
        signature_shares.clone(),
        pubkey_package.clone(),
    );

    check_verifying_shares(
        pubkey_package.clone(),
        signing_package.clone(),
        signature_shares.clone(),
    );

    check_verify_signature_share(&pubkey_package, &signing_package, &signature_shares);

    // Aggregate (also verifies the signature shares)
    let group_signature = frost::aggregate(&signing_package, &signature_shares, &pubkey_package)?;
    // Simulate serialization / deserialization to ensure it works
    let group_signature = Signature::deserialize(&group_signature.serialize().unwrap()).unwrap();

    // Check that the threshold signature can be verified by the group public
    // key (the verification key).
    pubkey_package
        .verifying_key
        .verify(message, &group_signature)?;

    // Check that the threshold signature can be verified by the group public
    // key (the verification key) from KeyPackage.verifying_key
    for (participant_identifier, _) in nonces_map.clone() {
        let key_package = key_packages.get(&participant_identifier).unwrap();

        key_package
            .verifying_key
            .verify(message, &group_signature)?;
    }

    Ok((
        message.to_owned(),
        group_signature,
        pubkey_package.verifying_key,
    ))
}

fn check_sign_errors<C: Ciphersuite + PartialEq>(
    signing_package: frost::SigningPackage<C>,
    signing_nonces: frost::round1::SigningNonces<C>,
    key_package: frost::keys::KeyPackage<C>,
) {
    // Check if passing not enough commitments causes an error

    let mut commitments = signing_package.signing_commitments().clone();
    // Remove one commitment that's not from the key_package owner
    let id = *commitments
        .keys()
        .find(|&&id| id != key_package.identifier)
        .unwrap();
    commitments.remove(&id);
    let signing_package = frost::SigningPackage::new(commitments, signing_package.message());

    let r = frost::round2::sign(&signing_package, &signing_nonces, &key_package);
    assert_eq!(r, Err(Error::IncorrectNumberOfCommitments));
}

fn check_aggregate_errors<C: Ciphersuite + PartialEq>(
    signing_package: frost::SigningPackage<C>,
    signature_shares: BTreeMap<frost::Identifier<C>, frost::round2::SignatureShare<C>>,
    pubkey_package: frost::keys::PublicKeyPackage<C>,
) {
    check_aggregate_corrupted_share(
        signing_package.clone(),
        signature_shares.clone(),
        pubkey_package.clone(),
    );

    check_aggregate_invalid_share_identifier_for_verifying_shares(
        signing_package,
        signature_shares,
        pubkey_package,
    );
}

fn check_aggregate_corrupted_share<C: Ciphersuite + PartialEq>(
    signing_package: frost::SigningPackage<C>,
    mut signature_shares: BTreeMap<frost::Identifier<C>, frost::round2::SignatureShare<C>>,
    pubkey_package: frost::keys::PublicKeyPackage<C>,
) {
    use crate::{round2::SignatureShare, CheaterDetection};

    let one = <<C as Ciphersuite>::Group as Group>::Field::one();
    // Corrupt two shares
    let id1 = *signature_shares.keys().next().unwrap();
    *signature_shares.get_mut(&id1).unwrap() =
        SignatureShare::new(signature_shares[&id1].to_scalar() + one);
    let id2 = *signature_shares.keys().nth(1).unwrap();
    *signature_shares.get_mut(&id2).unwrap() =
        SignatureShare::new(signature_shares[&id2].to_scalar() + one);

    let e = frost::aggregate(&signing_package, &signature_shares, &pubkey_package).unwrap_err();
    assert_eq!(e.culprits(), vec![id1]);
    assert_eq!(
        e,
        Error::InvalidSignatureShare {
            culprits: vec![id1]
        }
    );

    let e = frost::aggregate_custom(
        &signing_package,
        &signature_shares,
        &pubkey_package,
        crate::CheaterDetection::Disabled,
    )
    .unwrap_err();
    assert_eq!(e.culprits(), vec![]);
    assert_eq!(e, Error::InvalidSignature);

    let e = frost::aggregate_custom(
        &signing_package,
        &signature_shares,
        &pubkey_package,
        crate::CheaterDetection::FirstCheater,
    )
    .unwrap_err();
    assert_eq!(e.culprits(), vec![id1]);
    assert_eq!(
        e,
        Error::InvalidSignatureShare {
            culprits: vec![id1]
        }
    );

    let e = frost::aggregate_custom(
        &signing_package,
        &signature_shares,
        &pubkey_package,
        CheaterDetection::AllCheaters,
    )
    .unwrap_err();
    assert_eq!(e.culprits(), vec![id1, id2]);
    assert_eq!(
        e,
        Error::InvalidSignatureShare {
            culprits: vec![id1, id2]
        }
    );
}

/// Test NCC-E008263-4VP audit finding (PublicKeyPackage).
/// Note that the SigningPackage part of the finding is not currently reachable
/// since it's caught by `compute_lagrange_coefficient()`, and the Binding Factor
/// part can't either since it's caught before by the PublicKeyPackage part.
fn check_aggregate_invalid_share_identifier_for_verifying_shares<C: Ciphersuite + PartialEq>(
    signing_package: frost::SigningPackage<C>,
    mut signature_shares: BTreeMap<frost::Identifier<C>, frost::round2::SignatureShare<C>>,
    pubkey_package: frost::keys::PublicKeyPackage<C>,
) {
    let invalid_identifier = Identifier::derive("invalid identifier".as_bytes()).unwrap();
    // Insert a new share (copied from other existing share) with an invalid identifier
    signature_shares.insert(
        invalid_identifier,
        *signature_shares.values().next().unwrap(),
    );
    // Should error, but not panic
    frost::aggregate(&signing_package, &signature_shares, &pubkey_package)
        .expect_err("should not work");
}

/// Test FROST signing with DKG with a Ciphersuite.
pub fn check_sign_with_dkg<C: Ciphersuite + PartialEq, R: RngCore + CryptoRng>(
    mut rng: R,
) -> (Vec<u8>, Signature<C>, VerifyingKey<C>)
where
    C::Group: core::cmp::PartialEq,
{
    ////////////////////////////////////////////////////////////////////////////
    // Key generation, Round 1
    ////////////////////////////////////////////////////////////////////////////

    let max_signers = 5;
    let min_signers = 3;

    // Keep track of each participant's round 1 secret package.
    // In practice each participant will keep its copy; no one
    // will have all the participant's packages.
    let mut round1_secret_packages: BTreeMap<
        frost::Identifier<C>,
        frost::keys::dkg::round1::SecretPackage<C>,
    > = BTreeMap::new();

    // Keep track of all round 1 packages sent to the given participant.
    // This is used to simulate the broadcast; in practice the packages
    // will be sent through some communication channel.
    let mut received_round1_packages: BTreeMap<
        frost::Identifier<C>,
        BTreeMap<frost::Identifier<C>, frost::keys::dkg::round1::Package<C>>,
    > = BTreeMap::new();

    // For each participant, perform the first part of the DKG protocol.
    // In practice, each participant will perform this on their own environments.
    for participant_index in 1..=max_signers {
        let participant_identifier = participant_index.try_into().expect("should be nonzero");
        let (round1_secret_package, round1_package) =
            frost::keys::dkg::part1(participant_identifier, max_signers, min_signers, &mut rng)
                .unwrap();

        // Simulate serialization / deserialization to ensure it works
        let round1_secret_package = frost::keys::dkg::round1::SecretPackage::<C>::deserialize(
            &round1_secret_package.serialize().unwrap(),
        )
        .unwrap();
        let round1_package = frost::keys::dkg::round1::Package::<C>::deserialize(
            &round1_package.serialize().unwrap(),
        )
        .unwrap();

        // Store the participant's secret package for later use.
        // In practice each participant will store it in their own environment.
        round1_secret_packages.insert(
            participant_identifier,
            // Serialization roundtrip to simulate storage for later
            round1::SecretPackage::deserialize(&round1_secret_package.serialize().unwrap())
                .unwrap(),
        );

        // "Send" the round 1 package to all other participants. In this
        // test this is simulated using a BTreeMap; in practice this will be
        // sent through some communication channel.
        for receiver_participant_index in 1..=max_signers {
            if receiver_participant_index == participant_index {
                continue;
            }
            let receiver_participant_identifier = receiver_participant_index
                .try_into()
                .expect("should be nonzero");
            received_round1_packages
                .entry(receiver_participant_identifier)
                .or_default()
                .insert(
                    participant_identifier,
                    // Serialization roundtrip to simulate communication
                    round1::Package::deserialize(&round1_package.serialize().unwrap()).unwrap(),
                );
        }
    }

    ////////////////////////////////////////////////////////////////////////////
    // Key generation, Round 2
    ////////////////////////////////////////////////////////////////////////////

    // Keep track of each participant's round 2 secret package.
    // In practice each participant will keep its copy; no one
    // will have all the participant's packages.
    let mut round2_secret_packages = BTreeMap::new();

    // Keep track of all round 2 packages sent to the given participant.
    // This is used to simulate the broadcast; in practice the packages
    // will be sent through some communication channel.
    let mut received_round2_packages = BTreeMap::new();

    // For each participant, perform the second part of the DKG protocol.
    // In practice, each participant will perform this on their own environments.
    for participant_index in 1..=max_signers {
        let participant_identifier = participant_index.try_into().expect("should be nonzero");
        let round1_secret_package = round1_secret_packages
            .remove(&participant_identifier)
            .unwrap();
        let round1_packages = &received_round1_packages[&participant_identifier];
        check_part2_error(round1_secret_package.clone(), round1_packages.clone());
        let (round2_secret_package, round2_packages) =
            frost::keys::dkg::part2(round1_secret_package, round1_packages).expect("should work");

        // Simulate serialization / deserialization to ensure it works
        let round2_secret_package = frost::keys::dkg::round2::SecretPackage::<C>::deserialize(
            &round2_secret_package.serialize().unwrap(),
        )
        .unwrap();

        // Store the participant's secret package for later use.
        // In practice each participant will store it in their own environment.
        round2_secret_packages.insert(
            participant_identifier,
            // Serialization roundtrip to simulate storage for later
            round2::SecretPackage::deserialize(&round2_secret_package.serialize().unwrap())
                .unwrap(),
        );

        // "Send" the round 2 package to all other participants. In this
        // test this is simulated using a BTreeMap; in practice this will be
        // sent through some communication channel.
        // Note that, in contrast to the previous part, here each other participant
        // gets its own specific package.
        for (receiver_identifier, round2_package) in round2_packages {
            // Simulate serialization / deserialization to ensure it works
            let round2_package = frost::keys::dkg::round2::Package::<C>::deserialize(
                &round2_package.serialize().unwrap(),
            )
            .unwrap();
            received_round2_packages
                .entry(receiver_identifier)
                .or_insert_with(BTreeMap::new)
                .insert(
                    participant_identifier,
                    // Serialization roundtrip to simulate communication
                    round2::Package::deserialize(&round2_package.serialize().unwrap()).unwrap(),
                );
        }
    }

    ////////////////////////////////////////////////////////////////////////////
    // Key generation, final computation
    ////////////////////////////////////////////////////////////////////////////

    // Keep track of each participant's long-lived key package.
    // In practice each participant will keep its copy; no one
    // will have all the participant's packages.
    let mut key_packages = BTreeMap::new();

    // Map of the verifying share of each participant.
    // Used by the signing test that follows.
    let mut verifying_shares = BTreeMap::new();
    // The group public key, used by the signing test that follows.
    let mut verifying_key = None;
    // For each participant, store the set of verifying keys they have computed.
    // This is used to check if the set is correct (the same) for all participants.
    // In practice, if there is a Coordinator, only they need to store the set.
    // If there is not, then all candidates must store their own sets.
    // The verifying keys are used to verify the signature shares produced
    // for each signature before being aggregated.
    let mut pubkey_packages_by_participant = BTreeMap::new();

    check_part3_errors(
        max_signers,
        round2_secret_packages.clone(),
        received_round1_packages.clone(),
        received_round2_packages.clone(),
    );

    // For each participant, perform the third part of the DKG protocol.
    // In practice, each participant will perform this on their own environments.
    for participant_index in 1..=max_signers {
        let participant_identifier = participant_index.try_into().expect("should be nonzero");
        let (key_package, pubkey_package_for_participant) = frost::keys::dkg::part3(
            &round2_secret_packages[&participant_identifier],
            &received_round1_packages[&participant_identifier],
            &received_round2_packages[&participant_identifier],
        )
        .unwrap();
        // Simulate serialization / deserialization to ensure it works
        let key_package =
            frost::keys::KeyPackage::deserialize(&key_package.serialize().unwrap()).unwrap();
        let pubkey_package_for_participant = frost::keys::PublicKeyPackage::deserialize(
            &pubkey_package_for_participant.serialize().unwrap(),
        )
        .unwrap();
        verifying_shares.insert(participant_identifier, key_package.verifying_share);
        // Test if all verifying_key are equal
        if let Some(previous_verifying_key) = verifying_key {
            assert_eq!(previous_verifying_key, key_package.verifying_key)
        }
        verifying_key = Some(key_package.verifying_key);
        key_packages.insert(participant_identifier, key_package);
        pubkey_packages_by_participant
            .insert(participant_identifier, pubkey_package_for_participant);
    }

    // Test if the set of verifying keys is correct for all participants.
    for verifying_keys_for_participant in pubkey_packages_by_participant.values() {
        assert!(verifying_keys_for_participant.verifying_shares == verifying_shares);
    }

    let pubkeys = pubkey_packages_by_participant
        .first_key_value()
        .unwrap()
        .1
        .clone();
    // Simulate serialization / deserialization to ensure it works
    let pubkeys =
        frost::keys::PublicKeyPackage::deserialize(&pubkeys.serialize().unwrap()).unwrap();

    // Proceed with the signing test.
    check_sign(min_signers, key_packages, rng, pubkeys).unwrap()
}

/// Check for error cases related to DKG part3.
fn check_part3_errors<C: Ciphersuite>(
    max_signers: u16,
    round2_secret_packages: BTreeMap<Identifier<C>, frost::keys::dkg::round2::SecretPackage<C>>,
    received_round1_packages: BTreeMap<
        Identifier<C>,
        BTreeMap<Identifier<C>, frost::keys::dkg::round1::Package<C>>,
    >,
    received_round2_packages: BTreeMap<
        Identifier<C>,
        BTreeMap<Identifier<C>, frost::keys::dkg::round2::Package<C>>,
    >,
) {
    check_part3_different_participants(
        max_signers,
        round2_secret_packages.clone(),
        received_round1_packages.clone(),
        received_round2_packages.clone(),
    );
    check_part3_corrupted_share(
        max_signers,
        round2_secret_packages,
        received_round1_packages,
        received_round2_packages,
    );
}

/// Check that calling dkg::part3() with distinct sets of participants fail.
pub fn check_part3_different_participants<C: Ciphersuite>(
    max_signers: u16,
    round2_secret_packages: BTreeMap<Identifier<C>, frost::keys::dkg::round2::SecretPackage<C>>,
    received_round1_packages: BTreeMap<
        Identifier<C>,
        BTreeMap<Identifier<C>, frost::keys::dkg::round1::Package<C>>,
    >,
    received_round2_packages: BTreeMap<
        Identifier<C>,
        BTreeMap<Identifier<C>, frost::keys::dkg::round2::Package<C>>,
    >,
) {
    // For each participant, perform the third part of the DKG protocol.
    // In practice, each participant will perform this on their own environments.
    for participant_index in 1..=max_signers {
        let participant_identifier = participant_index.try_into().expect("should be nonzero");

        // Remove the first package from the map, and reinsert it with an unrelated
        // Do the same for Round 2 packages
        let mut received_round2_packages =
            received_round2_packages[&participant_identifier].clone();
        let package = received_round2_packages
            .remove(&received_round2_packages.keys().next().unwrap().clone())
            .unwrap();
        received_round2_packages.insert(42u16.try_into().unwrap(), package);

        let r = frost::keys::dkg::part3(
            &round2_secret_packages[&participant_identifier],
            &received_round1_packages[&participant_identifier],
            &received_round2_packages,
        )
        .expect_err("Should have failed due to different identifier sets");
        assert_eq!(r, Error::IncorrectPackage)
    }
}

/// Check that calling dkg::part3() with a corrupted share fail, and the
/// culprit is correctly identified.
fn check_part3_corrupted_share<C: Ciphersuite>(
    max_signers: u16,
    round2_secret_packages: BTreeMap<Identifier<C>, frost::keys::dkg::round2::SecretPackage<C>>,
    received_round1_packages: BTreeMap<
        Identifier<C>,
        BTreeMap<Identifier<C>, frost::keys::dkg::round1::Package<C>>,
    >,
    received_round2_packages: BTreeMap<
        Identifier<C>,
        BTreeMap<Identifier<C>, frost::keys::dkg::round2::Package<C>>,
    >,
) {
    // For each participant, perform the third part of the DKG protocol.
    // In practice, each participant will perform this on their own environments.
    for participant_index in 1..=max_signers {
        let participant_identifier = participant_index.try_into().expect("should be nonzero");

        // Remove the first package from the map, and reinsert it with an unrelated
        // Do the same for Round 2 packages
        let mut received_round2_packages =
            received_round2_packages[&participant_identifier].clone();
        let culprit = *received_round2_packages.keys().next().unwrap();
        let package = received_round2_packages.get_mut(&culprit).unwrap();
        let one = <<C as Ciphersuite>::Group as Group>::Field::one();
        package.signing_share = SigningShare::new(package.signing_share().to_scalar() + one);

        let r = frost::keys::dkg::part3(
            &round2_secret_packages[&participant_identifier],
            &received_round1_packages[&participant_identifier],
            &received_round2_packages,
        )
        .expect_err("Should have failed due to corrupted share");
        assert_eq!(
            r,
            Error::InvalidSecretShare {
                culprit: Some(culprit)
            }
        )
    }
}

/// Test FROST signing with trusted dealer with a Ciphersuite, using specified
/// Identifiers.
pub fn check_sign_with_dealer_and_identifiers<C: Ciphersuite, R: RngCore + CryptoRng>(
    mut rng: R,
) -> (Vec<u8>, Signature<C>, VerifyingKey<C>) {
    // Check error cases first
    // Check repeated identifiers

    let identifiers: Vec<frost::Identifier<C>> = [1u16, 42, 100, 257, 42]
        .into_iter()
        .map(|i| i.try_into().unwrap())
        .collect();
    let max_signers = 5;
    let min_signers = 3;
    let err = frost::keys::generate_with_dealer(
        max_signers,
        min_signers,
        frost::keys::IdentifierList::Custom(&identifiers),
        &mut rng,
    )
    .unwrap_err();
    assert_eq!(err, Error::DuplicatedIdentifier);

    // Check incorrect number of identifiers

    let identifiers: Vec<frost::Identifier<C>> = [1u16, 42, 100, 257]
        .into_iter()
        .map(|i| i.try_into().unwrap())
        .collect();
    let max_signers = 5;
    let min_signers = 3;
    let err = frost::keys::generate_with_dealer(
        max_signers,
        min_signers,
        frost::keys::IdentifierList::Custom(&identifiers),
        &mut rng,
    )
    .unwrap_err();
    assert_eq!(err, Error::IncorrectNumberOfIdentifiers);

    // Check correct case

    let identifiers: Vec<frost::Identifier<C>> = [1u16, 42, 100, 257, 65535]
        .into_iter()
        .map(|i| i.try_into().unwrap())
        .collect();

    let max_signers = 5;
    let min_signers = 3;
    let (shares, pubkeys) = frost::keys::generate_with_dealer(
        max_signers,
        min_signers,
        frost::keys::IdentifierList::Custom(&identifiers),
        &mut rng,
    )
    .unwrap();

    // Check if the specified identifiers were used
    for id in identifiers {
        assert!(shares.contains_key(&id));
    }

    // Do regular testing to make sure it works

    let mut key_packages: BTreeMap<frost::Identifier<C>, frost::keys::KeyPackage<C>> =
        BTreeMap::new();
    for (k, v) in shares {
        let key_package = frost::keys::KeyPackage::try_from(v).unwrap();
        key_packages.insert(k, key_package);
    }
    check_sign(min_signers, key_packages, rng, pubkeys).unwrap()
}

// Check for error cases in DKG part 2.
fn check_part2_error<C: Ciphersuite>(
    round1_secret_package: frost::keys::dkg::round1::SecretPackage<C>,
    mut round1_packages: BTreeMap<frost::Identifier<C>, frost::keys::dkg::round1::Package<C>>,
) {
    // Check if a corrupted proof of knowledge results in failure.
    let one = <<C as Ciphersuite>::Group as Group>::Field::one();
    // Corrupt a PoK
    let id = *round1_packages.keys().next().unwrap();
    round1_packages.get_mut(&id).unwrap().proof_of_knowledge.z =
        round1_packages[&id].proof_of_knowledge.z + one;
    let e = frost::keys::dkg::part2(round1_secret_package, &round1_packages).unwrap_err();
    assert_eq!(e.culprits(), vec![id]);
    assert_eq!(e, Error::InvalidProofOfKnowledge { culprit: id });
}

/// Test Error culprit method.
pub fn check_error_culprit<C: Ciphersuite>() {
    let identifier: frost::Identifier<C> = 42u16.try_into().unwrap();

    let e = Error::InvalidSignatureShare {
        culprits: vec![identifier],
    };
    assert_eq!(e.culprits(), vec![identifier]);

    let e = Error::InvalidProofOfKnowledge {
        culprit: identifier,
    };
    assert_eq!(e.culprits(), vec![identifier]);

    let e: Error<C> = Error::InvalidSignature;
    assert_eq!(e.culprits(), vec![]);
}

/// Test identifier derivation with a Ciphersuite
pub fn check_identifier_derivation<C: Ciphersuite>() {
    let id1a = Identifier::<C>::derive("username1".as_bytes()).unwrap();
    let id1b = Identifier::<C>::derive("username1".as_bytes()).unwrap();
    let id2 = Identifier::<C>::derive("username2".as_bytes()).unwrap();

    assert!(id1a == id1b);
    assert!(id1a != id2);
}

/// Checks the signer's identifier is included in the package
pub fn check_sign_with_missing_identifier<C: Ciphersuite, R: RngCore + CryptoRng>(mut rng: R) {
    ////////////////////////////////////////////////////////////////////////////
    // Key generation
    ////////////////////////////////////////////////////////////////////////////

    let max_signers = 5;
    let min_signers = 3;
    let (shares, _pubkeys) = frost::keys::generate_with_dealer(
        max_signers,
        min_signers,
        frost::keys::IdentifierList::Default,
        &mut rng,
    )
    .unwrap();

    // Verifies the secret shares from the dealer
    let mut key_packages: BTreeMap<frost::Identifier<C>, frost::keys::KeyPackage<C>> =
        BTreeMap::new();

    for (k, v) in shares {
        let key_package = frost::keys::KeyPackage::try_from(v).unwrap();
        key_packages.insert(k, key_package);
    }

    let mut nonces_map: BTreeMap<frost::Identifier<C>, frost::round1::SigningNonces<C>> =
        BTreeMap::new();
    let mut commitments_map: BTreeMap<frost::Identifier<C>, frost::round1::SigningCommitments<C>> =
        BTreeMap::new();

    ////////////////////////////////////////////////////////////////////////////
    // Round 1: generating nonces and signing commitments for each participant
    ////////////////////////////////////////////////////////////////////////////

    let id_1 = Identifier::<C>::try_from(1).unwrap();
    let id_2 = Identifier::<C>::try_from(2).unwrap();
    let id_3 = Identifier::<C>::try_from(3).unwrap();
    let id_4 = Identifier::<C>::try_from(4).unwrap();
    let key_packages_inc = vec![id_1, id_2, id_3];

    for participant_identifier in key_packages_inc {
        // The nonces and commitments for each participant are generated.
        let (nonces, commitments) = frost::round1::commit(
            key_packages
                .get(&participant_identifier)
                .unwrap()
                .signing_share(),
            &mut rng,
        );
        nonces_map.insert(participant_identifier, nonces);

        // Participant with id_1 is excluded from the commitments_map so it is missing from the signing package.
        // To prevent sign() from returning an error due to incorrect number of commitments,
        // add the commitment under another unrelated participant.
        if participant_identifier == id_1 {
            commitments_map.insert(id_4, commitments);
        } else {
            commitments_map.insert(participant_identifier, commitments);
        }
    }

    // This is what the signature aggregator / coordinator needs to do:
    // - decide what message to sign
    // - take one (unused) commitment per signing participant
    let message = "message to sign".as_bytes();
    let signing_package = SigningPackage::new(commitments_map, message);

    ////////////////////////////////////////////////////////////////////////////
    // Round 2: Participant with id_1 signs
    ////////////////////////////////////////////////////////////////////////////

    let key_package_1 = key_packages.get(&id_1).unwrap();

    let nonces_to_use = &nonces_map.get(&id_1).unwrap();

    // Each participant generates their signature share.
    let signature_share = frost::round2::sign(&signing_package, nonces_to_use, key_package_1);

    assert_eq!(signature_share, Err(Error::MissingCommitment))
}

/// Checks the signer's commitment is valid
pub fn check_sign_with_incorrect_commitments<C: Ciphersuite, R: RngCore + CryptoRng>(mut rng: R) {
    ////////////////////////////////////////////////////////////////////////////
    // Key generation
    ////////////////////////////////////////////////////////////////////////////

    let max_signers = 5;
    let min_signers = 3;
    let (shares, _pubkeys) = frost::keys::generate_with_dealer(
        max_signers,
        min_signers,
        frost::keys::IdentifierList::Default,
        &mut rng,
    )
    .unwrap();

    // Verifies the secret shares from the dealer
    let mut key_packages: BTreeMap<frost::Identifier<C>, frost::keys::KeyPackage<C>> =
        BTreeMap::new();

    for (k, v) in shares {
        let key_package = frost::keys::KeyPackage::try_from(v).unwrap();
        key_packages.insert(k, key_package);
    }

    let mut commitments_map: BTreeMap<frost::Identifier<C>, frost::round1::SigningCommitments<C>> =
        BTreeMap::new();

    ////////////////////////////////////////////////////////////////////////////
    // Round 1: generating nonces and signing commitments for each participant
    ////////////////////////////////////////////////////////////////////////////

    let id_1 = Identifier::<C>::try_from(1).unwrap();
    let id_2 = Identifier::<C>::try_from(2).unwrap();
    let id_3 = Identifier::<C>::try_from(3).unwrap();
    // let key_packages_inc = vec![id_1, id_2, id_3];

    let (_nonces_1, commitments_1) =
        frost::round1::commit(key_packages[&id_1].signing_share(), &mut rng);

    let (_nonces_2, commitments_2) =
        frost::round1::commit(key_packages[&id_2].signing_share(), &mut rng);

    let (nonces_3, _commitments_3) =
        frost::round1::commit(key_packages[&id_3].signing_share(), &mut rng);

    commitments_map.insert(id_1, commitments_1);
    commitments_map.insert(id_2, commitments_2);
    // Invalid commitment for id_3
    commitments_map.insert(id_3, commitments_1);

    // This is what the signature aggregator / coordinator needs to do:
    // - decide what message to sign
    // - take one (unused) commitment per signing participant
    let message = "message to sign".as_bytes();
    let signing_package = SigningPackage::new(commitments_map, message);

    ////////////////////////////////////////////////////////////////////////////
    // Round 2: Participant with id_3 signs
    ////////////////////////////////////////////////////////////////////////////

    let key_package_3 = key_packages.get(&id_3).unwrap();

    // Each participant generates their signature share.
    let signature_share = frost::round2::sign(&signing_package, &nonces_3, key_package_3);

    assert!(signature_share.is_err());
    assert!(signature_share == Err(Error::IncorrectCommitment))
}

// Checks the verifying shares are valid
//
// NOTE: If the last verifying share is invalid this test will not detect this.
// The test is intended for ensuring the correct calculation of verifying shares
// which is covered in this test
fn check_verifying_shares<C: Ciphersuite>(
    pubkeys: PublicKeyPackage<C>,
    signing_package: SigningPackage<C>,
    mut signature_shares: BTreeMap<Identifier<C>, SignatureShare<C>>,
) {
    let one = <<C as Ciphersuite>::Group as Group>::Field::one();

    // Corrupt last share
    let id = *signature_shares.keys().last().unwrap();
    *signature_shares.get_mut(&id).unwrap() =
        SignatureShare::new(signature_shares[&id].to_scalar() + one);

    let e = frost::aggregate(&signing_package, &signature_shares, &pubkeys).unwrap_err();
    assert_eq!(e.culprits(), vec![id]);
    assert_eq!(e, Error::InvalidSignatureShare { culprits: vec![id] });
}

// Checks if `verify_signature_share()` works correctly.
fn check_verify_signature_share<C: Ciphersuite>(
    pubkeys: &PublicKeyPackage<C>,
    signing_package: &SigningPackage<C>,
    signature_shares: &BTreeMap<Identifier<C>, SignatureShare<C>>,
) {
    for (identifier, signature_share) in signature_shares {
        frost::verify_signature_share(
            *identifier,
            pubkeys.verifying_shares().get(identifier).unwrap(),
            signature_share,
            signing_package,
            pubkeys.verifying_key(),
        )
        .expect("should pass");
    }

    for (identifier, signature_share) in signature_shares {
        let one = <<C as Ciphersuite>::Group as Group>::Field::one();
        // Corrupt  share
        let signature_share = SignatureShare::new(signature_share.to_scalar() + one);

        frost::verify_signature_share(
            *identifier,
            pubkeys.verifying_shares().get(identifier).unwrap(),
            &signature_share,
            signing_package,
            pubkeys.verifying_key(),
        )
        .expect_err("should have failed");
    }
}

/// Test FROST signing in an async context.
/// The ultimate goal of the test is to ensure that types are Send + Sync.
pub async fn async_check_sign<C: Ciphersuite, R: RngCore + CryptoRng + 'static + Send + Sync>(
    mut rng: R,
) {
    tokio::spawn(async move {
        let max_signers = 5;
        let min_signers = 3;
        let (shares, pubkey_package) = frost::keys::generate_with_dealer(
            max_signers,
            min_signers,
            frost::keys::IdentifierList::Default,
            &mut rng,
        )
        .unwrap();

        // The test is sprinkled with await points to ensure that types that
        // cross them are Send + Sync.
        tokio::time::sleep(core::time::Duration::from_millis(1)).await;

        // Verifies the secret shares from the dealer
        let key_packages: BTreeMap<frost::Identifier<C>, frost::keys::KeyPackage<C>> = shares
            .into_iter()
            .map(|(k, v)| (k, frost::keys::KeyPackage::try_from(v).unwrap()))
            .collect();

        tokio::time::sleep(core::time::Duration::from_millis(1)).await;

        let mut nonces_map: BTreeMap<frost::Identifier<C>, frost::round1::SigningNonces<C>> =
            BTreeMap::new();
        let mut commitments_map: BTreeMap<
            frost::Identifier<C>,
            frost::round1::SigningCommitments<C>,
        > = BTreeMap::new();

        for participant_identifier in key_packages.keys().take(min_signers as usize).cloned() {
            // Generate one (1) nonce and one SigningCommitments instance for each
            // participant, up to _min_signers_.
            let (nonces, commitments) = frost::round1::commit(
                key_packages
                    .get(&participant_identifier)
                    .unwrap()
                    .signing_share(),
                &mut rng,
            );
            tokio::time::sleep(core::time::Duration::from_millis(1)).await;
            nonces_map.insert(participant_identifier, nonces);
            commitments_map.insert(participant_identifier, commitments);
        }

        let mut signature_shares = BTreeMap::new();
        let message = "message to sign".as_bytes();
        let signing_package = SigningPackage::new(commitments_map, message);

        for participant_identifier in nonces_map.keys() {
            let key_package = key_packages.get(participant_identifier).unwrap();
            let nonces_to_use = nonces_map.get(participant_identifier).unwrap();
            let signature_share =
                frost::round2::sign(&signing_package, nonces_to_use, key_package).unwrap();
            tokio::time::sleep(core::time::Duration::from_millis(1)).await;
            signature_shares.insert(*participant_identifier, signature_share);
        }

        let group_signature =
            frost::aggregate(&signing_package, &signature_shares, &pubkey_package).unwrap();
        tokio::time::sleep(core::time::Duration::from_millis(1)).await;

        pubkey_package
            .verifying_key
            .verify(message, &group_signature)
            .unwrap();
        tokio::time::sleep(core::time::Duration::from_millis(1)).await;

        for (participant_identifier, _) in nonces_map.clone() {
            let key_package = key_packages.get(&participant_identifier).unwrap();
            key_package
                .verifying_key
                .verify(message, &group_signature)
                .unwrap();
            tokio::time::sleep(core::time::Duration::from_millis(1)).await;
        }
    })
    .await
    .unwrap();
}