commonware-cryptography 0.0.63

Generate keys, sign arbitrary messages, and deterministically verify signatures.
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
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
//! Distributed Key Generation (DKG) and Resharing protocol for the BLS12-381 curve.
//!
//! This crate implements an interactive Distributed Key Generation (DKG) and Resharing protocol
//! for the BLS12-381 curve. Unlike other constructions, this construction does not require encrypted
//! shares to be publicly broadcast to complete a DKG/Reshare. Shares, instead, are sent directly
//! between dealers and players over an encrypted channel (which can be instantiated
//! with [commonware-p2p](https://docs.rs/commonware-p2p)).
//!
//! The DKG is based on the "Joint-Feldman" construction from "Secure Distributed Key
//! Generation for Discrete-Log Based Cryptosystems" (GJKR99) and Resharing is based
//! on the construction described in "Redistributing secret shares to new access structures
//! and its applications" (Desmedt97).
//!
//! # Overview
//!
//! The protocol has three types of participants: arbiters, dealers, and players. The arbiter
//! serves as an orchestrator that collects commitments, acknowledgements, and reveals from
//! dealers/players and replicates them to all dealers/players. The arbiter can be implemented as
//! a standalone process or by some consensus protocol. Dealers generate commitments/shares and collect
//! acknowledgements from players. Players receive shares from dealers, validate them, and send acknowledgements
//! back to dealers. It is possible to be both a dealer and a player in the protocol.
//!
//! Whether or not the protocol succeeds, the dealers that did not post valid commitments/acks/reveals are
//! identified and returned. If the protocol succeeds, any dealers that did not post valid commitments/acks/reveals
//! are identified (and still returned). It is expected that the set of participants would punish/exclude
//! "bad" dealers prior to a future round (to eventually make progress).
//!
//! # Specification
//!
//! ## Assumptions
//!
//! * Let `t` be the maximum amount of time it takes for a message to be sent between any two participants.
//! * Each participant has an encrypted channel to every other participant.
//! * There exist `3f + 1` participants and at most `f` static Byzantine faults.
//!
//! ## [Arbiter] Step 0: Start Round
//!
//! Send a message to all participants to start a round. If this is a reshare, include the group polynomial from
//! the last successful round.
//!
//! ## [Dealer] Step 1: Generate Commitment and Dealings
//!
//! Upon receiving start message from arbiter, generate commitment and dealings. If it is a DKG, the commitment is
//! a random polynomial of degree `2f`. If it is a reshare, the commitment must be consistent with the
//! previous group polynomial.
//!
//! ## [Dealer] Step 2: Distribute Commitment and Dealings
//!
//! Distribute generated commitment and corresponding dealings to each player over an encrypted channel.
//!
//! ## [Player] Step 3: Verify Dealing and Send Acknowledgement
//!
//! Verify incoming dealing against provided commitment (additionally comparing the commitment to the previous group
//! polynomial, if reshare). If the dealing is valid, send an acknowledgement back to the dealer.
//!
//! To protect against a dealer sending different commitments to different players, players must sign this
//! acknowledgement over `(dealer, commitment)`.
//!
//! ## [Dealer] Step 4: Collect Acknowledgements and Send to Arbiter
//!
//! Collect acknowledgements from players. After `2t` has elapsed since Step 1 (up to `3t` from Step 0), check to
//! see if at least `2f + 1` acknowledgements have been received (including self, if a player as well). If so, send the
//! commitment, acknowledgements, and unencrypted dealings of players that did not send an acknowledgement to the
//! arbiter. If not, exit.
//!
//! ## [Arbiter] Step 5: Select Commitments and Forward Reveals
//!
//! Select the first `2f + 1` commitments with at most `f` reveals. Forward these `2f + 1` commitments
//! (and any reveals associated with each) to all players. If there do not exist `2f + 1` commitments with
//! at most `f` reveals by time `4t`, exit.
//!
//! ## [Player] Step 6: Recover Group Polynomial and Derive Share
//!
//! If the round is successful, each player will receive `2f + 1` commitments and any dealings associated with said
//! commitments they did not acknowledge (or that the dealer said they didn't acknowledge). With this, they can recover
//! the new group polynomial and derive their share of the secret. If this distribution is not received by time `5t`, exit.
//!
//! # Caveats
//!
//! ## Synchrony Assumption
//!
//! Under synchrony (where `t` is the maximum amount of time it takes for a message to be sent between any two participants),
//! this construction can be used to maintain a shared secret where at least `f + 1` honest players must participate to
//! recover the shared secret (`2f + 1` threshold where at most `f` players are Byzantine). To see how this is true,
//! first consider that in any successful round there must exist `2f + 1` commitments with at most `f` reveals. This implies
//! that all players must have acknowledged or have access to a reveal for each of the `2f + 1` selected commitments (allowing
//! them to derive their share). Next, consider that when the network is synchronous that all `2f + 1` honest players send
//! acknowledgements to honest dealers before `2t`. Because `2f + 1` commitments must be chosen, at least `f + 1` commitments
//! must be from honest dealers (where no honest player dealing is revealed). Even if the remaining `f` commitments are from
//! Byzantine dealers, there will not be enough dealings to recover the derived share of any honest player (at most `f` of
//! `2f + 1` dealings publicly revealed). Given all `2f + 1` honest players have access to their shares and it is not possible
//! for a Byzantine player to derive any honest player's share, this claim holds.
//!
//! If the network is not synchronous, however, Byzantine players can collude to recover a shared secret with the
//! participation of a single honest player (rather than `f + 1`) and `f + 1` honest players will each be able to derive
//! the shared secret (if the Byzantine players reveal their shares). To see how this could be, consider a network where
//! `f` honest participants are in one partition and (`f + 1` honest and `f` Byzantine participants) are in another. All
//! `f` Byzantine players acknowledge dealings from the `f + 1` honest dealers. Participants in the second partition will
//! complete a round and all the reveals will belong to the same set of `f` honest players (that are in the first partition).
//! A colluding Byzantine adversary will then have access to their acknowledged `f` shares and the revealed `f` shares
//! (requiring only the participation of a single honest player that was in their partition to recover the shared secret).
//! If the Byzantine adversary reveals all of their (still private) shares at this time, each of the `f + 1` honest players
//! that were in the second partition will be able to derive the shared secret without collusion (using their private share
//! and the `2f` public shares). It will not be possible for any external observer, however, to recover the shared secret.
//!
//! ### Future Work: Dropping the Synchrony Assumption?
//!
//! It is possible to design a DKG/Resharing scheme that maintains a shared secret where at least `f + 1` honest players
//! must participate to recover the shared secret that doesn't require a synchrony assumption (`2f + 1` threshold
//! where at most `f` players are Byzantine). However, known constructions that satisfy this requirement require both
//! broadcasting encrypted dealings publicly and employing Zero-Knowledge Proofs (ZKPs) to attest that encrypted dealings
//! were generated correctly ([Groth21](https://eprint.iacr.org/2021/339), [Kate23](https://eprint.iacr.org/2023/451)).
//!
//! As of January 2025, these constructions are still considered novel (2-3 years in production), require stronger
//! cryptographic assumptions, don't scale to hundreds of participants (unless dealers have powerful hardware), and provide
//! observers the opportunity to brute force decrypt shares (even if honest players are online).
//!
//! ## Tracking Complaints
//!
//! This crate does not provide an integrated mechanism for tracking complaints from players (of malicious dealers). However, it is
//! possible to implement your own mechanism and to manually disqualify dealers from a given round in the arbiter. This decision was made
//! because the mechanism for communicating commitments/shares/acknowledgements is highly dependent on the context in which this
//! construction is used.
//!
//! ## Non-Uniform Distribution
//!
//! The Joint-Feldman DKG protocol does not guarantee a uniformly random secret key is generated. An adversary
//! can introduce `O(lg N)` bits of bias into the key with `O(poly(N))` amount of computation. For uses
//! like signing, threshold encryption, where the security of the scheme reduces to that of
//! the underlying assumption that cryptographic constructions using the curve are secure (i.e.
//! that the Discrete Logarithm Problem, or stronger variants, are hard), then this caveat does
//! not affect the security of the scheme. This must be taken into account when integrating this
//! component into more esoteric schemes.
//!
//! This choice was explicitly made, because the best known protocols guaranteeing a uniform output
//! require an extra round of broadcast ([GJKR02](https://www.researchgate.net/publication/2558744_Revisiting_the_Distributed_Key_Generation_for_Discrete-Log_Based_Cryptosystems),
//! [BK25](https://eprint.iacr.org/2025/819)).
//!
//! ## Share Reveals
//!
//! In order to prevent malicious dealers from withholding shares from players, we
//! require the dealers reveal the shares for which they did not receive acks.
//! Because of the synchrony assumption above, this will only happen if either:
//! - the dealer is malicious, not sending a share, but honestly revealing,
//! - or, the player is malicious, not sending an ack when they should.
//!
//! Thus, for honest players, in the worst case, `f` reveals get created, because
//! they correctly did not ack the `f` malicious dealers who failed to send them
//! a share. In that case, their final share remains secret, because it is the linear
//! combination of at least `f + 1` shares received from dealers.
//!
//! # Example
//!
//! For a complete example of how to instantiate this crate, check out [commonware-vrf](https://docs.rs/commonware-vrf).

pub mod arbiter;
pub use arbiter::Arbiter;
pub mod dealer;
pub use dealer::Dealer;
pub mod ops;
pub mod player;
pub use player::Player;
pub mod types;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("unexpected polynomial")]
    UnexpectedPolynomial,
    #[error("commitment has wrong degree")]
    CommitmentWrongDegree,
    #[error("misdirected share")]
    MisdirectedShare,
    #[error("share does not on commitment")]
    ShareWrongCommitment,
    #[error("insufficient dealings")]
    InsufficientDealings,
    #[error("reshare mismatch")]
    ReshareMismatch,
    #[error("share interpolation failed")]
    ShareInterpolationFailed,
    #[error("public key interpolation failed")]
    PublicKeyInterpolationFailed,
    #[error("dealer is invalid")]
    DealerInvalid,
    #[error("player invalid")]
    PlayerInvalid,
    #[error("missing share")]
    MissingShare,
    #[error("missing commitment")]
    MissingCommitment,
    #[error("too many commitments")]
    TooManyCommitments,
    #[error("duplicate commitment")]
    DuplicateCommitment,
    #[error("duplicate share")]
    DuplicateShare,
    #[error("duplicate ack")]
    DuplicateAck,
    #[error("mismatched commitment")]
    MismatchedCommitment,
    #[error("mismatched share")]
    MismatchedShare,
    #[error("too many reveals")]
    TooManyReveals,
    #[error("incorrect active")]
    IncorrectActive,
    #[error("already active")]
    AlreadyActive,
    #[error("invalid commitments")]
    InvalidCommitments,
    #[error("dealer disqualified")]
    DealerDisqualified,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        bls12381::primitives::{
            ops::{
                partial_sign_proof_of_possession, threshold_signature_recover,
                verify_proof_of_possession,
            },
            poly::{self, public},
            variant::{MinPk, MinSig, Variant},
        },
        ed25519::{PrivateKey, PublicKey},
        PrivateKeyExt as _, Signer as _,
    };
    use commonware_utils::{quorum, set::Ordered};
    use rand::{rngs::StdRng, SeedableRng};
    use std::collections::{BTreeMap, HashMap};

    #[test]
    fn test_invalid_commitment() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, _, shares) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create unrelated commitment of correct degree
        let t = quorum(n);
        let (public, _) = ops::generate_shares::<_, MinSig>(&mut rng, None, n, t);

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send invalid commitment to player
        let result = player.share(contributors[0].clone(), public, shares[0].clone());
        assert!(matches!(result, Err(Error::ShareWrongCommitment)));
    }

    #[test]
    fn test_mismatched_commitment() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create unrelated commitment of correct degree
        let t = quorum(n);
        let (other_commitment, _) = ops::generate_shares::<_, MinSig>(&mut rng, None, n, t);

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send valid commitment to player
        player
            .share(contributors[0].clone(), commitment, shares[0].clone())
            .unwrap();

        // Send alternative commitment to player
        let result = player.share(contributors[0].clone(), other_commitment, shares[0].clone());
        assert!(matches!(result, Err(Error::MismatchedCommitment)));
    }

    #[test]
    fn test_mismatched_share() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create unrelated commitment of correct degree
        let t = quorum(n);
        let (_, other_shares) = ops::generate_shares::<_, MinSig>(&mut rng, None, n, t);

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send valid share to player
        player
            .share(
                contributors[0].clone(),
                commitment.clone(),
                shares[0].clone(),
            )
            .unwrap();

        // Send alternative share to player
        let result = player.share(contributors[0].clone(), commitment, other_shares[0].clone());
        assert!(matches!(result, Err(Error::MismatchedShare)));
    }

    #[test]
    fn test_duplicate_share() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send valid share to player
        player
            .share(
                contributors[0].clone(),
                commitment.clone(),
                shares[0].clone(),
            )
            .unwrap();

        // Send alternative share to player
        let result = player.share(contributors[0].clone(), commitment, shares[0].clone());
        assert!(matches!(result, Err(Error::DuplicateShare)));
    }

    #[test]
    fn test_misdirected_share() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send misdirected share to player
        let result = player.share(
            contributors[0].clone(),
            commitment.clone(),
            shares[1].clone(),
        );
        assert!(matches!(result, Err(Error::MisdirectedShare)));
    }

    #[test]
    fn test_invalid_dealer() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send share from invalid dealer
        let dealer = PrivateKey::from_seed(n as u64).public_key();
        let result = player.share(dealer.clone(), commitment.clone(), shares[0].clone());
        assert!(matches!(result, Err(Error::DealerInvalid)));

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Send commitment from invalid dealer
        let result = arb.commitment(dealer, commitment, vec![0, 1, 2, 3], Vec::new());
        assert!(matches!(result, Err(Error::DealerInvalid)));
    }

    #[test]
    fn test_invalid_commitment_degree() {
        // Initialize test
        let n = 5;
        let t = quorum(n);
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create invalid commitments
        let mut commitments = Vec::new();
        let (public, shares) = ops::generate_shares::<_, MinSig>(&mut rng, None, n, 1);
        commitments.push((public, shares));
        let (public, shares) = ops::generate_shares::<_, MinSig>(&mut rng, None, n, t - 1);
        commitments.push((public, shares));
        let (public, shares) = ops::generate_shares::<_, MinSig>(&mut rng, None, n, t + 1);
        commitments.push((public, shares));

        // Check invalid commitments
        for (public, shares) in commitments {
            // Send invalid commitment to player
            let mut player = Player::<_, MinSig>::new(
                contributors[0].clone(),
                None,
                contributors.clone(),
                contributors.clone(),
                1,
            );
            let result = player.share(contributors[0].clone(), public.clone(), shares[0].clone());
            assert!(matches!(result, Err(Error::CommitmentWrongDegree)));

            // Create arbiter
            let mut arb =
                Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);
            let result = arb.commitment(
                contributors[0].clone(),
                public,
                vec![0, 1, 2, 3, 4],
                Vec::new(),
            );
            assert!(matches!(result, Err(Error::CommitmentWrongDegree)));
        }
    }

    #[test]
    fn test_reveal() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Add commitment to arbiter
        arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2, 3],
            vec![shares[4].clone()],
        )
        .unwrap();
    }

    #[test]
    fn test_arbiter_reveals() {
        // Initialize test
        let n = 11;
        let q = quorum(n as u32) as usize;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Create dealers
        let mut commitments = Vec::with_capacity(n);
        let mut reveals = Vec::with_capacity(n);
        for con in &contributors {
            // Create dealer
            let (_, commitment, shares) =
                Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
            commitments.push(commitment.clone());
            reveals.push(shares[q].clone());

            // Add commitment to arbiter
            let acks: Vec<u32> = (0..q as u32).collect();
            let reveals = shares[q..n].to_vec();
            arb.commitment(con.clone(), commitment, acks, reveals)
                .unwrap();
        }

        // Finalize arbiter
        let (result, _) = arb.finalize();
        let output = result.unwrap();

        // Ensure commitments and reveals are correct
        assert_eq!(output.commitments.len(), q);
        for (dealer_idx, commitment) in commitments.iter().enumerate().take(q) {
            let dealer_idx = dealer_idx as u32;
            assert_eq!(output.commitments.get(&dealer_idx).unwrap(), commitment);
            assert_eq!(
                output.reveals.get(&dealer_idx).unwrap()[0],
                reveals[dealer_idx as usize]
            );
        }
    }

    #[test]
    fn test_duplicate_commitment() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Add commitment to arbiter
        arb.commitment(
            contributors[0].clone(),
            commitment.clone(),
            vec![0, 1, 2, 3],
            vec![shares[4].clone()],
        )
        .unwrap();

        // Add commitment to arbiter (again)
        let result = arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2, 3],
            vec![shares[4].clone()],
        );
        assert!(matches!(result, Err(Error::DuplicateCommitment)));
    }

    #[test]
    fn test_reveal_duplicate_player() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Add commitment to arbiter
        let result = arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2, 3],
            vec![shares[3].clone()],
        );
        assert!(matches!(result, Err(Error::AlreadyActive)));
    }

    #[test]
    fn test_insufficient_active() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Add commitment to arbiter
        let result = arb.commitment(
            contributors[0].clone(),
            commitment.clone(),
            vec![0, 1, 2, 3],
            Vec::new(),
        );
        assert!(matches!(result, Err(Error::IncorrectActive)));

        // Add valid commitment to arbiter after disqualified
        let result = arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2, 3, 4],
            Vec::new(),
        );
        assert!(matches!(result, Err(Error::DealerDisqualified)));
    }

    #[test]
    fn test_manual_disqualify() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Disqualify dealer
        arb.disqualify(contributors[0].clone());

        // Add valid commitment to arbiter after disqualified
        let result = arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2, 3, 4],
            Vec::new(),
        );
        assert!(matches!(result, Err(Error::DealerDisqualified)));
    }

    #[test]
    fn test_too_many_reveals() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Add commitment to arbiter
        let result = arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2],
            vec![shares[3].clone(), shares[4].clone()],
        );
        assert!(matches!(result, Err(Error::TooManyReveals)));
    }

    #[test]
    fn test_incorrect_reveal() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create invalid shares
        let t = quorum(n);
        let (_, shares) = ops::generate_shares::<_, MinSig>(&mut rng, None, n, t);

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Add commitment to arbiter
        let result = arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2, 3],
            vec![shares[4].clone()],
        );
        assert!(matches!(result, Err(Error::ShareWrongCommitment)));
    }

    #[test]
    fn test_reveal_corrupt_share() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Swap share value
        let mut share = shares[3].clone();
        share.index = 4;

        // Add commitment to arbiter
        let result = arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2, 3],
            vec![share],
        );
        assert!(matches!(result, Err(Error::ShareWrongCommitment)));
    }

    #[test]
    fn test_reveal_duplicate_ack() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Add commitment to arbiter
        let result = arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2, 2],
            Vec::new(),
        );
        assert!(matches!(result, Err(Error::AlreadyActive)));
    }

    #[test]
    fn test_reveal_invalid_ack() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Add commitment to arbiter
        let result = arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2, 10],
            Vec::new(),
        );
        assert!(matches!(result, Err(Error::PlayerInvalid)));
    }

    #[test]
    fn test_reveal_invalid_share() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Create arbiter
        let mut arb =
            Arbiter::<_, MinSig>::new(None, contributors.clone(), contributors.clone(), 1);

        // Swap share value
        let mut share = shares[3].clone();
        share.index = 10;

        // Add commitment to arbiter
        let result = arb.commitment(
            contributors[0].clone(),
            commitment,
            vec![0, 1, 2, 3],
            vec![share],
        );
        assert!(matches!(result, Err(Error::PlayerInvalid)));
    }

    #[test]
    fn test_dealer_acks() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (mut dealer, _, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Ack all players
        for player in &contributors {
            dealer.ack(player.clone()).unwrap();
        }

        // Finalize dealer
        let output = dealer.finalize().unwrap();
        assert_eq!(Vec::from(output.active), vec![0, 1, 2, 3, 4]);
        assert!(output.inactive.is_empty());
    }

    #[test]
    fn test_dealer_inactive() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (mut dealer, _, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Ack all players
        for player in contributors.iter().take(4) {
            dealer.ack(player.clone()).unwrap();
        }

        // Finalize dealer
        let output = dealer.finalize().unwrap();
        assert_eq!(Vec::from(output.active), vec![0, 1, 2, 3]);
        assert_eq!(Vec::from(output.inactive), vec![4]);
    }

    #[test]
    fn test_dealer_insufficient() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (mut dealer, _, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Ack all players
        for player in contributors.iter().take(2) {
            dealer.ack(player.clone()).unwrap();
        }

        // Finalize dealer
        assert!(dealer.finalize().is_none());
    }

    #[test]
    fn test_dealer_duplicate_ack() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (mut dealer, _, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Ack player
        let player = contributors[0].clone();
        dealer.ack(player.clone()).unwrap();

        // Ack player (again)
        let result = dealer.ack(player);
        assert!(matches!(result, Err(Error::DuplicateAck)));
    }

    #[test]
    fn test_dealer_invalid_player() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create dealer
        let (mut dealer, _, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());

        // Ack invalid player
        let player = PrivateKey::from_seed(n as u64).public_key();
        let result = dealer.ack(player);
        assert!(matches!(result, Err(Error::PlayerInvalid)));
    }

    #[test]
    fn test_player_reveals() {
        // Initialize test
        let n = 11;
        let q = quorum(n as u32) as usize;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send shares to player
        let mut commitments = BTreeMap::new();
        for (i, con) in contributors.iter().enumerate().take(q - 1) {
            let (_, commitment, shares) =
                Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
            player
                .share(con.clone(), commitment.clone(), shares[0].clone())
                .unwrap();
            commitments.insert(i as u32, commitment);
        }

        // Finalize player with reveal
        let last = (q - 1) as u32;
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
        commitments.insert(last, commitment);
        let mut reveals = BTreeMap::new();
        reveals.insert(last, shares[0].clone());
        player.finalize(commitments, reveals).unwrap();
    }

    #[test]
    fn test_player_missing_reveal() {
        // Initialize test
        let n = 11;
        let q = quorum(n as u32) as usize;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send shares to player
        let mut commitments = BTreeMap::new();
        for (i, con) in contributors.iter().enumerate().take(q - 1) {
            let (_, commitment, shares) =
                Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
            player
                .share(con.clone(), commitment.clone(), shares[0].clone())
                .unwrap();
            commitments.insert(i as u32, commitment);
        }

        // Finalize player with reveal
        let last = (q - 1) as u32;
        let (_, commitment, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
        commitments.insert(last, commitment);
        let result = player.finalize(commitments, BTreeMap::new());
        assert!(matches!(result, Err(Error::MissingShare)));
    }

    #[test]
    fn test_player_insufficient_commitments() {
        // Initialize test
        let n = 5;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send shares to player
        let mut commitments = BTreeMap::new();
        for (i, con) in contributors.iter().enumerate().take(2) {
            let (_, commitment, shares) =
                Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
            player
                .share(con.clone(), commitment.clone(), shares[0].clone())
                .unwrap();
            commitments.insert(i as u32, commitment);
        }

        // Finalize player with reveal
        let result = player.finalize(commitments, BTreeMap::new());
        assert!(matches!(result, Err(Error::InvalidCommitments)));
    }

    #[test]
    fn test_player_misdirected_reveal() {
        // Initialize test
        let n = 11;
        let q = quorum(n as u32) as usize;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send shares to player
        let mut commitments = BTreeMap::new();
        for (i, con) in contributors.iter().enumerate().take(q - 1) {
            let (_, commitment, shares) =
                Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
            player
                .share(con.clone(), commitment.clone(), shares[0].clone())
                .unwrap();
            commitments.insert(i as u32, commitment);
        }

        // Finalize player with reveal
        let last = (q - 1) as u32;
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
        commitments.insert(last, commitment);
        let mut reveals = BTreeMap::new();
        reveals.insert(last, shares[1].clone());
        let result = player.finalize(commitments, reveals);
        assert!(matches!(result, Err(Error::MisdirectedShare)));
    }

    #[test]
    fn test_player_invalid_commitment() {
        // Initialize test
        let n = 11;
        let q = quorum(n as u32) as usize;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send shares to player
        let mut commitments = BTreeMap::new();
        for (i, con) in contributors.iter().enumerate().take(q - 1) {
            let (_, commitment, shares) =
                Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
            player
                .share(con.clone(), commitment.clone(), shares[0].clone())
                .unwrap();
            commitments.insert(i as u32, commitment);
        }

        // Finalize player with reveal
        let last = (q - 1) as u32;
        let (commitment, shares) = ops::generate_shares::<_, MinSig>(&mut rng, None, n as u32, 1);
        commitments.insert(last, commitment);
        let mut reveals = BTreeMap::new();
        reveals.insert(last, shares[0].clone());
        let result = player.finalize(commitments, reveals);
        assert!(matches!(result, Err(Error::CommitmentWrongDegree)));
    }

    #[test]
    fn test_player_invalid_reveal() {
        // Initialize test
        let n = 11;
        let q = quorum(n as u32) as usize;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send shares to player
        let mut commitments = BTreeMap::new();
        for (i, con) in contributors.iter().enumerate().take(q - 1) {
            let (_, commitment, shares) =
                Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
            player
                .share(con.clone(), commitment.clone(), shares[0].clone())
                .unwrap();
            commitments.insert(i as u32, commitment);
        }

        // Finalize player with reveal
        let last = (q - 1) as u32;
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
        commitments.insert(last, commitment);
        let mut reveals = BTreeMap::new();
        let mut share = shares[1].clone();
        share.index = 0;
        reveals.insert(last, share);
        let result = player.finalize(commitments, reveals);
        assert!(matches!(result, Err(Error::ShareWrongCommitment)));
    }

    #[test]
    fn test_player_dealer_equivocation() {
        // Initialize test
        let n = 11;
        let q = quorum(n as u32) as usize;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send shares to player
        let mut commitments = BTreeMap::new();
        for (i, con) in contributors.iter().enumerate().take(q - 1) {
            let (_, commitment, shares) =
                Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
            player
                .share(con.clone(), commitment.clone(), shares[0].clone())
                .unwrap();
            commitments.insert(i as u32, commitment);
        }

        // Finalize player with equivocating reveal
        let last = (q - 1) as u32;
        let (_, commitment, shares) =
            Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
        commitments.insert(last, commitment);

        // Add commitments
        let mut public = poly::Public::<MinSig>::zero();
        for commitment in commitments.values() {
            public.add(commitment);
        }

        // Finalize player with equivocating reveal
        let mut reveals = BTreeMap::new();
        reveals.insert(last, shares[0].clone());
        let result = player.finalize(commitments, reveals).unwrap();
        assert_eq!(result.public, public);
    }

    #[test]
    fn test_player_dealer_equivocation_missing_reveal() {
        // Initialize test
        let n = 11;
        let q = quorum(n as u32) as usize;
        let mut rng = StdRng::seed_from_u64(0);

        // Create contributors (must be in sorted order)
        let contributors = (0..n)
            .map(|i| PrivateKey::from_seed(i as u64).public_key())
            .collect::<Ordered<_>>();

        // Create player
        let mut player = Player::<_, MinSig>::new(
            contributors[0].clone(),
            None,
            contributors.clone(),
            contributors.clone(),
            1,
        );

        // Send shares to player
        let mut commitments = BTreeMap::new();
        for (i, con) in contributors.iter().enumerate().take(q - 1) {
            let (_, commitment, shares) =
                Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
            player
                .share(con.clone(), commitment.clone(), shares[0].clone())
                .unwrap();
            commitments.insert(i as u32, commitment);
        }

        // Finalize player with equivocating reveal
        let last = (q - 1) as u32;
        let (_, commitment, _) = Dealer::<_, MinSig>::new(&mut rng, None, contributors.clone());
        commitments.insert(last, commitment);

        // Finalize player with equivocating reveal
        let result = player.finalize(commitments, BTreeMap::new());
        assert!(matches!(result, Err(Error::MissingShare)));
    }

    /// Configuration for a single DKG/Resharing round.
    #[derive(Clone)]
    struct Round {
        players: Vec<u64>,
        absent_dealers: Vec<u64>,
        absent_players: Vec<u64>,
    }

    impl From<Vec<u64>> for Round {
        fn from(players: Vec<u64>) -> Self {
            Self {
                players,
                absent_dealers: Vec::new(),
                absent_players: Vec::new(),
            }
        }
    }

    impl Round {
        fn with_absent_dealers(mut self, absent_dealers: Vec<u64>) -> Self {
            self.absent_dealers = absent_dealers;
            self
        }

        fn with_absent_players(mut self, absent_players: Vec<u64>) -> Self {
            self.absent_players = absent_players;
            self
        }
    }

    /// Configuration for a sequence of DKG/Resharing rounds.
    #[derive(Clone)]
    struct Plan {
        rounds: Vec<Round>,
        seed: u64,
        concurrency: usize,
    }

    impl Plan {
        fn from(rounds: Vec<Round>) -> Self {
            Self {
                rounds,
                seed: 0,
                concurrency: 1,
            }
        }

        fn with_concurrency(mut self, concurrency: usize) -> Self {
            self.concurrency = concurrency;
            self
        }

        fn with_seed(mut self, seed: u64) -> Self {
            self.seed = seed;
            self
        }

        fn run<V: Variant>(&self) -> V::Public {
            // We must have at least one round to execute
            assert!(
                !self.rounds.is_empty(),
                "plan must contain at least one round"
            );

            // Create seeded RNG (for determinism)
            let mut rng = StdRng::seed_from_u64(self.seed);
            let mut current_public: Option<poly::Public<V>> = None;
            let mut participant_states: HashMap<PublicKey, player::Output<V>> = HashMap::new();
            let mut share_holders: Option<Ordered<PublicKey>> = None;

            // Process rounds
            for (round_idx, round) in self.rounds.iter().enumerate() {
                // Materialize dealer/player sets
                assert!(
                    !round.players.is_empty(),
                    "round {round_idx} must include at least one player",
                );
                let player_set = participants(&round.players);
                let dealer_candidates = if let Some(ref registry) = share_holders {
                    registry.clone()
                } else {
                    // If no previous share holders, use all players as dealers
                    player_set.clone()
                };
                assert!(
                    !dealer_candidates.is_empty(),
                    "round {round_idx} must have at least one dealer",
                );

                // Configure absent dealers and players
                let absent_dealers = participants(&round.absent_dealers);
                for absent in absent_dealers.iter() {
                    assert!(
                        dealer_candidates.position(absent).is_some(),
                        "round {round_idx} absent dealer not in committee"
                    );
                }
                let dealer_registry = if let Some(ref registry) = share_holders {
                    for dealer in dealer_candidates.iter() {
                        assert!(
                            registry.position(dealer).is_some(),
                            "round {round_idx} dealer not in previous committee",
                        );
                    }
                    registry.clone()
                } else {
                    dealer_candidates.clone()
                };
                let mut active_dealers = Vec::new();
                for dealer in dealer_candidates.iter() {
                    if absent_dealers.position(dealer).is_some() {
                        continue;
                    }
                    active_dealers.push(dealer.clone());
                }
                let active_len = active_dealers.len();
                let min_dealers = match current_public.as_ref() {
                    None => quorum(player_set.len() as u32),
                    Some(previous) => previous.required(),
                } as usize;
                assert!(
                    active_len >= min_dealers,
                    "round {} requires at least {} active dealers for {} players, got {}",
                    round_idx,
                    min_dealers,
                    player_set.len(),
                    active_len
                );
                let absent_players = participants(&round.absent_players);
                for absent in absent_players.iter() {
                    assert!(
                        player_set.position(absent).is_some(),
                        "round {round_idx} absent player not in committee"
                    );
                }

                // Setup dealers
                let mut dealers = BTreeMap::new();
                let mut dealer_outputs = BTreeMap::new();
                let mut expected_reveals = BTreeMap::new();
                let expected_inactive: Ordered<u32> = absent_players
                    .iter()
                    .map(|player_pk| player_set.position(player_pk).unwrap() as u32)
                    .collect();
                for dealer_pk in active_dealers.iter() {
                    let previous_share = participant_states
                        .get(dealer_pk)
                        .map(|out| out.share.clone());
                    if current_public.is_some() && previous_share.is_none() {
                        panic!("dealer missing share required for reshare in round {round_idx}",);
                    }

                    let (dealer, commitment, shares) =
                        Dealer::<_, V>::new(&mut rng, previous_share, player_set.clone());
                    dealers.insert(dealer_pk.clone(), dealer);
                    dealer_outputs.insert(dealer_pk.clone(), (commitment, shares));
                }

                // Setup players
                let mut players = BTreeMap::new();
                for player_pk in player_set.iter() {
                    if absent_players.position(player_pk).is_some() {
                        continue;
                    }
                    let player = Player::<_, V>::new(
                        player_pk.clone(),
                        current_public.clone(),
                        dealer_registry.clone(),
                        player_set.clone(),
                        self.concurrency,
                    );
                    players.insert(player_pk.clone(), player);
                }

                // Setup arbiter
                let mut arbiter = Arbiter::<_, V>::new(
                    current_public.clone(),
                    dealer_registry.clone(),
                    player_set.clone(),
                    self.concurrency,
                );

                // Distribute dealings
                for dealer_pk in active_dealers.iter() {
                    let (commitment, shares) = dealer_outputs
                        .get(dealer_pk)
                        .expect("missing dealer output");
                    let commitment = commitment.clone();
                    let shares = shares.clone();
                    let mut dealer_reveals = Vec::new();
                    {
                        let dealer = dealers.get_mut(dealer_pk).expect("missing dealer instance");
                        for (idx, player_pk) in player_set.iter().enumerate() {
                            let share = shares[idx].clone();
                            if absent_players.position(player_pk).is_some() {
                                dealer_reveals.push(share);
                                continue;
                            }
                            let player_obj = players
                                .get_mut(player_pk)
                                .expect("missing player for share delivery");
                            if let Err(err) =
                                player_obj.share(dealer_pk.clone(), commitment.clone(), share)
                            {
                                panic!(
                                    "failed to deliver share from dealer {dealer_pk:?} to player {player_pk:?}: {err:?}",
                                );
                            }
                            dealer.ack(player_pk.clone()).unwrap();
                        }
                    }

                    let dealer = dealers
                        .remove(dealer_pk)
                        .expect("missing dealer instance after distribution");
                    let dealer_output = dealer.finalize().expect("insufficient acknowledgements");
                    assert_eq!(
                        dealer_output.inactive, expected_inactive,
                        "inactive set mismatch for dealer in round {round_idx}",
                    );
                    let dealer_pos = dealer_registry.position(dealer_pk).unwrap() as u32;
                    if !dealer_reveals.is_empty() {
                        expected_reveals.insert(dealer_pos, dealer_reveals.clone());
                    }
                    arbiter
                        .commitment(
                            dealer_pk.clone(),
                            commitment,
                            dealer_output.active.into(),
                            dealer_reveals,
                        )
                        .unwrap();
                }

                // Finalize arbiter
                assert!(arbiter.ready(), "arbiter not ready in round {round_idx}");
                let (result, disqualified) = arbiter.finalize();
                let expected_disqualified =
                    dealer_registry.len().saturating_sub(active_dealers.len());
                assert_eq!(
                    disqualified.len(),
                    expected_disqualified,
                    "unexpected disqualified dealers in round {round_idx}",
                );
                let output = result.unwrap();
                for (&dealer_idx, _) in output.commitments.iter() {
                    let expected = expected_reveals.remove(&dealer_idx).unwrap_or_default();
                    match output.reveals.get(&dealer_idx) {
                        Some(reveals) => assert_eq!(
                            reveals, &expected,
                            "unexpected reveal content for dealer {dealer_idx} in round {round_idx}",
                        ),
                        None => assert!(
                            expected.is_empty(),
                            "missing reveals for dealer {dealer_idx} in round {round_idx}",
                        ),
                    }
                }
                for dealer_idx in output.reveals.keys() {
                    assert!(
                        output.commitments.contains_key(dealer_idx),
                        "reveals present for unselected dealer {dealer_idx} in round {round_idx}",
                    );
                }
                let expected_commitments = quorum(dealer_registry.len() as u32) as usize;
                assert_eq!(
                    output.commitments.len(),
                    expected_commitments,
                    "unexpected number of commitments in round {round_idx}",
                );

                // Finalize players (that were not revealed)
                let mut round_results = Vec::new();
                let mut next_states = HashMap::new();
                for player_pk in player_set.iter() {
                    if absent_players.position(player_pk).is_some() {
                        continue;
                    }
                    let player_obj = players.remove(player_pk).unwrap();
                    let result = player_obj
                        .finalize(output.commitments.clone(), BTreeMap::new())
                        .unwrap();
                    assert_eq!(result.public, output.public);
                    next_states.insert(player_pk.clone(), result.clone());
                    round_results.push(result);
                }
                assert!(
                    !round_results.is_empty(),
                    "round {round_idx} produced no outputs",
                );

                // Ensure public constant is maintained between rounds
                let public_key = public::<V>(&round_results[0].public);
                if let Some(previous) = current_public.as_ref() {
                    assert_eq!(public_key, public::<V>(previous));
                }

                // Check recovered shares by constructing a proof-of-possession
                let threshold = quorum(player_set.len() as u32);
                let partials = round_results
                    .iter()
                    .map(|res| partial_sign_proof_of_possession::<V>(&res.public, &res.share))
                    .collect::<Vec<_>>();
                let signature = threshold_signature_recover::<V, _>(threshold, &partials)
                    .expect("unable to recover threshold signature");
                verify_proof_of_possession::<V>(public_key, &signature)
                    .expect("invalid proof of possession");

                // Update state for next round
                current_public = Some(round_results[0].public.clone());
                share_holders = Some(player_set);
                participant_states = next_states;
            }

            // Return public constant
            *public::<V>(&current_public.expect("plan must produce a public constant"))
        }
    }

    // Compute the participant set from a list of IDs
    fn participants(ids: &[u64]) -> Ordered<PublicKey> {
        ids.iter()
            .map(|id| PrivateKey::from_seed(*id).public_key())
            .collect::<Ordered<_>>()
    }

    #[test]
    fn test_dkg() {
        let plan = Plan::from(vec![Round::from((0..5).collect::<Vec<_>>())]);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_dkg_with_absent_dealer() {
        let plan = Plan::from(vec![
            Round::from(vec![0, 1, 2, 3]).with_absent_dealers(vec![3])
        ]);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_dkg_with_absent_player() {
        let plan = Plan::from(vec![
            Round::from(vec![0, 1, 2, 3]).with_absent_players(vec![3])
        ]);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_dkg_determinism() {
        let plan_template = || Plan::from(vec![Round::from((0..5).collect::<Vec<_>>())]);

        let public_a_pk = plan_template().with_seed(1).run::<MinPk>();
        assert_eq!(public_a_pk, plan_template().with_seed(1).run::<MinPk>());
        let public_b_pk = plan_template().with_seed(2).run::<MinPk>();
        assert_eq!(public_b_pk, plan_template().with_seed(2).run::<MinPk>());
        assert_ne!(public_a_pk, public_b_pk);

        let public_a_sig = plan_template().with_seed(1).run::<MinSig>();
        assert_eq!(public_a_sig, plan_template().with_seed(1).run::<MinSig>());
        let public_b_sig = plan_template().with_seed(2).run::<MinSig>();
        assert_eq!(public_b_sig, plan_template().with_seed(2).run::<MinSig>());
        assert_ne!(public_a_sig, public_b_sig);
    }

    #[test]
    fn test_reshare_distinct() {
        let plan = Plan::from(vec![
            Round::from((0..5).collect::<Vec<_>>()),
            Round::from((5..15).collect::<Vec<_>>()),
            Round::from((15..30).collect::<Vec<_>>()),
        ]);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_reshare_increasing_committee() {
        let plan = Plan::from(vec![
            Round::from(vec![0, 1, 2]),
            Round::from(vec![0, 1, 2, 3]),
            Round::from(vec![0, 1, 2, 3, 4]),
            Round::from(vec![0, 1, 2, 3, 4, 5]),
        ]);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_reshare_decreasing_committee() {
        let plan = Plan::from(vec![
            Round::from(vec![0, 1, 2, 3, 4, 5]),
            Round::from(vec![0, 1, 2, 3, 4]),
            Round::from(vec![0, 1, 2, 3]),
            Round::from(vec![0, 1, 2]),
        ]);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_reshare_with_absent_dealer() {
        let plan = Plan::from(vec![
            Round::from(vec![0, 1, 2, 3]),
            Round::from(vec![4, 5, 6, 7]).with_absent_dealers(vec![3]),
        ]);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_reshare_with_absent_player() {
        let plan = Plan::from(vec![
            Round::from(vec![0, 1, 2, 3]),
            Round::from(vec![4, 5, 6, 7]).with_absent_players(vec![4]),
            Round::from(vec![8, 9, 10, 11]).with_absent_dealers(vec![4]),
        ]);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_reshare_min_active() {
        let plan = Plan::from(vec![
            Round::from(vec![0, 1, 2, 3]).with_absent_players(vec![3]),
            Round::from(vec![4, 5, 6, 7]).with_absent_dealers(vec![3]),
        ]);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_reshare_min_active_different_sizes() {
        let plan = Plan::from(vec![
            Round::from(vec![0, 1, 2, 3]).with_absent_players(vec![3]),
            Round::from(vec![4, 5, 6, 7, 8, 9]).with_absent_dealers(vec![3]),
        ]);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_reshare_min_active_large() {
        let plan = Plan::from(vec![
            Round::from((0..20).collect::<Vec<_>>())
                .with_absent_dealers((14..20).collect::<Vec<_>>())
                .with_absent_players((14..20).collect::<Vec<_>>()),
            Round::from((100..200).collect::<Vec<_>>())
                .with_absent_dealers((14..20).collect::<Vec<_>>()),
        ])
        .with_concurrency(4);
        plan.run::<MinPk>();
        plan.run::<MinSig>();
    }

    #[test]
    fn test_reshare_determinism() {
        let plan_template = || {
            Plan::from(vec![
                Round::from((0..5).collect::<Vec<_>>()),
                Round::from((5..10).collect::<Vec<_>>()),
            ])
        };

        let public_a_pk = plan_template().with_seed(1).run::<MinPk>();
        assert_eq!(public_a_pk, plan_template().with_seed(1).run::<MinPk>());
        let public_b_pk = plan_template().with_seed(2).run::<MinPk>();
        assert_eq!(public_b_pk, plan_template().with_seed(2).run::<MinPk>());
        assert_ne!(public_a_pk, public_b_pk);

        let public_a_sig = plan_template().with_seed(1).run::<MinSig>();
        assert_eq!(public_a_sig, plan_template().with_seed(1).run::<MinSig>());
        let public_b_sig = plan_template().with_seed(2).run::<MinSig>();
        assert_eq!(public_b_sig, plan_template().with_seed(2).run::<MinSig>());
        assert_ne!(public_a_sig, public_b_sig);
    }
}