commonware-cryptography 2026.4.0

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
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
//! Distributed Key Generation (DKG) and Resharing protocol for the BLS12-381 curve.
//!
//! This module 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 involves _dealers_ and _players_. The dealers are trying to jointly create a shared
//! key, and then distribute it among the players. The dealers may have pre-existing shares of a key
//! from a previous round, in which case the goal is to re-distribute that key among the players,
//! with fresh randomness.
//!
//! The protocol is also designed such that an external observer can figure out whether the protocol
//! succeeded or failed, and learn of the public outputs of the protocol. This includes
//! the participants in the protocol, and the public polynomial committing to the key
//! and its sharing.
//!
//! # Usage
//!
//! ## Core Types
//!
//! * [`Info`]: Configuration for a DKG/Reshare round, containing the dealers, players, and optional previous output
//! * [`Output`]: The public result of a successful DKG round, containing the public polynomial and player list
//! * [`Share`]: A player's final private share of the distributed key (from `primitives::group`)
//! * [`Dealer`]: State machine for a dealer participating in the protocol
//! * [`Player`]: State machine for a player receiving dealings
//! * [`SignedDealerLog`]: A dealer's signed transcript of their interactions with players
//!
//! ## Message Types
//!
//! * [`DealerPubMsg`]: Public commitment polynomial sent from dealer to all players
//! * [`DealerPrivMsg`]: Private dealing sent from dealer to a specific player
//! * [`PlayerAck`]: Acknowledgement sent from player back to dealer
//! * [`DealerLog`]: Complete log of a dealer's interactions (commitments and acks/reveals)
//!
//! ## Protocol Flow
//!
//! ### Step 1: Initialize Round
//!
//! Create a [`Info`] using [`Info::new`] with:
//! - Round number (should increment sequentially, including for failed rounds)
//! - Optional previous [`Output`] (for resharing)
//! - List of dealers (must be >= quorum of previous round if resharing)
//! - List of players who will receive dealings
//!
//! ### Step 2: Dealer Phase
//!
//! Each dealer calls [`Dealer::start`] which returns:
//! - A [`Dealer`] instance for tracking state
//! - A [`DealerPubMsg`] containing the polynomial commitment to broadcast
//! - A vector of `(player_id, DealerPrivMsg)` pairs to send privately
//!
//! The [`DealerPubMsg`] contains a public polynomial commitment of degree `2f` where `f = max_faults(n)`.
//! Each [`DealerPrivMsg`] contains a scalar evaluation of the dealer's private polynomial at the player's index.
//!
//! ### Step 3: Player Verification
//!
//! Each player creates a [`Player`] instance via [`Player::new`], then for each dealer message:
//! - Call [`Player::dealer_message`] with the [`DealerPubMsg`] and [`DealerPrivMsg`]
//! - If valid, this returns a [`PlayerAck`] containing a signature over `(dealer, commitment)`
//! - The player verifies that the private dealing matches the public commitment evaluation
//!
//! ### Step 4: Dealer Collection
//!
//! Each dealer:
//! - Calls [`Dealer::receive_player_ack`] for each acknowledgement received
//! - After timeout, calls [`Dealer::finalize`] to produce a [`SignedDealerLog`]
//! - The log contains the commitment and either acks or reveals for each player
//!
//! ### Step 5: Finalization
//!
//! With collected [`SignedDealerLog`]s:
//! - Call [`SignedDealerLog::check`] to verify and extract [`DealerLog`]s
//! - Players call [`Player::finalize`] with all logs to compute their [`Share`] and [`Output`]
//! - Observers call [`observe`] with all logs to compute just the [`Output`]
//!
//! The [`Output`] contains:
//! - The final public polynomial (sum of dealer polynomials for DKG, interpolation for reshare),
//! - The list of dealers who distributed dealings,
//! - The list of players who received shares,
//! - The set of players whose shares may have been revealed,
//! - A digest of the round's [`Info`] (including the counter, and the list of dealers and players).
//!
//! ## Trusted Dealing Functions
//!
//! As a convenience (for tests, etc.), this module also provides functions for
//! generating shares using a trusted dealer.
//!
//! - [`deal`]: given a list of players, generates an [`Output`] like the DKG would,
//! - [`deal_anonymous`]: a lower-level version that produces a polynomial directly,
//!   and doesn't require public keys for the players.
//!
//! ## State
//!
//! The structs in this module are stateful and they assume that they exist from the
//! start of the DKG to the end of the DKG.
//!
//! During restart, state should be restored by replaying all messages that
//! dealers and players previously processed. For the dealer, it's important to use a
//! seeded form of randomness, so that way the same messages can be generated on a second run.
//! For the player, using [`Player::resume`] is more robust than just [`Player::new`], because it
//! checks the integrity of the replayed messages against the publicly committed transcript (so far).
//! This can detect some recoverable operator errors, like storage misconfiguration (where a player has publicly
//! acknowledged a private message but has no record of it in storage).
//!
//! # Caveats
//!
//! ## 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.
//!
//! Under synchrony (as discussed below), 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.
//!
//! ### Up to `f` Reveals Under Synchrony
//!
//! Under synchrony (where `t` is the maximum amount of time it takes for a message to be sent between any two participants),
//! this construction will not result in more than `f` reveals from honest dealers, and none of those reveals are for honest players
//! (`2f + 1` commitments with 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 each 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...recall, a Byzantine dealer can opt to reveal any
//! player's dealing even if they sent an acknowledgement).
//!
//! 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` points for a linear combination 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.
//!
//! ### Up to `2f` Reveals Under Asynchrony
//!
//! If the network is asynchronous, Byzantine players may obtain up to `2f` revealed shares (`f` from Byzantine players
//! and `f` from honest players).
//!
//! 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. 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` revealed shares). **It will not be possible for any external observer (or a Byzantine adversary), however, to recover the shared secret.**
//!
//! While not entirely revealed, a secret with more than `f` revealed shares may no longer be safe for some applications (like when used to
//! form threshold certificates for consensus). Consider an equivocating leader (one of the `f` Byzantine players) that sends one block `B_1` to `f`
//! honest players and another block `B_2` to `f + 1` other honest players. Normally, it would only be possible to create one quorum of `2f + 1` (for `B_2`),
//! however, with `h` other shares revealed another quorum of `2f + h` can be formed for `B_1`.
//!
//! #### Future Work: Dropping the Synchrony Assumption for `f` Bounded Reveals?
//!
//! 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).
//!
//! ## Handling 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.
//!
//! In practice:
//! - [`Player::dealer_message`] returns `None` for invalid messages (implicit complaint)
//! - [`Dealer::receive_player_ack`] validates acknowledgements
//! - Other custom mechanisms can exclude dealers before calling [`observe`] or [`Player::finalize`],
//!   to enforce other rules for "misbehavior" beyond what the DKG does already.
//!
//! ## 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)).
//!
//! # Example
//!
//! ```
//! use commonware_cryptography::bls12381::{
//!     dkg::{Dealer, Info, Logs, Player, SignedDealerLog, observe},
//!     primitives::{variant::MinSig, sharing::Mode},
//! };
//! use commonware_cryptography::{ed25519, Signer};
//! use commonware_math::algebra::Random;
//! use commonware_utils::{ordered::Set, TryCollect, N3f1};
//! use std::collections::BTreeMap;
//! use rand::SeedableRng;
//! use rand_chacha::ChaCha8Rng;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut rng = ChaCha8Rng::seed_from_u64(42);
//!
//! // Generate 4 Ed25519 private keys for participants
//! let mut private_keys = Vec::new();
//! for _ in 0..4 {
//!     let private_key = ed25519::PrivateKey::random(&mut rng);
//!     private_keys.push(private_key);
//! }
//!
//! // All 4 participants are both dealers and players in initial DKG
//! let dealer_set: Set<ed25519::PublicKey> = private_keys.iter()
//!     .map(|k| k.public_key())
//!     .try_collect()?;
//! let player_set = dealer_set.clone();
//!
//! // Step 1: Create round info for initial DKG
//! let info = Info::<MinSig, ed25519::PublicKey>::new::<N3f1>(
//!     b"application-namespace",
//!     0,                        // round number
//!     None,                     // no previous output (initial DKG)
//!     Mode::default(),   // sharing mode
//!     dealer_set.clone(),       // dealers
//!     player_set.clone(),       // players
//! )?;
//!
//! // Step 2: Initialize players
//! let mut players = BTreeMap::new();
//! for private_key in &private_keys {
//!     let player = Player::<MinSig, ed25519::PrivateKey>::new(
//!         info.clone(),
//!         private_key.clone(),
//!     )?;
//!     players.insert(private_key.public_key(), player);
//! }
//!
//! // Step 3: Run dealer protocol for each participant
//! let mut logs = Logs::<MinSig, ed25519::PublicKey, N3f1>::new(info.clone());
//! for dealer_priv in &private_keys {
//!     // Each dealer generates messages for all players
//!     let (mut dealer, pub_msg, priv_msgs) = Dealer::start::<N3f1>(
//!         &mut rng,
//!         info.clone(),
//!         dealer_priv.clone(),
//!         None,  // no previous share for initial DKG
//!     )?;
//!
//!     // Distribute messages to players and collect acknowledgements
//!     for (player_pk, priv_msg) in priv_msgs {
//!         if let Some(player) = players.get_mut(&player_pk) {
//!             if let Some(ack) = player.dealer_message::<N3f1>(
//!                 dealer_priv.public_key(),
//!                 pub_msg.clone(),
//!                 priv_msg,
//!             ) {
//!                 dealer.receive_player_ack(player_pk, ack)?;
//!             }
//!         }
//!     }
//!
//!     // Finalize dealer and verify log
//!     let signed_log = dealer.finalize::<N3f1>();
//!     if let Some((dealer_pk, log)) = signed_log.check(&info) {
//!         logs.record(dealer_pk, log);
//!     }
//! }
//!
//! // Step 4: Players finalize to get their shares
//! let mut player_shares = BTreeMap::new();
//! for (player_pk, player) in players {
//!     let (output, share) = player.finalize::<N3f1, ed25519::Batch>(
//!       &mut rng,
//!       logs.clone(),
//!       &commonware_parallel::Sequential,
//!     )?;
//!     println!("Player {:?} got share at index {}", player_pk, share.index);
//!     player_shares.insert(player_pk, share);
//! }
//!
//! // Step 5: Observer can also compute the public output
//! let observer_output = observe::<MinSig, ed25519::PublicKey, N3f1, ed25519::Batch>(
//!     &mut rng,
//!     logs,
//!     &commonware_parallel::Sequential,
//! )?;
//! println!("DKG completed with threshold {}", observer_output.quorum::<N3f1>());
//! # Ok(())
//! # }
//! ```
//!
//! For a complete example with resharing, see [commonware-reshare](https://docs.rs/commonware-reshare).

use super::primitives::group::{Private, Share};
use crate::{
    bls12381::primitives::{
        group::Scalar,
        sharing::{Mode, ModeVersion, Sharing},
        variant::Variant,
    },
    transcript::{Summary, Transcript},
    BatchVerifier, PublicKey, Secret, Signer,
};
use commonware_codec::{Encode, EncodeSize, RangeCfg, Read, ReadExt, Write};
use commonware_math::{
    algebra::{Additive, CryptoGroup, Random, Ring as _},
    poly::{Interpolator, Poly},
};
use commonware_parallel::{Sequential, Strategy};
#[cfg(feature = "arbitrary")]
use commonware_utils::N3f1;
use commonware_utils::{
    ordered::{Map, Quorum, Set},
    Faults, Participant, TryCollect, NZU32,
};
use core::num::NonZeroU32;
use rand_core::CryptoRngCore;
use std::{borrow::Cow, collections::BTreeMap, marker::PhantomData};
use thiserror::Error;

const NAMESPACE: &[u8] = b"_COMMONWARE_CRYPTOGRAPHY_BLS12381_DKG";
const SIG_ACK: &[u8] = b"ack";
const SIG_LOG: &[u8] = b"log";
const NOISE_PRE_VERIFY: &[u8] = b"pre_verify";

/// The error type for the DKG protocol.
///
/// The only error which can happen through no fault of your own is
/// [`Error::DkgFailed`].
///
/// [`Error::MissingPlayerDealing`] happens through mistakes or faults when the state
/// of a player is restored after a crash.
///
/// The other errors are due to issues with configuration or misuse.
#[derive(Debug, Error)]
pub enum Error {
    #[error("missing dealer's share from the previous round")]
    MissingDealerShare,
    #[error("player is not present in the list of players")]
    UnknownPlayer,
    #[error("dealer is not present in the previous list of players")]
    UnknownDealer(String),
    #[error("invalid number of dealers: {0}")]
    NumDealers(usize),
    #[error("invalid number of players: {0}")]
    NumPlayers(usize),
    #[error("dkg failed for some reason")]
    DkgFailed,
    #[error("logs are bound to a different dkg round")]
    MismatchedLogs,
    /// The player's state is missing a dealing it should have.
    ///
    /// This error is emitted when the player is missing dealings that it should
    /// otherwise have based on the flow of the protocol. This can only happen if
    /// the code in this module is used in a stateful way, restoring the
    /// state of the player from saved information. If this state is corrupted
    /// on disk, or missing, then this error can happen.
    #[error("missing player's dealing")]
    MissingPlayerDealing,
}

/// The output of a successful DKG.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Output<V: Variant, P> {
    summary: Summary,
    public: Sharing<V>,
    dealers: Set<P>,
    players: Set<P>,
    revealed: Set<P>,
}

impl<V: Variant, P: Ord> Output<V, P> {
    fn share_commitment(&self, player: &P) -> Option<V::Public> {
        self.public.partial_public(self.players.index(player)?).ok()
    }

    /// Return the quorum, i.e. the number of players needed to reconstruct the key.
    pub fn quorum<M: Faults>(&self) -> u32 {
        self.players.quorum::<M>()
    }

    /// Get the public polynomial associated with this output.
    ///
    /// This is useful for verifying partial signatures, with [crate::bls12381::primitives::ops::threshold::verify_message].
    pub const fn public(&self) -> &Sharing<V> {
        &self.public
    }

    /// Return the dealers who were selected in this round of the DKG.
    pub const fn dealers(&self) -> &Set<P> {
        &self.dealers
    }

    /// Return the players who participated in this round of the DKG, and should have shares.
    pub const fn players(&self) -> &Set<P> {
        &self.players
    }

    /// Return the set of players whose shares may have been revealed.
    ///
    /// These are players who had more than `max_faults` reveals.
    pub const fn revealed(&self) -> &Set<P> {
        &self.revealed
    }
}

impl<V: Variant, P: PublicKey> EncodeSize for Output<V, P> {
    fn encode_size(&self) -> usize {
        self.summary.encode_size()
            + self.public.encode_size()
            + self.dealers.encode_size()
            + self.players.encode_size()
            + self.revealed.encode_size()
    }
}

impl<V: Variant, P: PublicKey> Write for Output<V, P> {
    fn write(&self, buf: &mut impl bytes::BufMut) {
        self.summary.write(buf);
        self.public.write(buf);
        self.dealers.write(buf);
        self.players.write(buf);
        self.revealed.write(buf);
    }
}

impl<V: Variant, P: PublicKey> Read for Output<V, P> {
    type Cfg = (NonZeroU32, ModeVersion);

    fn read_cfg(
        buf: &mut impl bytes::Buf,
        (max_participants, max_supported_mode): &Self::Cfg,
    ) -> Result<Self, commonware_codec::Error> {
        let max_participants_usize = max_participants.get() as usize;
        Ok(Self {
            summary: ReadExt::read(buf)?,
            public: Read::read_cfg(buf, &(*max_participants, *max_supported_mode))?,
            dealers: Read::read_cfg(buf, &(RangeCfg::new(1..=max_participants_usize), ()))?, // at least one dealer must be part of a dealing
            players: Read::read_cfg(buf, &(RangeCfg::new(1..=max_participants_usize), ()))?, // at least one player must be part of a dealing
            revealed: Read::read_cfg(buf, &(RangeCfg::new(0..=max_participants_usize), ()))?, // there may not be any reveals
        })
    }
}

#[cfg(feature = "arbitrary")]
impl<P: PublicKey, V: Variant> arbitrary::Arbitrary<'_> for Output<V, P>
where
    P: for<'a> arbitrary::Arbitrary<'a> + Ord,
    V::Public: for<'a> arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let summary = u.arbitrary()?;
        let public: Sharing<V> = u.arbitrary()?;
        let total = public.total().get() as usize;

        let num_dealers = u.int_in_range(1..=total * 2)?;
        let dealers = Set::try_from(
            u.arbitrary_iter::<P>()?
                .take(num_dealers)
                .collect::<Result<Vec<_>, _>>()?,
        )
        .map_err(|_| arbitrary::Error::IncorrectFormat)?;

        let players = Set::try_from(
            u.arbitrary_iter::<P>()?
                .take(total)
                .collect::<Result<Vec<_>, _>>()?,
        )
        .map_err(|_| arbitrary::Error::IncorrectFormat)?;

        let max_revealed = N3f1::max_faults(total) as usize;
        let revealed = Set::from_iter_dedup(
            players
                .iter()
                .filter(|_| u.arbitrary::<bool>().unwrap_or(false))
                .take(max_revealed)
                .cloned(),
        );

        Ok(Self {
            summary,
            public,
            dealers,
            players,
            revealed,
        })
    }
}

/// Information about the current round of the DKG.
///
/// This is used to bind signatures to the current round, and to provide the
/// information that dealers, players, and observers need to perform their actions.
#[derive(Debug, Clone)]
pub struct Info<V: Variant, P: PublicKey> {
    summary: Summary,
    round: u64,
    previous: Option<Output<V, P>>,
    mode: Mode,
    dealers: Set<P>,
    players: Set<P>,
}

impl<V: Variant, P: PublicKey> PartialEq for Info<V, P> {
    fn eq(&self, other: &Self) -> bool {
        self.summary == other.summary
    }
}

impl<V: Variant, P: PublicKey> Info<V, P> {
    /// Figure out what the dealer share should be.
    ///
    /// If there's no previous round, we need a random value, hence `rng`.
    ///
    /// However, if there is a previous round, we expect a share, hence `Result`.
    fn unwrap_or_random_share(
        &self,
        mut rng: impl CryptoRngCore,
        share: Option<Scalar>,
    ) -> Result<Scalar, Error> {
        let out = match (self.previous.as_ref(), share) {
            (None, None) => Scalar::random(&mut rng),
            (_, Some(x)) => x,
            (Some(_), None) => return Err(Error::MissingDealerShare),
        };
        Ok(out)
    }

    const fn num_players(&self) -> NonZeroU32 {
        // Will not panic because we check that the number of players is non-empty in `new`
        NZU32!(self.players.len() as u32)
    }

    fn degree<M: Faults>(&self) -> u32 {
        self.players.quorum::<M>().saturating_sub(1)
    }

    fn required_commitments<M: Faults>(&self) -> u32 {
        let dealer_quorum = self.dealers.quorum::<M>();
        let prev_quorum = self
            .previous
            .as_ref()
            .map(Output::quorum::<M>)
            .unwrap_or(u32::MIN);
        dealer_quorum.max(prev_quorum)
    }

    fn max_reveals<M: Faults>(&self) -> u32 {
        self.players.max_faults::<M>()
    }

    fn player_index(&self, player: &P) -> Result<Participant, Error> {
        self.players.index(player).ok_or(Error::UnknownPlayer)
    }

    fn dealer_index(&self, dealer: &P) -> Result<Participant, Error> {
        self.dealers
            .index(dealer)
            .ok_or(Error::UnknownDealer(format!("{dealer:?}")))
    }

    fn player_scalar(&self, player: &P) -> Result<Scalar, Error> {
        Ok(self
            .mode
            .scalar(self.num_players(), self.player_index(player)?)
            .expect("player index should be < num_players"))
    }

    #[must_use]
    fn check_dealer_pub_msg<M: Faults>(&self, dealer: &P, pub_msg: &DealerPubMsg<V>) -> bool {
        if self.degree::<M>() != pub_msg.commitment.degree_exact() {
            return false;
        }
        if let Some(previous) = self.previous.as_ref() {
            let Some(share_commitment) = previous.share_commitment(dealer) else {
                return false;
            };
            if *pub_msg.commitment.constant() != share_commitment {
                return false;
            }
        }
        true
    }

    #[must_use]
    fn check_dealer_priv_msg(
        &self,
        player: &P,
        pub_msg: &DealerPubMsg<V>,
        priv_msg: &DealerPrivMsg,
    ) -> bool {
        let Ok(scalar) = self.player_scalar(player) else {
            return false;
        };
        let expected = pub_msg.commitment.eval_msm(&scalar, &Sequential);
        priv_msg
            .share
            .expose(|share| expected == V::Public::generator() * share)
    }

    #[must_use]
    fn check_dealer_log<M: Faults, B: BatchVerifier<PublicKey = P>>(
        &self,
        rng: &mut impl CryptoRngCore,
        strategy: &impl Strategy,
        round_transcript: &Transcript,
        dealer: &P,
        log: &DealerLog<V, P>,
    ) -> bool {
        if self.dealer_index(dealer).is_err() {
            return false;
        }
        if !self.check_dealer_pub_msg::<M>(dealer, &log.pub_msg) {
            return false;
        }
        let Some(results_iter) = log.zip_players(&self.players) else {
            return false;
        };
        let ack_summary = transcript_for_ack(round_transcript, dealer, &log.pub_msg).summarize();
        let mut ack_batch = B::new();
        let mut reveal_count = 0;
        let max_reveals = self.max_reveals::<M>();
        let mut reveal_eval_points = Vec::new();
        let mut reveal_sum = Scalar::zero();
        for (player, result) in results_iter {
            match result {
                AckOrReveal::Ack(ack) => {
                    if !ack_summary.add_to_batch(&mut ack_batch, player, &ack.sig) {
                        return false;
                    }
                }
                AckOrReveal::Reveal(priv_msg) => {
                    reveal_count += 1;
                    if reveal_count > max_reveals {
                        return false;
                    }
                    let Ok(player_scalar) = self.player_scalar(player) else {
                        return false;
                    };
                    let coeff = if reveal_count == 1 {
                        Scalar::one()
                    } else {
                        Scalar::random(&mut *rng)
                    };
                    reveal_eval_points.push((coeff.clone(), player_scalar));
                    priv_msg
                        .share
                        .expose(|share| reveal_sum += &(coeff * share));
                }
            }
        }
        if !ack_batch.verify(&mut *rng) {
            return false;
        }
        let lhs = log.pub_msg.commitment.lin_comb_eval(
            reveal_eval_points
                .into_iter()
                .map(|(coeff, point)| (coeff, Cow::Owned(point))),
            strategy,
        );
        lhs == V::Public::generator() * &reveal_sum
    }
}

impl<V: Variant, P: PublicKey> Info<V, P> {
    /// Create a new [`Info`].
    ///
    /// `namespace` must be provided to isolate different applications
    /// performing DKGs from each other.
    /// `round` should be a counter, always incrementing, even for failed DKGs.
    /// `previous` should be the result of the previous successful DKG.
    /// `dealers` should be the list of public keys for the dealers. This MUST
    /// be a subset of the previous round's players.
    /// `players` should be the list of public keys for the players.
    pub fn new<M: Faults>(
        namespace: &[u8],
        round: u64,
        previous: Option<Output<V, P>>,
        mode: Mode,
        dealers: Set<P>,
        players: Set<P>,
    ) -> Result<Self, Error> {
        let participant_range = 1..u32::MAX as usize;
        if !participant_range.contains(&dealers.len()) {
            return Err(Error::NumDealers(dealers.len()));
        }
        if !participant_range.contains(&players.len()) {
            return Err(Error::NumPlayers(players.len()));
        }
        if let Some(previous) = previous.as_ref() {
            if let Some(unknown) = dealers
                .iter()
                .find(|d| previous.players.position(d).is_none())
            {
                return Err(Error::UnknownDealer(format!("{unknown:?}")));
            }
            if dealers.len() < previous.quorum::<M>() as usize {
                return Err(Error::NumDealers(dealers.len()));
            }
        }
        let summary = {
            let mut transcript = Transcript::new(NAMESPACE);
            transcript
                .commit(namespace)
                .commit(round.encode())
                .commit(previous.encode())
                .commit(dealers.encode())
                .commit(players.encode());
            // We want backwards compatibility with the default mode, which wasn't
            // committed. The absence of the mode is thus treated as an implicit
            // default in the transcript, so this is sound.
            if mode != Mode::default() {
                transcript.commit([mode as u8].as_slice());
            }
            transcript.summarize()
        };
        Ok(Self {
            summary,
            round,
            previous,
            mode,
            dealers,
            players,
        })
    }

    /// Return the round number for this round.
    ///
    /// Round numbers should increase sequentially.
    pub const fn round(&self) -> u64 {
        self.round
    }
}

#[derive(Clone, Debug)]
pub struct DealerPubMsg<V: Variant> {
    commitment: Poly<V::Public>,
}

impl<V: Variant> PartialEq for DealerPubMsg<V> {
    fn eq(&self, other: &Self) -> bool {
        self.commitment == other.commitment
    }
}

impl<V: Variant> Eq for DealerPubMsg<V> {}

impl<V: Variant> EncodeSize for DealerPubMsg<V> {
    fn encode_size(&self) -> usize {
        self.commitment.encode_size()
    }
}

impl<V: Variant> Write for DealerPubMsg<V> {
    fn write(&self, buf: &mut impl bytes::BufMut) {
        self.commitment.write(buf);
    }
}

impl<V: Variant> Read for DealerPubMsg<V> {
    type Cfg = NonZeroU32;

    fn read_cfg(
        buf: &mut impl bytes::Buf,
        &max_size: &Self::Cfg,
    ) -> Result<Self, commonware_codec::Error> {
        Ok(Self {
            commitment: Read::read_cfg(buf, &(RangeCfg::from(NZU32!(1)..=max_size), ()))?,
        })
    }
}

#[cfg(feature = "arbitrary")]
impl<V: Variant> arbitrary::Arbitrary<'_> for DealerPubMsg<V>
where
    V::Public: for<'a> arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let commitment = u.arbitrary()?;
        Ok(Self { commitment })
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DealerPrivMsg {
    share: Secret<Scalar>,
}

impl DealerPrivMsg {
    /// Creates a new `DealerPrivMsg` with the given share.
    pub const fn new(share: Scalar) -> Self {
        Self {
            share: Secret::new(share),
        }
    }
}

impl EncodeSize for DealerPrivMsg {
    fn encode_size(&self) -> usize {
        self.share.expose(|share| share.encode_size())
    }
}

impl Write for DealerPrivMsg {
    fn write(&self, buf: &mut impl bytes::BufMut) {
        self.share.expose(|share| share.write(buf));
    }
}

impl Read for DealerPrivMsg {
    type Cfg = ();

    fn read_cfg(
        buf: &mut impl bytes::Buf,
        _cfg: &Self::Cfg,
    ) -> Result<Self, commonware_codec::Error> {
        Ok(Self::new(ReadExt::read(buf)?))
    }
}

#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary<'_> for DealerPrivMsg {
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        Ok(Self::new(u.arbitrary()?))
    }
}

#[derive(Clone, Debug)]
pub struct PlayerAck<P: PublicKey> {
    sig: P::Signature,
}

impl<P: PublicKey> PartialEq for PlayerAck<P> {
    fn eq(&self, other: &Self) -> bool {
        self.sig == other.sig
    }
}

impl<P: PublicKey> EncodeSize for PlayerAck<P> {
    fn encode_size(&self) -> usize {
        self.sig.encode_size()
    }
}

impl<P: PublicKey> Write for PlayerAck<P> {
    fn write(&self, buf: &mut impl bytes::BufMut) {
        self.sig.write(buf);
    }
}

impl<P: PublicKey> Read for PlayerAck<P> {
    type Cfg = ();

    fn read_cfg(
        buf: &mut impl bytes::Buf,
        _cfg: &Self::Cfg,
    ) -> Result<Self, commonware_codec::Error> {
        Ok(Self {
            sig: ReadExt::read(buf)?,
        })
    }
}

#[cfg(feature = "arbitrary")]
impl<P: PublicKey> arbitrary::Arbitrary<'_> for PlayerAck<P>
where
    P::Signature: for<'a> arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let sig = u.arbitrary()?;
        Ok(Self { sig })
    }
}

#[derive(Clone, PartialEq)]
enum AckOrReveal<P: PublicKey> {
    Ack(PlayerAck<P>),
    Reveal(DealerPrivMsg),
}

impl<P: PublicKey> AckOrReveal<P> {
    const fn is_reveal(&self) -> bool {
        matches!(*self, Self::Reveal(_))
    }
}

impl<P: PublicKey> std::fmt::Debug for AckOrReveal<P> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Ack(x) => write!(f, "Ack({x:?})"),
            Self::Reveal(_) => write!(f, "Reveal(REDACTED)"),
        }
    }
}

impl<P: PublicKey> EncodeSize for AckOrReveal<P> {
    fn encode_size(&self) -> usize {
        1 + match self {
            Self::Ack(x) => x.encode_size(),
            Self::Reveal(x) => x.encode_size(),
        }
    }
}

impl<P: PublicKey> Write for AckOrReveal<P> {
    fn write(&self, buf: &mut impl bytes::BufMut) {
        match self {
            Self::Ack(x) => {
                0u8.write(buf);
                x.write(buf);
            }
            Self::Reveal(x) => {
                1u8.write(buf);
                x.write(buf);
            }
        }
    }
}

impl<P: PublicKey> Read for AckOrReveal<P> {
    type Cfg = ();

    fn read_cfg(
        buf: &mut impl bytes::Buf,
        _cfg: &Self::Cfg,
    ) -> Result<Self, commonware_codec::Error> {
        let tag = u8::read(buf)?;
        match tag {
            0 => Ok(Self::Ack(ReadExt::read(buf)?)),
            1 => Ok(Self::Reveal(ReadExt::read(buf)?)),
            x => Err(commonware_codec::Error::InvalidEnum(x)),
        }
    }
}

#[cfg(feature = "arbitrary")]
impl<P: PublicKey> arbitrary::Arbitrary<'_> for AckOrReveal<P>
where
    P: for<'a> arbitrary::Arbitrary<'a>,
    P::Signature: for<'a> arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let choice = u.int_in_range(0..=1)?;
        match choice {
            0 => {
                let ack = u.arbitrary()?;
                Ok(Self::Ack(ack))
            }
            1 => {
                let reveal = u.arbitrary()?;
                Ok(Self::Reveal(reveal))
            }
            _ => unreachable!(),
        }
    }
}

#[derive(Clone, Debug)]
enum DealerResult<P: PublicKey> {
    Ok(Map<P, AckOrReveal<P>>),
    TooManyReveals,
}

impl<P: PublicKey> PartialEq for DealerResult<P> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Ok(x), Self::Ok(y)) => x == y,
            (Self::TooManyReveals, Self::TooManyReveals) => true,
            _ => false,
        }
    }
}

impl<P: PublicKey> EncodeSize for DealerResult<P> {
    fn encode_size(&self) -> usize {
        1 + match self {
            Self::Ok(r) => r.encode_size(),
            Self::TooManyReveals => 0,
        }
    }
}

impl<P: PublicKey> Write for DealerResult<P> {
    fn write(&self, buf: &mut impl bytes::BufMut) {
        match self {
            Self::Ok(r) => {
                0u8.write(buf);
                r.write(buf);
            }
            Self::TooManyReveals => {
                1u8.write(buf);
            }
        }
    }
}

impl<P: PublicKey> Read for DealerResult<P> {
    type Cfg = NonZeroU32;

    fn read_cfg(
        buf: &mut impl bytes::Buf,
        &max_players: &Self::Cfg,
    ) -> Result<Self, commonware_codec::Error> {
        let tag = u8::read(buf)?;
        match tag {
            0 => Ok(Self::Ok(Read::read_cfg(
                buf,
                &(RangeCfg::from(0..=max_players.get() as usize), (), ()),
            )?)),
            1 => Ok(Self::TooManyReveals),
            x => Err(commonware_codec::Error::InvalidEnum(x)),
        }
    }
}

#[cfg(feature = "arbitrary")]
impl<P: PublicKey> arbitrary::Arbitrary<'_> for DealerResult<P>
where
    P: for<'a> arbitrary::Arbitrary<'a>,
    P::Signature: for<'a> arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let choice = u.int_in_range(0..=1)?;
        match choice {
            0 => {
                use commonware_utils::TryFromIterator;
                use std::collections::HashMap;

                let base: HashMap<P, AckOrReveal<P>> = u.arbitrary()?;
                let map =
                    Map::try_from_iter(base).map_err(|_| arbitrary::Error::IncorrectFormat)?;

                Ok(Self::Ok(map))
            }
            1 => Ok(Self::TooManyReveals),
            _ => unreachable!(),
        }
    }
}

#[derive(Clone, Debug)]
pub struct DealerLog<V: Variant, P: PublicKey> {
    pub_msg: DealerPubMsg<V>,
    results: DealerResult<P>,
}

impl<V: Variant, P: PublicKey> PartialEq for DealerLog<V, P> {
    fn eq(&self, other: &Self) -> bool {
        self.pub_msg == other.pub_msg && self.results == other.results
    }
}

impl<V: Variant, P: PublicKey> EncodeSize for DealerLog<V, P> {
    fn encode_size(&self) -> usize {
        self.pub_msg.encode_size() + self.results.encode_size()
    }
}

impl<V: Variant, P: PublicKey> Write for DealerLog<V, P> {
    fn write(&self, buf: &mut impl bytes::BufMut) {
        self.pub_msg.write(buf);
        self.results.write(buf);
    }
}

impl<V: Variant, P: PublicKey> Read for DealerLog<V, P> {
    type Cfg = NonZeroU32;

    fn read_cfg(
        buf: &mut impl bytes::Buf,
        cfg: &Self::Cfg,
    ) -> Result<Self, commonware_codec::Error> {
        Ok(Self {
            pub_msg: Read::read_cfg(buf, cfg)?,
            results: Read::read_cfg(buf, cfg)?,
        })
    }
}

impl<V: Variant, P: PublicKey> DealerLog<V, P> {
    fn get_ack(&self, player: &P) -> Option<&PlayerAck<P>> {
        let DealerResult::Ok(results) = &self.results else {
            return None;
        };
        match results.get_value(player) {
            Some(AckOrReveal::Ack(ack)) => Some(ack),
            _ => None,
        }
    }

    fn get_reveal(&self, player: &P) -> Option<&DealerPrivMsg> {
        let DealerResult::Ok(results) = &self.results else {
            return None;
        };
        match results.get_value(player) {
            Some(AckOrReveal::Reveal(priv_msg)) => Some(priv_msg),
            _ => None,
        }
    }

    fn zip_players<'a, 'b>(
        &'a self,
        players: &'b Set<P>,
    ) -> Option<impl Iterator<Item = (&'b P, &'a AckOrReveal<P>)>> {
        match &self.results {
            DealerResult::TooManyReveals => None,
            DealerResult::Ok(results) => {
                // We don't check this on deserialization.
                if results.keys() != players {
                    return None;
                }
                Some(players.iter().zip(results.values().iter()))
            }
        }
    }

    /// Return a [`DealerLogSummary`] of the results in this log.
    ///
    /// This can be useful for observing the progress of the DKG.
    pub fn summary(&self) -> DealerLogSummary<P> {
        match &self.results {
            DealerResult::TooManyReveals => DealerLogSummary::TooManyReveals,
            DealerResult::Ok(map) => {
                let (reveals, acks): (Vec<_>, Vec<_>) =
                    map.iter_pairs().partition(|(_, a_r)| a_r.is_reveal());
                DealerLogSummary::Ok {
                    acks: acks
                        .into_iter()
                        .map(|(p, _)| p.clone())
                        .try_collect()
                        .expect("map keys are deduped"),
                    reveals: reveals
                        .into_iter()
                        .map(|(p, _)| p.clone())
                        .try_collect()
                        .expect("map keys are deduped"),
                }
            }
        }
    }
}

/// Information about the reveals and acks in a [`DealerLog`].
// This exists to have a public interface we're happy maintaining, not leaking
// internal details about various things.
#[derive(Clone, Debug)]
pub enum DealerLogSummary<P> {
    /// The dealer is refusing to post any information, because they would have
    /// too many reveals otherwise.
    TooManyReveals,
    /// The dealer has some players who acked, and some players who didn't, that it's revealing.
    Ok { acks: Set<P>, reveals: Set<P> },
}

#[cfg(feature = "arbitrary")]
impl<V: Variant, P: PublicKey> arbitrary::Arbitrary<'_> for DealerLog<V, P>
where
    P: for<'a> arbitrary::Arbitrary<'a>,
    V::Public: for<'a> arbitrary::Arbitrary<'a>,
    P::Signature: for<'a> arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let pub_msg = u.arbitrary()?;
        let results = u.arbitrary()?;
        Ok(Self { pub_msg, results })
    }
}

/// A [`DealerLog`], but identified to and signed by a dealer.
///
/// The [`SignedDealerLog::check`] method allows extracting a public key (the dealer)
/// and a [`DealerLog`] from this struct.
///
/// This avoids having to trust some other party or process for knowing that a
/// dealer actually produced a log.
#[derive(Clone, Debug)]
pub struct SignedDealerLog<V: Variant, S: Signer> {
    dealer: S::PublicKey,
    log: DealerLog<V, S::PublicKey>,
    sig: S::Signature,
}

impl<V: Variant, S: Signer> PartialEq for SignedDealerLog<V, S> {
    fn eq(&self, other: &Self) -> bool {
        self.dealer == other.dealer && self.log == other.log && self.sig == other.sig
    }
}

impl<V: Variant, S: Signer> SignedDealerLog<V, S> {
    fn sign(sk: &S, info: &Info<V, S::PublicKey>, log: DealerLog<V, S::PublicKey>) -> Self {
        let sig = transcript_for_log(info, &log).sign(sk);
        Self {
            dealer: sk.public_key(),
            log,
            sig,
        }
    }

    /// Check this log for a particular round.
    ///
    /// This will produce the public key of the dealer that signed this log,
    /// and the underlying log that they signed.
    ///
    /// This will return [`Option::None`] if the check fails.
    #[allow(clippy::type_complexity)]
    pub fn check(
        self,
        info: &Info<V, S::PublicKey>,
    ) -> Option<(S::PublicKey, DealerLog<V, S::PublicKey>)> {
        if !transcript_for_log(info, &self.log).verify(&self.dealer, &self.sig) {
            return None;
        }
        Some((self.dealer, self.log))
    }
}

impl<V: Variant, S: Signer> EncodeSize for SignedDealerLog<V, S> {
    fn encode_size(&self) -> usize {
        self.dealer.encode_size() + self.log.encode_size() + self.sig.encode_size()
    }
}

impl<V: Variant, S: Signer> Write for SignedDealerLog<V, S> {
    fn write(&self, buf: &mut impl bytes::BufMut) {
        self.dealer.write(buf);
        self.log.write(buf);
        self.sig.write(buf);
    }
}

impl<V: Variant, S: Signer> Read for SignedDealerLog<V, S> {
    type Cfg = NonZeroU32;

    fn read_cfg(
        buf: &mut impl bytes::Buf,
        cfg: &Self::Cfg,
    ) -> Result<Self, commonware_codec::Error> {
        Ok(Self {
            dealer: ReadExt::read(buf)?,
            log: Read::read_cfg(buf, cfg)?,
            sig: ReadExt::read(buf)?,
        })
    }
}

#[cfg(feature = "arbitrary")]
impl<V: Variant, S: Signer> arbitrary::Arbitrary<'_> for SignedDealerLog<V, S>
where
    S::PublicKey: for<'a> arbitrary::Arbitrary<'a>,
    V::Public: for<'a> arbitrary::Arbitrary<'a>,
    S::Signature: for<'a> arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let dealer = u.arbitrary()?;
        let log = u.arbitrary()?;
        let sig = u.arbitrary()?;
        Ok(Self { dealer, log, sig })
    }
}

fn transcript_for_round<V: Variant, P: PublicKey>(info: &Info<V, P>) -> Transcript {
    Transcript::resume(info.summary)
}

fn transcript_for_ack<V: Variant, P: PublicKey>(
    transcript: &Transcript,
    dealer: &P,
    pub_msg: &DealerPubMsg<V>,
) -> Transcript {
    let mut out = transcript.fork(SIG_ACK);
    out.commit(dealer.encode());
    out.commit(pub_msg.encode());
    out
}

fn transcript_for_log<V: Variant, P: PublicKey>(
    info: &Info<V, P>,
    log: &DealerLog<V, P>,
) -> Transcript {
    let mut out = transcript_for_round(info).fork(SIG_LOG);
    out.commit(log.encode());
    out
}

/// Accumulates dealer logs for a DKG round and caches verification results so
/// `pre_verify` work can be reused until a dealer's log is replaced.
#[derive(Clone)]
pub struct Logs<V: Variant, P: PublicKey, M: Faults> {
    info: Info<V, P>,
    logs: BTreeMap<P, DealerLog<V, P>>,
    known: BTreeMap<P, bool>,
    phantom_m: PhantomData<M>,
}

// Keep the selected logs paired with the bound round info without repeating
// the tuple shape at each `select` call site.
type SelectedLogs<V, P> = (Info<V, P>, Map<P, DealerLog<V, P>>);

impl<V: Variant, P: PublicKey, M: Faults> Logs<V, P, M> {
    /// Create a log set bound to a particular DKG round.
    pub fn new(info: Info<V, P>) -> Self {
        Self {
            info,
            logs: Default::default(),
            known: Default::default(),
            phantom_m: Default::default(),
        }
    }

    fn check_dealers<B: BatchVerifier<PublicKey = P>>(
        rng: &mut impl CryptoRngCore,
        info: &Info<V, P>,
        strategy: &impl Strategy,
        transcript: &Transcript,
        dealers: &[(&P, &DealerLog<V, P>)],
    ) -> Vec<(P, bool)> {
        let checks: Vec<_> = dealers
            .iter()
            .map(|&(dealer, log)| {
                let seed = Summary::random(&mut *rng);
                ((*dealer).clone(), log, seed)
            })
            .collect();

        // This uses signature batch verification only for a particular dealer's
        // signatures. We could batch across all dealers, but in practice this starts
        // performing worse than just using parallelism with at least 4 threads,
        // and also introduces a slow path if any dealer has a bad sig. This slow
        // path can easily be exercised by an adversary.
        strategy.map_collect_vec(checks, |(dealer, log, seed)| {
            let mut local_rng = Transcript::resume(seed).noise(NOISE_PRE_VERIFY);
            let valid =
                info.check_dealer_log::<M, B>(&mut local_rng, strategy, transcript, &dealer, log);
            (dealer, valid)
        })
    }

    /// Record the log for a particular dealer.
    ///
    /// Return `true` if the dealer was already present in the log, in which
    /// case its log will be replaced.
    pub fn record(&mut self, dealer: P, log: DealerLog<V, P>) -> bool {
        self.known.remove(&dealer);
        self.logs.insert(dealer, log).is_some()
    }

    /// Verify the logs that we've received so far.
    ///
    /// This makes finalization faster, by doing some of
    /// the verification work now.
    ///
    /// This method can amortize work over a batch of items. It's more efficient
    /// to call it after several [`Self::record`], rather than after
    /// each call.
    pub fn pre_verify<B: BatchVerifier<PublicKey = P>>(
        &mut self,
        rng: &mut impl CryptoRngCore,
        strategy: &impl Strategy,
    ) {
        let required_commitments = self.info.required_commitments::<M>() as usize;
        let transcript = transcript_for_round(&self.info);

        // Create a pending batch, which we try and optimistically size as small as
        // possible, to avoid verifying more dealers than we need, if they're all
        // honest.
        let mut need = required_commitments;
        let mut pending = Vec::new();
        let mut iter = self.logs.iter();
        while need > 0 {
            let Some((dealer, log)) = iter.next() else {
                break;
            };
            match self.known.get(dealer) {
                Some(true) => need -= 1,
                Some(false) => {}
                None => {
                    need -= 1;
                    pending.push((dealer, log));
                }
            }
        }

        // Verify the batch and update the known valid dealers.
        let pending_results =
            Self::check_dealers::<B>(rng, &self.info, strategy, &transcript, &pending);
        let mut all_pending_valid = true;
        for (dealer, is_valid) in pending_results {
            self.known.insert(dealer, is_valid);
            all_pending_valid &= is_valid;
        }
        if all_pending_valid {
            return;
        }

        // We could jump back to the start of the function to recalculate the minimal pending set,
        // hoping that they would all be valid again. However, in this case, we're
        // dealing with some dealers that are malicious, and they might be trying to
        // slow down verification as much as possible by making us waste our time with
        // undue optimism. We instead adopt a pessimistic approach, assuming the
        // worst: that we might need to check all of the remaining dealers
        // to find the honest ones we need.
        let remaining: Vec<_> = iter
            .filter(|(dealer, _)| !self.known.contains_key(*dealer))
            .collect();
        let results = Self::check_dealers::<B>(rng, &self.info, strategy, &transcript, &remaining);
        for (dealer, is_valid) in results {
            self.known.insert(dealer, is_valid);
        }
    }

    /// Given the logs we've received, determine which dealer logs to use, if any.
    ///
    /// This might return an error if there are not enough good logs that we can use.
    fn select<B: BatchVerifier<PublicKey = P>>(
        mut self,
        rng: &mut impl CryptoRngCore,
        strategy: &impl Strategy,
    ) -> Result<SelectedLogs<V, P>, Error> {
        self.pre_verify::<B>(rng, strategy);
        let required_commitments = self.info.required_commitments::<M>() as usize;
        let out: Map<_, _> = self
            .logs
            .into_iter()
            .filter(|(dealer, _)| matches!(self.known.get(dealer), Some(true)))
            .take(required_commitments)
            .try_collect()
            .expect("dealers should be unique");
        if out.len() < required_commitments {
            return Err(Error::DkgFailed);
        }
        Ok((self.info, out))
    }
}

pub struct Dealer<V: Variant, S: Signer> {
    me: S,
    info: Info<V, S::PublicKey>,
    pub_msg: DealerPubMsg<V>,
    results: Map<S::PublicKey, AckOrReveal<S::PublicKey>>,
    transcript: Transcript,
}

impl<V: Variant, S: Signer> Dealer<V, S> {
    /// Create a [`Dealer`].
    ///
    /// This needs randomness, to generate a dealing.
    ///
    /// We also need the dealer's private key, in order to produce the [`SignedDealerLog`].
    ///
    /// If we're doing a reshare, the dealer should have a share from the previous round.
    ///
    /// This will produce the [`Dealer`], a [`DealerPubMsg`] to send to every player,
    /// and a list of [`DealerPrivMsg`]s, along with which players those need to
    /// be sent to.
    ///
    /// The public message can be sent in the clear, but it's important that players
    /// know which dealer sent what public message. You MUST ensure that dealers
    /// cannot impersonate each-other when sending this message.
    ///
    /// The private message MUST be sent encrypted (or, in some other way, privately)
    /// to the target player. Similarly, that player MUST be convinced that this dealer
    /// sent it that message, without any possibility of impersonation. A simple way
    /// to provide both guarantees is through an authenticated channel, e.g. via
    /// [crate::handshake], or [commonware-p2p](https://docs.rs/commonware-p2p/latest/commonware_p2p/).
    #[allow(clippy::type_complexity)]
    pub fn start<M: Faults>(
        mut rng: impl CryptoRngCore,
        info: Info<V, S::PublicKey>,
        me: S,
        share: Option<Share>,
    ) -> Result<(Self, DealerPubMsg<V>, Vec<(S::PublicKey, DealerPrivMsg)>), Error> {
        // Check that this dealer is defined in the round.
        info.dealer_index(&me.public_key())?;
        let share = info.unwrap_or_random_share(
            &mut rng,
            // We are extracting the private scalar from `Secret` protection because
            // `Poly::new_with_constant` requires an owned value. The extracted scalar is
            // scoped to this function and will be zeroized on drop (i.e. the secret is
            // only exposed for the duration of this function).
            share.map(|x| x.private.expose_unwrap()),
        )?;
        let my_poly = Poly::new_with_constant(&mut rng, info.degree::<M>(), share);
        let priv_msgs = info
            .players
            .iter()
            .map(|pk| {
                (
                    pk.clone(),
                    DealerPrivMsg::new(my_poly.eval_msm(
                        &info.player_scalar(pk).expect("player should exist"),
                        &Sequential,
                    )),
                )
            })
            .collect::<Vec<_>>();
        let results: Map<_, _> = priv_msgs
            .clone()
            .into_iter()
            .map(|(pk, priv_msg)| (pk, AckOrReveal::Reveal(priv_msg)))
            .try_collect()
            .expect("players are unique");
        let commitment = Poly::commit(my_poly);
        let pub_msg = DealerPubMsg { commitment };
        let transcript = {
            let t = transcript_for_round(&info);
            transcript_for_ack(&t, &me.public_key(), &pub_msg)
        };
        let this = Self {
            me,
            info,
            pub_msg: pub_msg.clone(),
            results,
            transcript,
        };
        Ok((this, pub_msg, priv_msgs))
    }

    /// Process an acknowledgement from a player.
    ///
    /// Acknowledgements should really only be processed once per player,
    /// but this method is idempotent nonetheless.
    pub fn receive_player_ack(
        &mut self,
        player: S::PublicKey,
        ack: PlayerAck<S::PublicKey>,
    ) -> Result<(), Error> {
        let res_mut = self
            .results
            .get_value_mut(&player)
            .ok_or(Error::UnknownPlayer)?;
        if self.transcript.verify(&player, &ack.sig) {
            *res_mut = AckOrReveal::Ack(ack);
        }
        Ok(())
    }

    /// Finalize the dealer, producing a signed log.
    ///
    /// This should be called at the point where no more acks will be processed.
    pub fn finalize<M: Faults>(self) -> SignedDealerLog<V, S> {
        let reveals = self
            .results
            .values()
            .iter()
            .filter(|x| x.is_reveal())
            .count() as u32;
        // Omit results if there are too many reveals.
        let results = if reveals > self.info.max_reveals::<M>() {
            DealerResult::TooManyReveals
        } else {
            DealerResult::Ok(self.results)
        };
        let log = DealerLog {
            pub_msg: self.pub_msg,
            results,
        };
        SignedDealerLog::sign(&self.me, &self.info, log)
    }
}

struct ObserveInner<V: Variant, P: PublicKey> {
    output: Output<V, P>,
    weights: Option<Interpolator<P, Scalar>>,
}

impl<V: Variant, P: PublicKey> ObserveInner<V, P> {
    fn reckon<M: Faults>(
        info: Info<V, P>,
        selected: Map<P, DealerLog<V, P>>,
        strategy: &impl Strategy,
    ) -> Result<Self, Error> {
        // Track players with too many reveals
        let max_faults = info.players.max_faults::<M>();
        let mut reveal_counts: BTreeMap<P, u32> = BTreeMap::new();
        let mut revealed = Vec::new();
        for log in selected.values() {
            let Some(iter) = log.zip_players(&info.players) else {
                continue;
            };
            for (player, result) in iter {
                if !result.is_reveal() {
                    continue;
                }
                let count = reveal_counts.entry(player.clone()).or_insert(0);
                *count += 1;
                if *count == max_faults + 1 {
                    revealed.push(player.clone());
                }
            }
        }
        let revealed: Set<P> = revealed
            .into_iter()
            .try_collect()
            .expect("players are unique");

        // Extract dealers before consuming selected
        let dealers: Set<P> = selected
            .keys()
            .iter()
            .cloned()
            .try_collect()
            .expect("selected dealers are unique");

        // Recover the public polynomial
        let (public, weights) = if let Some(previous) = info.previous.as_ref() {
            let weights = previous
                .public()
                .mode()
                .subset_interpolator(previous.players(), selected.keys())
                .expect("the result of select should produce a valid subset");
            let commitments = selected
                .into_iter()
                .map(|(dealer, log)| (dealer, log.pub_msg.commitment))
                .try_collect::<Map<_, _>>()
                .expect("Map should have unique keys");
            let public = weights
                .interpolate(&commitments, strategy)
                .expect("select checks that enough points have been provided");
            if previous.public().public() != public.constant() {
                return Err(Error::DkgFailed);
            }
            (public, Some(weights))
        } else {
            let mut public = Poly::zero();
            for log in selected.values() {
                public += &log.pub_msg.commitment;
            }
            (public, None)
        };
        let n = info.players.len() as u32;
        let output = Output {
            summary: info.summary,
            public: Sharing::new(info.mode, NZU32!(n), public),
            dealers,
            players: info.players,
            revealed,
        };
        Ok(Self { output, weights })
    }
}

/// Observe the result of a DKG, using the public results.
///
/// The log mapping dealers to their log is the shared piece of information
/// that the participants (players, observers) of the DKG must all agree on.
///
/// From this log, we can (potentially, as the DKG can fail) compute the public output.
///
/// This will only ever return [`Error::DkgFailed`].
pub fn observe<V: Variant, P: PublicKey, M: Faults, B: BatchVerifier<PublicKey = P>>(
    rng: &mut impl CryptoRngCore,
    logs: Logs<V, P, M>,
    strategy: &impl Strategy,
) -> Result<Output<V, P>, Error> {
    let (info, selected) = logs.select::<B>(rng, strategy)?;
    ObserveInner::<V, P>::reckon::<M>(info, selected, strategy).map(|x| x.output)
}

/// Represents a player in the DKG / reshare process.
///
/// The player is attempting to get a share of the key.
///
/// They need not have participated in prior rounds.
pub struct Player<V: Variant, S: Signer> {
    me: S,
    me_pub: S::PublicKey,
    info: Info<V, S::PublicKey>,
    index: Participant,
    transcript: Transcript,
    view: BTreeMap<S::PublicKey, (DealerPubMsg<V>, DealerPrivMsg)>,
}

impl<V: Variant, S: Signer> Player<V, S> {
    /// Create a new [`Player`].
    ///
    /// We need the player's private key in order to sign messages.
    pub fn new(info: Info<V, S::PublicKey>, me: S) -> Result<Self, Error> {
        let me_pub = me.public_key();
        Ok(Self {
            index: info.player_index(&me_pub)?,
            me,
            me_pub,
            transcript: transcript_for_round(&info),
            info,
            view: BTreeMap::new(),
        })
    }

    /// Resume a [`Player`], given some existing public state.
    ///
    /// This is equivalent to calling [`Self::new`] and then [`Self::dealer_message`]
    /// with the appropriate messages, but includes extra safeguards to detect
    /// missing / corrupted state.
    ///
    /// It's imperative that the `logs` passed in have been verified. This is done
    /// naturally when converting from a [`SignedDealerLog`] to a [`DealerLog`],
    /// but this function, like [`Player::finalize`], assumes that this check has
    /// been done.
    ///
    /// All messages the player should have received must be passed into this method,
    /// and if any messages which should be present based on this player's actions
    /// in the log are missing, this method will return [`Error::MissingPlayerDealing`].
    ///
    /// For example, if a particular private message containing a share is not
    /// present in `msgs`, but we've already acknowledged it, and this has been
    /// included in a public log, then this method will fail.
    /// This method cannot catch all cases where state has been corrupted. In
    /// particular, if a dealer has not posted their log publicly yet, but has
    /// already received an ack, then this method cannot help in that case,
    /// but the issue still remains.
    ///
    /// The returned map contains the acknowledgements generated while replaying
    /// `msgs`, keyed by dealer.
    #[allow(clippy::type_complexity)]
    pub fn resume<M: Faults>(
        info: Info<V, S::PublicKey>,
        me: S,
        logs: &BTreeMap<S::PublicKey, DealerLog<V, S::PublicKey>>,
        msgs: impl IntoIterator<Item = (S::PublicKey, DealerPubMsg<V>, DealerPrivMsg)>,
    ) -> Result<(Self, BTreeMap<S::PublicKey, PlayerAck<S::PublicKey>>), Error> {
        // Record all acks we've emitted (by dealer).
        let mut this = Self::new(info, me)?;
        let mut acks = BTreeMap::new();
        for (dealer, pub_msg, priv_msg) in msgs {
            if let Some(ack) = this.dealer_message::<M>(dealer.clone(), pub_msg, priv_msg) {
                acks.insert(dealer, ack);
            }
        }

        // Have we emitted any valid acks, publicly recorded, for which we do
        // not have the private message?
        if logs.iter().any(|(dealer, log)| {
            let Some(ack) = log.get_ack(&this.me_pub) else {
                return false;
            };
            // Only trust this ack if the signature is valid for this round.
            transcript_for_ack(&this.transcript, dealer, &log.pub_msg)
                .verify(&this.me_pub, &ack.sig)
                && !acks.contains_key(dealer)
        }) {
            // If so, we have a problem, because we're missing a dealing that we're
            // supposed to have, and that we publicly committed to having.
            return Err(Error::MissingPlayerDealing);
        }

        Ok((this, acks))
    }

    /// Process a message from a dealer.
    ///
    /// It's important that nobody can impersonate the dealer, and that the
    /// private message was not exposed to anyone else. A convenient way to
    /// provide this is by using an authenticated channel, e.g. via
    /// [crate::handshake], or [commonware-p2p](https://docs.rs/commonware-p2p/latest/commonware_p2p/).
    pub fn dealer_message<M: Faults>(
        &mut self,
        dealer: S::PublicKey,
        pub_msg: DealerPubMsg<V>,
        priv_msg: DealerPrivMsg,
    ) -> Option<PlayerAck<S::PublicKey>> {
        if self.view.contains_key(&dealer) {
            return None;
        }
        self.info.dealer_index(&dealer).ok()?;
        if !self.info.check_dealer_pub_msg::<M>(&dealer, &pub_msg) {
            return None;
        }
        if !self
            .info
            .check_dealer_priv_msg(&self.me_pub, &pub_msg, &priv_msg)
        {
            return None;
        }
        let sig = transcript_for_ack(&self.transcript, &dealer, &pub_msg).sign(&self.me);
        self.view.insert(dealer, (pub_msg, priv_msg));
        Some(PlayerAck { sig })
    }

    /// Finalize the player, producing an output, and a share.
    ///
    /// This should agree with [`observe`], in terms of `Ok` vs `Err` (with one exception)
    /// and the public output, so long as the logs agree. It's crucial that the players
    /// come to agreement, in some way, on exactly which logs they need to use
    /// for finalize.
    ///
    /// The exception is that if this function returns [`Error::MissingPlayerDealing`],
    /// then [`observe`] will return `Ok`, because this error indicates that this
    /// player's state has been corrupted, but the DKG has otherwise succeeded.
    /// However, this player's share is not recoverable without external intervention.
    ///
    /// Otherwise, this function returns [`Error::DkgFailed`] if the DKG fails, or
    /// [`Error::MismatchedLogs`] if `logs` are bound to a different DKG round.
    pub fn finalize<M: Faults, B: BatchVerifier<PublicKey = S::PublicKey>>(
        self,
        rng: &mut impl CryptoRngCore,
        logs: Logs<V, S::PublicKey, M>,
        strategy: &impl Strategy,
    ) -> Result<(Output<V, S::PublicKey>, Share), Error> {
        // `Logs::select` verifies ack signatures, so any ack present in `selected`
        // is trustworthy for this round/dealer/pub_msg transcript.
        // If there's a log that contains an ack of ours, but no corresponding view,
        // then we're missing a dealing.
        if logs.info != self.info {
            return Err(Error::MismatchedLogs);
        }
        let (_, selected) = logs.select::<B>(rng, strategy)?;
        if selected
            .iter_pairs()
            .any(|(d, l)| l.get_ack(&self.me_pub).is_some() && !self.view.contains_key(d))
        {
            return Err(Error::MissingPlayerDealing);
        }

        // We are extracting the private scalars from `Secret` protection
        // because interpolation/summation needs owned scalars for polynomial
        // arithmetic. The extracted scalars are scoped to this function and
        // will be zeroized on drop (i.e. the secrets are only exposed for the
        // duration of this function).
        let dealings = selected
            .iter_pairs()
            .map(|(dealer, log)| {
                let share = self
                    .view
                    .get(dealer)
                    .map(|(_, priv_msg)| priv_msg.share.clone().expose_unwrap())
                    .unwrap_or_else(|| {
                        log.get_reveal(&self.me_pub).map_or_else(
                            || {
                                unreachable!(
                                    "Logs::select didn't check dealer reveal, or we're not a player?"
                                )
                            },
                            |priv_msg| priv_msg.share.clone().expose_unwrap(),
                        )
                    });
                (dealer.clone(), share)
            })
            .try_collect::<Map<_, _>>()
            .expect("Logs::select produces at most one entry per dealer");
        let ObserveInner { output, weights } =
            ObserveInner::<V, S::PublicKey>::reckon::<M>(self.info, selected, strategy)?;
        let private = weights.map_or_else(
            || {
                let mut out = <Scalar as Additive>::zero();
                for s in dealings.values() {
                    out += s;
                }
                out
            },
            |weights| {
                weights
                    .interpolate(&dealings, strategy)
                    .expect("Logs::select ensures that we can recover")
            },
        );
        let share = Share::new(self.index, Private::new(private));
        Ok((output, share))
    }
}

/// The result of dealing shares to players.
pub type DealResult<V, P> = Result<(Output<V, P>, Map<P, Share>), Error>;

/// Simply distribute shares at random, instead of performing a distributed protocol.
pub fn deal<V: Variant, P: Clone + Ord, M: Faults>(
    mut rng: impl CryptoRngCore,
    mode: Mode,
    players: Set<P>,
) -> DealResult<V, P> {
    if players.is_empty() {
        return Err(Error::NumPlayers(0));
    }
    let n = NZU32!(players.len() as u32);
    let t = players.quorum::<M>();
    let private = Poly::new(&mut rng, t - 1);
    let shares: Map<_, _> = players
        .iter()
        .enumerate()
        .map(|(i, p)| {
            let participant = Participant::from_usize(i);
            let eval = private.eval_msm(
                &mode
                    .scalar(n, participant)
                    .expect("player index should be valid"),
                &Sequential,
            );
            let share = Share::new(participant, Private::new(eval));
            (p.clone(), share)
        })
        .try_collect()
        .expect("players are unique");
    let output = Output {
        summary: Summary::random(&mut rng),
        public: Sharing::new(mode, n, Poly::commit(private)),
        dealers: players.clone(),
        players,
        revealed: Set::default(),
    };
    Ok((output, shares))
}

/// Like [`deal`], but without linking the result to specific public keys.
///
/// This can be more convenient for testing, where you don't want to go through
/// the trouble of generating signing keys. The downside is that the result isn't
/// compatible with subsequent DKGs, which need an [`Output`].
pub fn deal_anonymous<V: Variant, M: Faults>(
    rng: impl CryptoRngCore,
    mode: Mode,
    n: NonZeroU32,
) -> (Sharing<V>, Vec<Share>) {
    let players = (0..n.get()).try_collect().unwrap();
    let (output, shares) = deal::<V, _, M>(rng, mode, players).unwrap();
    (output.public().clone(), shares.values().to_vec())
}

#[cfg(any(feature = "arbitrary", test))]
mod test_plan {
    use super::*;
    use crate::{
        bls12381::primitives::{
            ops::{self, threshold},
            variant::Variant,
        },
        ed25519, PublicKey,
    };
    use anyhow::anyhow;
    use bytes::BytesMut;
    use commonware_utils::{Faults, N3f1, TryCollect};
    use core::num::NonZeroI32;
    use rand::{rngs::StdRng, SeedableRng as _};
    use std::collections::BTreeSet;

    /// Apply a mask to some bytes, returning whether or not a modification happened
    fn apply_mask(bytes: &mut BytesMut, mask: &[u8]) -> bool {
        let mut modified = false;
        for (l, &r) in bytes.iter_mut().zip(mask.iter()) {
            modified |= r != 0;
            *l ^= r;
        }
        modified
    }

    #[derive(Clone, Default, Debug)]
    pub struct Masks {
        pub info_summary: Vec<u8>,
        pub dealer: Vec<u8>,
        pub pub_msg: Vec<u8>,
        pub log: Vec<u8>,
    }

    impl Masks {
        fn modifies_player_ack(&self) -> bool {
            self.info_summary.iter().any(|&b| b != 0)
                || self.dealer.iter().any(|&b| b != 0)
                || self.pub_msg.iter().any(|&b| b != 0)
        }

        fn transcript_for_round<V: Variant, P: PublicKey>(
            &self,
            info: &Info<V, P>,
        ) -> anyhow::Result<(bool, Transcript)> {
            let mut summary_bs = info.summary.encode_mut();
            let modified = apply_mask(&mut summary_bs, &self.info_summary);
            let summary = Summary::read(&mut summary_bs)?;
            Ok((modified, Transcript::resume(summary)))
        }

        fn transcript_for_player_ack<V: Variant, P: PublicKey>(
            &self,
            info: &Info<V, P>,
            dealer: &P,
            pub_msg: &DealerPubMsg<V>,
        ) -> anyhow::Result<(bool, Transcript)> {
            let (mut modified, transcript) = self.transcript_for_round(info)?;
            let mut transcript = transcript.fork(SIG_ACK);

            let mut dealer_bs = dealer.encode_mut();
            modified |= apply_mask(&mut dealer_bs, &self.dealer);
            transcript.commit(&mut dealer_bs);

            let mut pub_msg_bs = pub_msg.encode_mut();
            modified |= apply_mask(&mut pub_msg_bs, &self.pub_msg);
            transcript.commit(&mut pub_msg_bs);

            Ok((modified, transcript))
        }

        fn transcript_for_signed_dealer_log<V: Variant, P: PublicKey>(
            &self,
            info: &Info<V, P>,
            log: &DealerLog<V, P>,
        ) -> anyhow::Result<(bool, Transcript)> {
            let (mut modified, transcript) = self.transcript_for_round(info)?;
            let mut transcript = transcript.fork(SIG_LOG);

            let mut log_bs = log.encode_mut();
            modified |= apply_mask(&mut log_bs, &self.log);
            transcript.commit(&mut log_bs);

            Ok((modified, transcript))
        }
    }

    /// A round in the DKG test plan.
    #[derive(Debug, Default)]
    pub struct Round {
        dealers: Vec<u32>,
        players: Vec<u32>,
        crash_resume_players: BTreeSet<(u32, u32)>,
        resume_missing_dealer_msg_fails: BTreeSet<(u32, u32)>,
        finalize_missing_dealer_msg_fails: BTreeSet<u32>,
        no_acks: BTreeSet<(u32, u32)>,
        bad_shares: BTreeSet<(u32, u32)>,
        bad_player_sigs: BTreeMap<(u32, u32), Masks>,
        bad_reveals: BTreeSet<(u32, u32)>,
        bad_dealer_sigs: BTreeMap<u32, Masks>,
        replace_shares: BTreeSet<u32>,
        shift_degrees: BTreeMap<u32, NonZeroI32>,
    }

    impl Round {
        pub fn new(dealers: Vec<u32>, players: Vec<u32>) -> Self {
            Self {
                dealers,
                players,
                ..Default::default()
            }
        }

        pub fn no_ack(mut self, dealer: u32, player: u32) -> Self {
            self.no_acks.insert((dealer, player));
            self
        }

        pub fn crash_resume_player(mut self, after_dealer: u32, player: u32) -> Self {
            self.crash_resume_players.insert((after_dealer, player));
            self
        }

        pub fn resume_missing_dealer_msg_fails(
            mut self,
            after_dealer: u32,
            missing_dealer: u32,
        ) -> Self {
            self.resume_missing_dealer_msg_fails
                .insert((after_dealer, missing_dealer));
            self
        }

        pub fn finalize_missing_dealer_msg_fails(mut self, player: u32) -> Self {
            self.finalize_missing_dealer_msg_fails.insert(player);
            self
        }

        pub fn bad_share(mut self, dealer: u32, player: u32) -> Self {
            self.bad_shares.insert((dealer, player));
            self
        }

        pub fn bad_player_sig(mut self, dealer: u32, player: u32, masks: Masks) -> Self {
            self.bad_player_sigs.insert((dealer, player), masks);
            self
        }

        pub fn bad_reveal(mut self, dealer: u32, player: u32) -> Self {
            self.bad_reveals.insert((dealer, player));
            self
        }

        pub fn bad_dealer_sig(mut self, dealer: u32, masks: Masks) -> Self {
            self.bad_dealer_sigs.insert(dealer, masks);
            self
        }

        pub fn replace_share(mut self, dealer: u32) -> Self {
            self.replace_shares.insert(dealer);
            self
        }

        pub fn shift_degree(mut self, dealer: u32, shift: NonZeroI32) -> Self {
            self.shift_degrees.insert(dealer, shift);
            self
        }

        /// Validate that this round is well-formed given the number of participants
        /// and the previous successful round's players.
        pub fn validate(
            &self,
            num_participants: u32,
            previous_players: Option<&[u32]>,
        ) -> anyhow::Result<()> {
            if self.dealers.is_empty() {
                return Err(anyhow!("dealers is empty"));
            }
            if self.players.is_empty() {
                return Err(anyhow!("players is empty"));
            }
            // Check dealer/player ranges
            for &d in &self.dealers {
                if d >= num_participants {
                    return Err(anyhow!("dealer {d} out of range [1, {num_participants}]"));
                }
            }
            for &p in &self.players {
                if p >= num_participants {
                    return Err(anyhow!("player {p} out of range [1, {num_participants}]"));
                }
            }
            // Crash/resume checkpoints must reference in-round dealers/players.
            for &(after_dealer, player) in &self.crash_resume_players {
                if !self.dealers.contains(&after_dealer) {
                    return Err(anyhow!("crash_resume dealer {after_dealer} not in round"));
                }
                if !self.players.contains(&player) {
                    return Err(anyhow!("crash_resume player {player} not in round"));
                }
            }
            let dealer_positions: BTreeMap<u32, usize> = self
                .dealers
                .iter()
                .enumerate()
                .map(|(idx, &dealer)| (dealer, idx))
                .collect();
            let previous_successful_round = previous_players.is_some();
            for &(after_dealer, missing_dealer) in &self.resume_missing_dealer_msg_fails {
                if !self.dealers.contains(&after_dealer) {
                    return Err(anyhow!("resume_missing dealer {after_dealer} not in round"));
                }
                if !self.dealers.contains(&missing_dealer) {
                    return Err(anyhow!(
                        "resume_missing missing_dealer {missing_dealer} not in round"
                    ));
                }
                let after_pos = dealer_positions[&after_dealer];
                let missing_pos = dealer_positions[&missing_dealer];
                if missing_pos > after_pos {
                    return Err(anyhow!(
                        "resume_missing missing_dealer {missing_dealer} appears after {after_dealer}"
                    ));
                }
                if self.bad(previous_successful_round, missing_dealer) {
                    return Err(anyhow!(
                        "resume_missing_dealer_msg_fails requires dealer {missing_dealer} to be good"
                    ));
                }
                let any_valid_ack = self.players.iter().any(|&player| {
                    let ack_corrupted = self.no_acks.contains(&(missing_dealer, player))
                        || self.bad_shares.contains(&(missing_dealer, player))
                        || self
                            .bad_player_sigs
                            .get(&(missing_dealer, player))
                            .is_some_and(Masks::modifies_player_ack);
                    !ack_corrupted
                });
                if !any_valid_ack {
                    return Err(anyhow!(
                        "resume_missing_dealer_msg_fails requires dealer {missing_dealer} to ack at least one player"
                    ));
                }
            }
            for &player in &self.finalize_missing_dealer_msg_fails {
                if !self.players.contains(&player) {
                    return Err(anyhow!("finalize_missing player {player} not in round"));
                }
            }

            // If there's a previous round, check dealer constraints
            if let Some(prev_players) = previous_players {
                // Every dealer must have been a player in the previous round
                for &d in &self.dealers {
                    if !prev_players.contains(&d) {
                        return Err(anyhow!("dealer {d} was not a player in previous round"));
                    }
                }
                // Must have >= quorum(prev_players) dealers
                let required = N3f1::quorum(prev_players.len());
                if (self.dealers.len() as u32) < required {
                    return Err(anyhow!(
                        "not enough dealers: have {}, need {} (quorum of {} previous players)",
                        self.dealers.len(),
                        required,
                        prev_players.len()
                    ));
                }
            }

            Ok(())
        }

        fn bad(&self, previous_successful_round: bool, dealer: u32) -> bool {
            if self.replace_shares.contains(&dealer) && previous_successful_round {
                return true;
            }
            if let Some(shift) = self.shift_degrees.get(&dealer) {
                let degree = N3f1::quorum(self.players.len()) as i32 - 1;
                // We shift the degree, but saturate at 0, so it's possible
                // that the shift isn't actually doing anything.
                //
                // This is effectively the same as checking degree == 0 && shift < 0,
                // but matches what ends up happening a bit better.
                if (degree + shift.get()).max(0) != degree {
                    return true;
                }
            }
            if self.bad_reveals.iter().any(|&(d, _)| d == dealer) {
                return true;
            }
            let revealed_players = self
                .bad_shares
                .iter()
                .copied()
                .chain(self.no_acks.iter().copied())
                .filter_map(|(d, p)| if d == dealer { Some(p) } else { None })
                .collect::<BTreeSet<_>>();
            revealed_players.len() as u32 > N3f1::max_faults(self.players.len())
        }

        /// Determine if this round is expected to fail.
        fn expect_failure(&self, previous_successful_round: Option<u32>) -> bool {
            let good_dealer_count = self
                .dealers
                .iter()
                .filter(|&&d| !self.bad(previous_successful_round.is_some(), d))
                .count();
            let required = previous_successful_round
                .map(N3f1::quorum)
                .unwrap_or_default()
                .max(N3f1::quorum(self.dealers.len())) as usize;
            good_dealer_count < required
        }
    }

    /// A DKG test plan consisting of multiple rounds.
    #[derive(Debug)]
    pub struct Plan {
        num_participants: NonZeroU32,
        rounds: Vec<Round>,
    }

    impl Plan {
        pub const fn new(num_participants: NonZeroU32) -> Self {
            Self {
                num_participants,
                rounds: Vec::new(),
            }
        }

        pub fn with(mut self, round: Round) -> Self {
            self.rounds.push(round);
            self
        }

        /// Validate the entire plan.
        pub(crate) fn validate(&self) -> anyhow::Result<()> {
            let mut last_successful_players: Option<Vec<u32>> = None;

            for round in &self.rounds {
                round.validate(
                    self.num_participants.get(),
                    last_successful_players.as_deref(),
                )?;

                // If this round is expected to succeed, update last_successful_players
                if !round.expect_failure(last_successful_players.as_ref().map(|x| x.len() as u32)) {
                    last_successful_players = Some(round.players.clone());
                }
            }
            Ok(())
        }

        /// Run the test plan with a given seed.
        pub fn run<V: Variant>(self, seed: u64) -> anyhow::Result<()> {
            self.validate()?;

            let mut rng = StdRng::seed_from_u64(seed);

            // Generate keys for all participants (1-indexed to num_participants)
            let keys = (0..self.num_participants.get())
                .map(|_| ed25519::PrivateKey::random(&mut rng))
                .collect::<Vec<_>>();

            // Precompute mapping from public key to key index to avoid confusion
            // between key indices and positions in sorted Sets.
            let pk_to_key_idx: BTreeMap<ed25519::PublicKey, u32> = keys
                .iter()
                .enumerate()
                .map(|(i, k)| (k.public_key(), i as u32))
                .collect();

            // The max_read_size needs to account for shifted polynomial degrees.
            // Find the maximum positive shift across all rounds.
            let max_shift = self
                .rounds
                .iter()
                .flat_map(|r| r.shift_degrees.values())
                .map(|s| s.get())
                .max()
                .unwrap_or(0)
                .max(0) as u32;
            let max_read_size =
                NonZeroU32::new(self.num_participants.get() + max_shift).expect("non-zero");

            let mut previous_output: Option<Output<V, ed25519::PublicKey>> = None;
            let mut shares: BTreeMap<ed25519::PublicKey, Share> = BTreeMap::new();
            let mut threshold_public_key: Option<V::Public> = None;

            for (i_round, round) in self.rounds.into_iter().enumerate() {
                let previous_successful_round =
                    previous_output.as_ref().map(|o| o.players.len() as u32);

                let dealer_set = round
                    .dealers
                    .iter()
                    .map(|&i| keys[i as usize].public_key())
                    .try_collect::<Set<_>>()
                    .unwrap();
                let player_set: Set<ed25519::PublicKey> = round
                    .players
                    .iter()
                    .map(|&i| keys[i as usize].public_key())
                    .try_collect()
                    .unwrap();

                // Create round info
                let info = Info::new::<N3f1>(
                    b"_COMMONWARE_CRYPTOGRAPHY_BLS12381_DKG_TEST",
                    i_round as u64,
                    previous_output.clone(),
                    Default::default(),
                    dealer_set.clone(),
                    player_set.clone(),
                )?;

                let mut players: Map<_, _> = round
                    .players
                    .iter()
                    .map(|&i| {
                        let sk = keys[i as usize].clone();
                        let pk = sk.public_key();
                        let player = Player::new(info.clone(), sk)?;
                        Ok((pk, player))
                    })
                    .collect::<anyhow::Result<Vec<_>>>()?
                    .try_into()
                    .unwrap();
                let mut acked_dealings: BTreeMap<
                    ed25519::PublicKey,
                    Vec<(ed25519::PublicKey, DealerPubMsg<V>, DealerPrivMsg)>,
                > = player_set
                    .iter()
                    .cloned()
                    .map(|pk| (pk, Vec::new()))
                    .collect();
                let mut crash_resume_by_dealer: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
                for &(after_dealer, player) in &round.crash_resume_players {
                    crash_resume_by_dealer
                        .entry(after_dealer)
                        .or_default()
                        .push(player);
                }
                let mut resume_missing_msg_by_dealer: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
                for &(after_dealer, missing_dealer) in &round.resume_missing_dealer_msg_fails {
                    resume_missing_msg_by_dealer
                        .entry(after_dealer)
                        .or_default()
                        .push(missing_dealer);
                }

                // Run dealer protocol
                let mut dealer_logs = BTreeMap::new();
                for &i_dealer in &round.dealers {
                    let sk = keys[i_dealer as usize].clone();
                    let pk = sk.public_key();
                    let share = match (shares.get(&pk), round.replace_shares.contains(&i_dealer)) {
                        (None, _) => None,
                        (Some(s), false) => Some(s.clone()),
                        (Some(_), true) => Some(Share::new(
                            Participant::new(i_dealer),
                            Private::random(&mut rng),
                        )),
                    };

                    // Start dealer (with potential modifications)
                    let (mut dealer, pub_msg, mut priv_msgs) =
                        if let Some(shift) = round.shift_degrees.get(&i_dealer) {
                            // Create dealer with shifted degree
                            let degree = u32::try_from(info.degree::<N3f1>() as i32 + shift.get())
                                .unwrap_or_default();

                            // Manually create the dealer with adjusted polynomial
                            let share = info
                                .unwrap_or_random_share(
                                    &mut rng,
                                    share.map(|s| s.private.expose_unwrap()),
                                )
                                .expect("Failed to generate dealer share");

                            let my_poly = Poly::new_with_constant(&mut rng, degree, share);
                            let priv_msgs = info
                                .players
                                .iter()
                                .map(|pk| {
                                    (
                                        pk.clone(),
                                        DealerPrivMsg::new(my_poly.eval_msm(
                                            &info.player_scalar(pk).expect("player should exist"),
                                            &Sequential,
                                        )),
                                    )
                                })
                                .collect::<Vec<_>>();
                            let results: Map<_, _> = priv_msgs
                                .iter()
                                .map(|(pk, pm)| (pk.clone(), AckOrReveal::Reveal(pm.clone())))
                                .try_collect()
                                .unwrap();
                            let commitment = Poly::commit(my_poly);
                            let pub_msg = DealerPubMsg { commitment };
                            let transcript = {
                                let t = transcript_for_round(&info);
                                transcript_for_ack(&t, &pk, &pub_msg)
                            };
                            let dealer = Dealer {
                                me: sk.clone(),
                                info: info.clone(),
                                pub_msg: pub_msg.clone(),
                                results,
                                transcript,
                            };
                            (dealer, pub_msg, priv_msgs)
                        } else {
                            Dealer::start::<N3f1>(&mut rng, info.clone(), sk.clone(), share)?
                        };

                    // Apply BadShare perturbations
                    for (player, priv_msg) in &mut priv_msgs {
                        let player_key_idx = pk_to_key_idx[player];
                        if round.bad_shares.contains(&(i_dealer, player_key_idx)) {
                            *priv_msg = DealerPrivMsg::new(Scalar::random(&mut rng));
                        }
                    }
                    assert_eq!(priv_msgs.len(), players.len());

                    // Process player acks
                    let mut num_reveals = players.len() as u32;
                    for (player_pk, priv_msg) in priv_msgs {
                        // Check priv msg encoding.
                        assert_eq!(priv_msg, ReadExt::read(&mut priv_msg.encode())?);

                        let i_player = players
                            .index(&player_pk)
                            .ok_or_else(|| anyhow!("unknown player: {:?}", &player_pk))?;
                        let player_key_idx = pk_to_key_idx[&player_pk];
                        let player = &mut players.values_mut()[usize::from(i_player)];
                        let persisted = priv_msg.clone();

                        let ack =
                            player.dealer_message::<N3f1>(pk.clone(), pub_msg.clone(), priv_msg);
                        assert_eq!(ack, ReadExt::read(&mut ack.encode())?);
                        if let Some(ack) = ack {
                            acked_dealings
                                .get_mut(&player_pk)
                                .expect("player should be present")
                                .push((pk.clone(), pub_msg.clone(), persisted));
                            let masks = round
                                .bad_player_sigs
                                .get(&(i_dealer, player_key_idx))
                                .cloned()
                                .unwrap_or_default();
                            let (modified, transcript) =
                                masks.transcript_for_player_ack(&info, &pk, &pub_msg)?;
                            assert_eq!(transcript.verify(&player_pk, &ack.sig), !modified);

                            // Skip receiving ack if NoAck perturbation
                            if !round.no_acks.contains(&(i_dealer, player_key_idx)) {
                                dealer.receive_player_ack(player_pk, ack)?;
                                num_reveals -= 1;
                            }
                        } else {
                            assert!(
                                round.bad_shares.contains(&(i_dealer, player_key_idx))
                                    || round.bad(previous_successful_round.is_some(), i_dealer)
                            );
                        }
                    }

                    // Finalize dealer
                    let signed_log = dealer.finalize::<N3f1>();
                    assert_eq!(
                        signed_log,
                        Read::read_cfg(&mut signed_log.encode(), &max_read_size)?
                    );

                    // Check for BadDealerSig
                    let masks = round
                        .bad_dealer_sigs
                        .get(&i_dealer)
                        .cloned()
                        .unwrap_or_default();
                    let (modified, transcript) =
                        masks.transcript_for_signed_dealer_log(&info, &signed_log.log)?;
                    assert_eq!(transcript.verify(&pk, &signed_log.sig), !modified);
                    let (found_pk, mut log) = signed_log
                        .check(&info)
                        .ok_or_else(|| anyhow!("signed log should verify"))?;
                    assert_eq!(pk, found_pk);
                    // Apply BadReveal perturbations
                    match &mut log.results {
                        DealerResult::TooManyReveals => {
                            assert!(num_reveals > info.max_reveals::<N3f1>());
                        }
                        DealerResult::Ok(results) => {
                            assert_eq!(results.len(), players.len());
                            for &i_player in &round.players {
                                if !round.bad_reveals.contains(&(i_dealer, i_player)) {
                                    continue;
                                }
                                let player_pk = keys[i_player as usize].public_key();
                                *results
                                    .get_value_mut(&player_pk)
                                    .ok_or_else(|| anyhow!("unknown player: {:?}", &player_pk))? =
                                    AckOrReveal::Reveal(DealerPrivMsg::new(Scalar::random(
                                        &mut rng,
                                    )));
                            }
                        }
                    }
                    dealer_logs.insert(pk, log);

                    // For selected checkpoints, omit a good dealer's private message and
                    // ensure resume reports corruption. Do not mutate player state.
                    for &missing_dealer in resume_missing_msg_by_dealer
                        .get(&i_dealer)
                        .into_iter()
                        .flatten()
                    {
                        assert!(
                            !round.bad(previous_successful_round.is_some(), missing_dealer),
                            "resume_missing_dealer_msg_fails requires dealer {missing_dealer} to be good"
                        );
                        let missing_pk = keys[missing_dealer as usize].public_key();
                        let missing_log = dealer_logs
                            .get(&missing_pk)
                            .unwrap_or_else(|| panic!("missing dealer log for {:?}", &missing_pk));
                        for &i_player in &round.players {
                            let player_pk = keys[i_player as usize].public_key();
                            let was_acked = missing_log.get_ack(&player_pk).is_some();

                            let replay = acked_dealings
                                .get(&player_pk)
                                .cloned()
                                .expect("player should be present");
                            let replay_without = replay
                                .into_iter()
                                .filter(|(dealer, _, _)| dealer != &missing_pk);
                            let player_sk = keys[i_player as usize].clone();
                            let resumed = Player::resume::<N3f1>(
                                info.clone(),
                                player_sk,
                                &dealer_logs,
                                replay_without,
                            );
                            if was_acked {
                                assert!(
                                    matches!(resumed, Err(Error::MissingPlayerDealing)),
                                    "resume without dealer {missing_dealer} message should report MissingPlayerDealing for player {i_player}"
                                );
                            } else {
                                assert!(
                                    resumed.is_ok(),
                                    "resume without dealer {missing_dealer} message should succeed for unacked player {i_player}"
                                );
                            }
                        }
                    }

                    // Crash/resume selected players after this dealer has finalized.
                    for &i_player in crash_resume_by_dealer.get(&i_dealer).into_iter().flatten() {
                        let player_pk = keys[i_player as usize].public_key();
                        let player_sk = keys[i_player as usize].clone();
                        let replay = acked_dealings
                            .get(&player_pk)
                            .cloned()
                            .expect("player should be present");
                        let (resumed, _) =
                            Player::resume::<N3f1>(info.clone(), player_sk, &dealer_logs, replay)
                                .expect("player resume perturbation should succeed");
                        *players
                            .get_value_mut(&player_pk)
                            .expect("player should be present") = resumed;
                    }
                }

                // Make sure that bad dealers are not selected.
                let mut logs = Logs::<_, _, N3f1>::new(info.clone());
                for (dealer, log) in &dealer_logs {
                    logs.record(dealer.clone(), log.clone());
                }
                let selection = logs.clone().select::<ed25519::Batch>(&mut rng, &Sequential);
                if let Ok(ref selection) = selection {
                    let good_pks = selection
                        .1
                        .iter_pairs()
                        .map(|(pk, _)| pk.clone())
                        .collect::<BTreeSet<_>>();
                    for &i_dealer in &round.dealers {
                        if round.bad(previous_successful_round.is_some(), i_dealer) {
                            assert!(!good_pks.contains(&keys[i_dealer as usize].public_key()));
                        }
                    }
                }
                // Run observer
                let observe_result =
                    observe::<_, _, N3f1, ed25519::Batch>(&mut rng, logs.clone(), &Sequential);
                if round.expect_failure(previous_successful_round) {
                    assert!(
                        observe_result.is_err(),
                        "Round {i_round} should have failed but succeeded",
                    );
                    continue;
                }
                let observer_output = observe_result?;
                let selection = selection.expect("select should succeed if observe succeeded");

                // Compute expected dealers: good dealers up to required_commitments
                // The select function iterates dealer_logs (BTreeMap) in public key order
                let required_commitments = info.required_commitments::<N3f1>() as usize;
                let expected_dealers: Set<ed25519::PublicKey> = dealer_set
                    .iter()
                    .filter(|pk| {
                        let i = keys.iter().position(|k| &k.public_key() == *pk).unwrap() as u32;
                        !round.bad(previous_successful_round.is_some(), i)
                    })
                    .take(required_commitments)
                    .cloned()
                    .try_collect()
                    .expect("dealers are unique");
                let expected_dealer_indices: BTreeSet<u32> = expected_dealers
                    .iter()
                    .filter_map(|pk| {
                        keys.iter()
                            .position(|k| &k.public_key() == pk)
                            .map(|i| i as u32)
                    })
                    .collect();
                assert_eq!(
                    observer_output.dealers(),
                    &expected_dealers,
                    "Output dealers should match expected good dealers"
                );

                // Map selected dealers to their key indices (for later use)
                let selected_dealers: BTreeSet<u32> = selection
                    .1
                    .keys()
                    .iter()
                    .filter_map(|pk| {
                        keys.iter()
                            .position(|k| &k.public_key() == pk)
                            .map(|i| i as u32)
                    })
                    .collect();
                assert_eq!(
                    selected_dealers, expected_dealer_indices,
                    "Selection should match expected dealers"
                );
                let selected_players: Set<ed25519::PublicKey> = round
                    .players
                    .iter()
                    .map(|&i| keys[i as usize].public_key())
                    .try_collect()
                    .expect("players are unique");
                for &i_player in &round.finalize_missing_dealer_msg_fails {
                    let player_pk = keys[i_player as usize].public_key();
                    let player_sk = keys[i_player as usize].clone();
                    let mut tested = 0u32;
                    for &dealer_idx in &selected_dealers {
                        if round.bad(previous_successful_round.is_some(), dealer_idx) {
                            continue;
                        }
                        let dealer_pk = keys[dealer_idx as usize].public_key();
                        let dealer_log = dealer_logs
                            .get(&dealer_pk)
                            .unwrap_or_else(|| panic!("missing dealer log for {:?}", &dealer_pk));
                        if dealer_log.get_ack(&player_pk).is_none() {
                            continue;
                        }
                        let replay = acked_dealings
                            .get(&player_pk)
                            .cloned()
                            .expect("player should be present");
                        let replay_without = replay
                            .into_iter()
                            .filter(|(dealer, _, _)| dealer != &dealer_pk);
                        let resume_logs: BTreeMap<_, _> = dealer_logs
                            .iter()
                            .filter(|(dealer, _)| *dealer != &dealer_pk)
                            .map(|(dealer, log)| (dealer.clone(), log.clone()))
                            .collect();
                        let (resumed, _) = Player::resume::<N3f1>(
                            info.clone(),
                            player_sk.clone(),
                            &resume_logs,
                            replay_without,
                        )
                        .expect("resume should succeed with stale logs");
                        let finalize_res = resumed.finalize::<N3f1, ed25519::Batch>(
                            &mut rng,
                            logs.clone(),
                            &Sequential,
                        );
                        assert!(
                            matches!(finalize_res, Err(Error::MissingPlayerDealing)),
                            "finalize without dealer {dealer_idx} message should return MissingPlayerDealing for player {i_player}"
                        );
                        tested += 1;
                    }
                    assert!(
                        tested > 0,
                        "finalize_missing_dealer_msg_fails for player {i_player} tested no dealers"
                    );
                }

                // Compute expected reveals
                //
                // Note: We use union of no_acks and bad_shares since each (dealer, player) pair
                // results in at most one reveal in the protocol, regardless of whether the player
                // didn't ack, got a bad share, or both.
                let mut expected_reveals: BTreeMap<ed25519::PublicKey, u32> = BTreeMap::new();
                for &(dealer_idx, player_key_idx) in round.no_acks.union(&round.bad_shares) {
                    if !selected_dealers.contains(&dealer_idx) {
                        continue;
                    }
                    let pk = keys[player_key_idx as usize].public_key();
                    if selected_players.position(&pk).is_none() {
                        continue;
                    }
                    *expected_reveals.entry(pk).or_insert(0) += 1;
                }

                // Verify each player's revealed status
                let max_faults = selected_players.max_faults::<N3f1>();
                for player in player_set.iter() {
                    let expected = expected_reveals.get(player).copied().unwrap_or(0) > max_faults;
                    let actual = observer_output.revealed().position(player).is_some();
                    assert_eq!(expected, actual, "Unexpected outcome for player {player:?} (expected={expected}, actual={actual})");
                }

                // Finalize each player
                for (player_pk, player) in players.into_iter() {
                    let (player_output, share) = player
                        .finalize::<N3f1, ed25519::Batch>(&mut rng, logs.clone(), &Sequential)
                        .expect("Player finalize should succeed");

                    assert_eq!(
                        player_output, observer_output,
                        "Player output should match observer output"
                    );

                    // Verify share matches public polynomial
                    let expected_public = observer_output
                        .public
                        .partial_public(share.index)
                        .expect("share index should be valid");
                    let actual_public = share.public::<V>();
                    assert_eq!(
                        expected_public, actual_public,
                        "Share should match public polynomial"
                    );

                    shares.insert(player_pk.clone(), share);
                }

                // Initialize or verify threshold public key
                let current_public = *observer_output.public().public();
                match threshold_public_key {
                    None => threshold_public_key = Some(current_public),
                    Some(tpk) => {
                        assert_eq!(
                            tpk, current_public,
                            "Public key should remain constant across reshares"
                        );
                    }
                }

                // Generate and verify threshold signature
                let test_message = format!("test message round {i_round}").into_bytes();
                let namespace = b"test";

                let mut partial_sigs = Vec::new();
                for &i_player in &round.players {
                    let share = &shares[&keys[i_player as usize].public_key()];
                    let partial_sig = threshold::sign_message::<V>(share, namespace, &test_message);

                    threshold::verify_message::<V>(
                        &observer_output.public,
                        namespace,
                        &test_message,
                        &partial_sig,
                    )
                    .expect("Partial signature verification should succeed");

                    partial_sigs.push(partial_sig);
                }

                let threshold = observer_output.quorum::<N3f1>();
                let threshold_sig = threshold::recover::<V, _, N3f1>(
                    &observer_output.public,
                    &partial_sigs[0..threshold as usize],
                    &Sequential,
                )
                .expect("Should recover threshold signature");

                // Verify against the saved public key
                ops::verify_message::<V>(
                    threshold_public_key.as_ref().unwrap(),
                    namespace,
                    &test_message,
                    &threshold_sig,
                )
                .expect("Threshold signature verification should succeed");

                // Update state for next round
                previous_output = Some(observer_output);
            }
            Ok(())
        }
    }

    #[cfg(feature = "arbitrary")]
    mod impl_arbitrary {
        use super::*;
        use arbitrary::{Arbitrary, Unstructured};
        use core::ops::ControlFlow;

        const MAX_NUM_PARTICIPANTS: u32 = 20;
        const MAX_ROUNDS: u32 = 10;

        fn arbitrary_masks<'a>(u: &mut Unstructured<'a>) -> arbitrary::Result<Masks> {
            Ok(Masks {
                info_summary: Arbitrary::arbitrary(u)?,
                dealer: Arbitrary::arbitrary(u)?,
                pub_msg: Arbitrary::arbitrary(u)?,
                log: Arbitrary::arbitrary(u)?,
            })
        }

        /// Pick at most `num` elements at random from `data`, returning them.
        ///
        /// This needs mutable access to perform a shuffle.
        ///
        fn pick<'a, T>(
            u: &mut Unstructured<'a>,
            num: usize,
            mut data: Vec<T>,
        ) -> arbitrary::Result<Vec<T>> {
            let len = data.len();
            let num = num.min(len);
            // Invariant: 0..start is a random subset of data.
            for start in 0..num {
                data.swap(start, u.int_in_range(start..=len - 1)?);
            }
            data.truncate(num);
            Ok(data)
        }

        fn arbitrary_round<'a>(
            u: &mut Unstructured<'a>,
            num_participants: u32,
            last_successful_players: Option<&Set<u32>>,
        ) -> arbitrary::Result<Round> {
            let dealers = if let Some(players) = last_successful_players {
                let to_pick = u.int_in_range(players.quorum::<N3f1>() as usize..=players.len())?;
                pick(u, to_pick, players.into_iter().copied().collect())?
            } else {
                let to_pick = u.int_in_range(1..=num_participants as usize)?;
                pick(u, to_pick, (0..num_participants).collect())?
            };
            let players = {
                let to_pick = u.int_in_range(1..=num_participants as usize)?;
                pick(u, to_pick, (0..num_participants).collect())?
            };
            let pairs = dealers
                .iter()
                .flat_map(|d| players.iter().map(|p| (*d, *p)))
                .collect::<Vec<_>>();
            let pick_pair_set = |u: &mut Unstructured<'a>| {
                let num = u.int_in_range(0..=pairs.len())?;
                if num == 0 {
                    return Ok(BTreeSet::new());
                }
                Ok(pick(u, num, pairs.clone())?.into_iter().collect())
            };
            let pick_dealer_set = |u: &mut Unstructured<'a>| {
                let num = u.int_in_range(0..=dealers.len())?;
                if num == 0 {
                    return Ok(BTreeSet::new());
                }
                Ok(pick(u, num, dealers.clone())?.into_iter().collect())
            };
            let round = Round {
                crash_resume_players: BTreeSet::new(),
                resume_missing_dealer_msg_fails: BTreeSet::new(),
                finalize_missing_dealer_msg_fails: BTreeSet::new(),
                no_acks: pick_pair_set(u)?,
                bad_shares: pick_pair_set(u)?,
                bad_player_sigs: {
                    let indices = pick_pair_set(u)?;
                    indices
                        .into_iter()
                        .map(|k| Ok((k, arbitrary_masks(u)?)))
                        .collect::<arbitrary::Result<_>>()?
                },
                bad_reveals: pick_pair_set(u)?,
                bad_dealer_sigs: {
                    let indices = pick_dealer_set(u)?;
                    indices
                        .into_iter()
                        .map(|k| Ok((k, arbitrary_masks(u)?)))
                        .collect::<arbitrary::Result<_>>()?
                },
                replace_shares: pick_dealer_set(u)?,
                shift_degrees: {
                    let indices = pick_dealer_set(u)?;
                    indices
                        .into_iter()
                        .map(|k| {
                            let expected = N3f1::quorum(players.len()) as i32 - 1;
                            let shift = u.int_in_range(1..=expected.max(1))?;
                            let shift = if bool::arbitrary(u)? { -shift } else { shift };
                            Ok((k, NonZeroI32::new(shift).expect("checked to not be zero")))
                        })
                        .collect::<arbitrary::Result<_>>()?
                },
                dealers,
                players,
            };
            Ok(round)
        }

        impl<'a> Arbitrary<'a> for Plan {
            fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
                let num_participants = u.int_in_range(1..=MAX_NUM_PARTICIPANTS)?;
                let mut rounds = Vec::new();
                let mut last_successful_players: Option<Set<u32>> = None;
                u.arbitrary_loop(None, Some(MAX_ROUNDS), |u| {
                    let round =
                        arbitrary_round(u, num_participants, last_successful_players.as_ref())?;
                    if !round
                        .expect_failure(last_successful_players.as_ref().map(|x| x.len() as u32))
                    {
                        last_successful_players =
                            Some(round.players.iter().copied().try_collect().unwrap());
                    }
                    rounds.push(round);
                    Ok(ControlFlow::Continue(()))
                })?;
                let plan = Self {
                    num_participants: NZU32!(num_participants),
                    rounds,
                };
                plan.validate()
                    .map_err(|_| arbitrary::Error::IncorrectFormat)?;
                Ok(plan)
            }
        }
    }
}

#[cfg(feature = "arbitrary")]
pub use test_plan::Plan as FuzzPlan;

#[cfg(test)]
mod test {
    use super::{test_plan::*, *};
    use crate::{bls12381::primitives::variant::MinPk, ed25519};
    use anyhow::anyhow;
    use arbitrary::{Arbitrary, Unstructured};
    use commonware_invariants::minifuzz;
    use commonware_math::algebra::Random;
    use commonware_utils::{test_rng, test_rng_seeded, Faults, N3f1};
    use core::num::NonZeroI32;

    const PRE_VERIFY_DEALERS: usize = 8;
    type PreVerifyLog = DealerLog<MinPk, ed25519::PublicKey>;
    type PreVerifyLogs = Logs<MinPk, ed25519::PublicKey, QuorumTwo>;

    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    struct QuorumTwo;

    impl Faults for QuorumTwo {
        fn max_faults(n: impl num_traits::ToPrimitive) -> u32 {
            let n = n
                .to_u32()
                .expect("n must be a non-negative integer that fits in u32");
            assert!(n >= 2, "n must be at least 2");
            n - 2
        }
    }

    struct PreVerifyDealer {
        key: ed25519::PublicKey,
        valid: PreVerifyLog,
        invalid: PreVerifyLog,
    }

    struct PreVerifyFixture {
        info: Info<MinPk, ed25519::PublicKey>,
        wrong_info: Info<MinPk, ed25519::PublicKey>,
        dealers: Vec<PreVerifyDealer>,
    }

    impl PreVerifyFixture {
        fn new() -> Self {
            fn pre_verify_test_keys() -> Vec<ed25519::PrivateKey> {
                (0..PRE_VERIFY_DEALERS as u64)
                    .map(ed25519::PrivateKey::from_seed)
                    .collect()
            }

            fn pre_verify_test_info(
                keys: &[ed25519::PrivateKey],
                round: u64,
            ) -> Info<MinPk, ed25519::PublicKey> {
                let dealers: Set<_> = keys
                    .iter()
                    .map(|sk| sk.public_key())
                    .try_collect()
                    .expect("dealers must be unique");
                Info::<MinPk, _>::new::<QuorumTwo>(
                    b"_COMMONWARE_CRYPTOGRAPHY_BLS12381_DKG_TEST",
                    round,
                    None,
                    Default::default(),
                    dealers.clone(),
                    dealers,
                )
                .expect("info must be valid")
            }

            fn generate_dealer_log(
                info: &Info<MinPk, ed25519::PublicKey>,
                keys: &[ed25519::PrivateKey],
                dealer_index: usize,
                seed: u64,
            ) -> DealerLog<MinPk, ed25519::PublicKey> {
                let mut players: BTreeMap<_, _> = keys
                    .iter()
                    .cloned()
                    .map(|sk| {
                        let pk = sk.public_key();
                        (
                            pk,
                            Player::<MinPk, _>::new(info.clone(), sk)
                                .expect("player initialization must succeed"),
                        )
                    })
                    .collect();

                let dealer_sk = keys[dealer_index].clone();
                let dealer_pk = dealer_sk.public_key();
                let mut rng = test_rng_seeded(seed);
                let (mut dealer, pub_msg, priv_msgs) =
                    Dealer::start::<QuorumTwo>(&mut rng, info.clone(), dealer_sk, None)
                        .expect("dealer initialization must succeed");
                for (player_pk, priv_msg) in priv_msgs {
                    let ack = players
                        .get_mut(&player_pk)
                        .expect("player should exist")
                        .dealer_message::<QuorumTwo>(dealer_pk.clone(), pub_msg.clone(), priv_msg)
                        .expect("dealer message must succeed");
                    dealer
                        .receive_player_ack(player_pk, ack)
                        .expect("ack handling must succeed");
                }
                dealer
                    .finalize::<QuorumTwo>()
                    .check(info)
                    .expect("signed dealer log must verify against its own info")
                    .1
            }

            let keys = pre_verify_test_keys();
            let info = pre_verify_test_info(&keys, 0);
            let wrong_info = pre_verify_test_info(&keys, 1);
            let mut logs_by_key: BTreeMap<_, _> = keys
                .iter()
                .enumerate()
                .map(|(dealer_index, sk)| {
                    let key = sk.public_key();
                    let seed = dealer_index as u64;
                    let valid = generate_dealer_log(&info, &keys, dealer_index, seed);
                    let invalid = generate_dealer_log(&wrong_info, &keys, dealer_index, seed);
                    assert_eq!(
                        valid.pub_msg, invalid.pub_msg,
                        "wrong-info log generation should only change transcript-bound signatures"
                    );
                    (key, (valid, invalid))
                })
                .collect();
            let dealers = info
                .dealers
                .iter()
                .cloned()
                .map(|key| {
                    let (valid, invalid) = logs_by_key
                        .remove(&key)
                        .expect("fixture should include every dealer");
                    PreVerifyDealer {
                        key,
                        valid,
                        invalid,
                    }
                })
                .collect();
            Self {
                info,
                wrong_info,
                dealers,
            }
        }

        fn required_commitments(&self) -> usize {
            self.info.required_commitments::<QuorumTwo>() as usize
        }

        fn expected(&self, valid: &[bool]) -> Set<ed25519::PublicKey> {
            assert_eq!(
                valid.len(),
                self.dealers.len(),
                "fixture size should match case"
            );
            self.dealers
                .iter()
                .zip(valid.iter().copied())
                .filter(|(_, is_valid)| *is_valid)
                .take(self.required_commitments())
                .map(|(dealer, _)| dealer.key.clone())
                .try_collect()
                .expect("dealers must be unique")
        }

        fn record(&self, logs: &mut PreVerifyLogs, dealer_index: usize, is_valid: bool) {
            let dealer = &self.dealers[dealer_index];
            let log = if is_valid {
                dealer.valid.clone()
            } else {
                dealer.invalid.clone()
            };
            logs.record(dealer.key.clone(), log);
        }

        fn logs_for(
            &self,
            info: &Info<MinPk, ed25519::PublicKey>,
            valid: &[bool],
        ) -> PreVerifyLogs {
            assert_eq!(
                valid.len(),
                self.dealers.len(),
                "fixture size should match case"
            );
            let mut logs = PreVerifyLogs::new(info.clone());
            for (dealer_index, &is_valid) in valid.iter().enumerate() {
                self.record(&mut logs, dealer_index, is_valid);
            }
            logs
        }
    }

    #[derive(Debug)]
    struct IncrementalPreVerifyCase {
        valid: [bool; PRE_VERIFY_DEALERS],
        batches: Vec<Vec<usize>>,
    }

    impl<'a> Arbitrary<'a> for IncrementalPreVerifyCase {
        fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
            let mut valid = [false; PRE_VERIFY_DEALERS];
            for is_valid in &mut valid {
                *is_valid = u.arbitrary()?;
            }

            let mut order: Vec<_> = (0..valid.len()).collect();
            for index in 0..valid.len() {
                let last = order.len() - 1;
                order.swap(index, u.int_in_range(index..=last)?);
            }

            let mut batches = Vec::new();
            let mut start = 0;
            while start < order.len() {
                let batch_size = u.int_in_range(1..=order.len() - start)?;
                batches.push(order[start..start + batch_size].to_vec());
                start += batch_size;
            }

            Ok(Self { valid, batches })
        }
    }

    impl IncrementalPreVerifyCase {
        fn run(self, fixture: &PreVerifyFixture) -> arbitrary::Result<()> {
            let required_commitments = fixture.required_commitments();
            let expected = fixture.expected(&self.valid);
            let fresh = fixture.logs_for(&fixture.info, &self.valid);

            let mut incremental = PreVerifyLogs::new(fixture.info.clone());
            let mut incremental_rng = test_rng();
            for batch in &self.batches {
                for &dealer_index in batch {
                    fixture.record(&mut incremental, dealer_index, self.valid[dealer_index]);
                }
                incremental.pre_verify::<ed25519::Batch>(&mut incremental_rng, &Sequential);
            }

            let mut fresh_rng = test_rng();
            let fresh_selected = fresh
                .select::<ed25519::Batch>(&mut fresh_rng, &Sequential)
                .map(|(_, selection)| selection.keys().clone());
            let incremental_selected = incremental
                .select::<ed25519::Batch>(&mut incremental_rng, &Sequential)
                .map(|(_, selection)| selection.keys().clone());

            match &fresh_selected {
                Ok(selected) => assert_eq!(
                    selected, &expected,
                    "all-at-once selection disagreed with validity mask: {:?}",
                    self
                ),
                Err(_) => assert!(
                    expected.len() < required_commitments,
                    "all-at-once selection failed despite quorum-sized expected set: {:?}",
                    self
                ),
            }

            match (fresh_selected, incremental_selected) {
                (Err(_), Err(_)) => {}
                (Ok(fresh_selected), Ok(incremental_selected)) => assert_eq!(
                    incremental_selected, fresh_selected,
                    "incremental selection disagreed with all-at-once selection: {:?}",
                    self
                ),
                (Ok(fresh_selected), Err(err)) => panic!(
                    "incremental selection failed with {err:?} but all-at-once selected {fresh_selected:?}: {self:?}"
                ),
                (Err(err), Ok(incremental_selected)) => panic!(
                    "incremental selection returned {incremental_selected:?} but all-at-once failed with {err:?}: {self:?}"
                ),
            }

            Ok(())
        }
    }

    #[test]
    fn incremental_pre_verify_preserves_dealer_order() {
        let fixture = PreVerifyFixture::new();
        minifuzz::test(move |u| u.arbitrary::<IncrementalPreVerifyCase>()?.run(&fixture));
    }

    #[test]
    fn logs_are_bound_to_constructor_info() {
        let fixture = PreVerifyFixture::new();
        let mut logs = fixture.logs_for(&fixture.info, &[false; PRE_VERIFY_DEALERS]);
        let mut wrong_logs = fixture.logs_for(&fixture.wrong_info, &[false; PRE_VERIFY_DEALERS]);
        let mut rng = test_rng();

        logs.pre_verify::<ed25519::Batch>(&mut rng, &Sequential);
        wrong_logs.pre_verify::<ed25519::Batch>(&mut rng, &Sequential);
        assert!(
            wrong_logs
                .select::<ed25519::Batch>(&mut rng, &Sequential)
                .is_ok(),
            "control check: logs should verify when bound to the round they were created for"
        );
        assert!(
            matches!(
                logs.select::<ed25519::Batch>(&mut rng, &Sequential),
                Err(Error::DkgFailed)
            ),
            "logs bound to a different round must reject these transcript-bound signatures"
        );
    }

    #[test]
    fn finalize_rejects_logs_bound_to_different_round() {
        let fixture = PreVerifyFixture::new();
        let player =
            Player::<MinPk, _>::new(fixture.info.clone(), ed25519::PrivateKey::from_seed(0))
                .expect("player initialization must succeed");
        let wrong_logs = fixture.logs_for(&fixture.wrong_info, &[false; PRE_VERIFY_DEALERS]);

        let result =
            player.finalize::<QuorumTwo, ed25519::Batch>(&mut test_rng(), wrong_logs, &Sequential);

        assert!(
            matches!(result, Err(Error::MismatchedLogs)),
            "finalize should reject logs bound to a different round"
        );
    }

    #[test]
    fn single_round() -> anyhow::Result<()> {
        Plan::new(NZU32!(4))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]))
            .run::<MinPk>(0)
    }

    #[test]
    fn multiple_rounds() -> anyhow::Result<()> {
        Plan::new(NZU32!(4))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]))
            .run::<MinPk>(0)
    }

    #[test]
    fn player_crash_resume_after_dealer() -> anyhow::Result<()> {
        Plan::new(NZU32!(4))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]).crash_resume_player(1, 2))
            .run::<MinPk>(0)
    }

    #[test]
    fn resume_missing_good_dealer_message_fails_after_checkpoint() -> anyhow::Result<()> {
        Plan::new(NZU32!(4))
            .with(
                Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3])
                    .resume_missing_dealer_msg_fails(2, 1),
            )
            .run::<MinPk>(0)
    }

    #[test]
    fn resume_missing_good_dealer_message_skips_unacked_players() -> anyhow::Result<()> {
        Plan::new(NZU32!(4))
            .with(
                Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3])
                    .no_ack(1, 0)
                    .resume_missing_dealer_msg_fails(2, 1),
            )
            .run::<MinPk>(0)
    }

    #[test]
    fn finalize_fails_after_resume_without_good_dealer_message() -> anyhow::Result<()> {
        Plan::new(NZU32!(4))
            .with(
                Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3])
                    .no_ack(0, 1)
                    .finalize_missing_dealer_msg_fails(0),
            )
            .run::<MinPk>(0)
    }

    #[test]
    fn invalid_checkpoint_configs_fail_validation() {
        assert!(Plan::new(NZU32!(4))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]).crash_resume_player(4, 2))
            .validate()
            .is_err());
        assert!(Plan::new(NZU32!(4))
            .with(
                Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3])
                    .resume_missing_dealer_msg_fails(1, 2),
            )
            .validate()
            .is_err());
        assert!(Plan::new(NZU32!(4))
            .with(
                Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3])
                    .bad_reveal(1, 0)
                    .resume_missing_dealer_msg_fails(2, 1),
            )
            .validate()
            .is_err());
    }

    #[test]
    fn changing_committee() -> anyhow::Result<()> {
        Plan::new(NonZeroU32::new(5).unwrap())
            .with(Round::new(vec![0, 1, 2], vec![1, 2, 3]))
            .with(Round::new(vec![1, 2, 3], vec![2, 3, 4]))
            .with(Round::new(vec![2, 3, 4], vec![3, 4, 0]))
            .with(Round::new(vec![3, 4, 0], vec![4, 0, 1]))
            .run::<MinPk>(0)
    }

    #[test]
    fn missing_ack() -> anyhow::Result<()> {
        // With 4 players, max_faults = 1, so 1 missing ack per dealer is OK
        Plan::new(NonZeroU32::new(4).unwrap())
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]).no_ack(0, 0))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]).no_ack(0, 1))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]).no_ack(0, 2))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]).no_ack(0, 3))
            .run::<MinPk>(0)
    }

    #[test]
    fn increasing_decreasing_committee() -> anyhow::Result<()> {
        Plan::new(NonZeroU32::new(5).unwrap())
            .with(Round::new(vec![0, 1], vec![0, 1, 2]))
            .with(Round::new(vec![0, 1, 2], vec![0, 1, 2, 3]))
            .with(Round::new(vec![0, 1, 2], vec![0, 1]))
            .with(Round::new(vec![0, 1], vec![0, 1, 2, 3, 4]))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1]))
            .run::<MinPk>(0)
    }

    #[test]
    fn bad_reveal_fails() -> anyhow::Result<()> {
        Plan::new(NonZeroU32::new(4).unwrap())
            .with(Round::new(vec![0], vec![0, 1, 2, 3]).bad_reveal(0, 1))
            .run::<MinPk>(0)
    }

    #[test]
    fn bad_share() -> anyhow::Result<()> {
        Plan::new(NonZeroU32::new(4).unwrap())
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]).bad_share(0, 1))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]).bad_share(0, 2))
            .run::<MinPk>(0)
    }

    #[test]
    fn shift_degree_fails() -> anyhow::Result<()> {
        Plan::new(NonZeroU32::new(4).unwrap())
            .with(Round::new(vec![0], vec![0, 1, 2, 3]).shift_degree(
                0,
                NonZeroI32::new(1).ok_or_else(|| anyhow!("invalid NZI32"))?,
            ))
            .run::<MinPk>(0)
    }

    #[test]
    fn replace_share_fails() -> anyhow::Result<()> {
        Plan::new(NonZeroU32::new(4).unwrap())
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]))
            .with(Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3]).replace_share(0))
            .run::<MinPk>(0)
    }

    #[test]
    fn too_many_reveals_dealer() -> anyhow::Result<()> {
        Plan::new(NonZeroU32::new(4).unwrap())
            .with(
                Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3])
                    .no_ack(0, 0)
                    .no_ack(0, 1),
            )
            .run::<MinPk>(0)
    }

    #[test]
    fn too_many_reveals_player() -> anyhow::Result<()> {
        Plan::new(NonZeroU32::new(4).unwrap())
            .with(
                Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3])
                    .no_ack(0, 0)
                    .no_ack(1, 0)
                    .no_ack(3, 0),
            )
            .run::<MinPk>(0)
    }

    #[test]
    fn bad_sigs() -> anyhow::Result<()> {
        Plan::new(NonZeroU32::new(4).unwrap())
            .with(
                Round::new(vec![0, 1, 2, 3], vec![0, 1, 2, 3])
                    .bad_dealer_sig(
                        0,
                        Masks {
                            log: vec![0xFF; 8],
                            ..Default::default()
                        },
                    )
                    .bad_player_sig(
                        0,
                        1,
                        Masks {
                            pub_msg: vec![0xFF; 8],
                            ..Default::default()
                        },
                    ),
            )
            .run::<MinPk>(0)
    }

    #[test]
    fn issue_2745_regression() -> anyhow::Result<()> {
        Plan::new(NonZeroU32::new(6).unwrap())
            .with(
                Round::new(vec![0], vec![5, 1, 3, 0, 4])
                    .no_ack(0, 5)
                    .bad_share(0, 5),
            )
            .with(Round::new(vec![0, 1, 3, 4], vec![0]))
            .with(Round::new(vec![0], vec![0]))
            .run::<MinPk>(0)
    }

    #[test]
    fn signed_dealer_log_commitment() -> Result<(), Error> {
        let sk = ed25519::PrivateKey::from_seed(0);
        let pk = sk.public_key();
        let info = Info::<MinPk, _>::new::<N3f1>(
            b"_COMMONWARE_CRYPTOGRAPHY_BLS12381_DKG_TEST",
            0,
            None,
            Default::default(),
            vec![sk.public_key()].try_into().unwrap(),
            vec![sk.public_key()].try_into().unwrap(),
        )?;
        let mut log0 = {
            let (dealer, _, _) =
                Dealer::start::<N3f1>(&mut test_rng(), info.clone(), sk.clone(), None)?;
            dealer.finalize::<N3f1>()
        };
        let mut log1 = {
            let (mut dealer, pub_msg, priv_msgs) =
                Dealer::start::<N3f1>(&mut test_rng(), info.clone(), sk.clone(), None)?;
            let mut player = Player::new(info.clone(), sk)?;
            let ack = player
                .dealer_message::<N3f1>(pk.clone(), pub_msg, priv_msgs[0].1.clone())
                .unwrap();
            dealer.receive_player_ack(pk, ack)?;
            dealer.finalize::<N3f1>()
        };
        std::mem::swap(&mut log0.log, &mut log1.log);
        assert!(log0.check(&info).is_none());
        assert!(log1.check(&info).is_none());

        Ok(())
    }

    #[test]
    fn info_with_different_mode_is_not_equal() -> Result<(), Error> {
        let sk = ed25519::PrivateKey::from_seed(0);
        let pk = sk.public_key();
        let dealers: Set<ed25519::PublicKey> = vec![pk.clone()].try_into().unwrap();
        let players: Set<ed25519::PublicKey> = vec![pk].try_into().unwrap();

        let default_mode_info = Info::<MinPk, _>::new::<N3f1>(
            b"_COMMONWARE_CRYPTOGRAPHY_BLS12381_DKG_TEST",
            0,
            None,
            Mode::default(),
            dealers.clone(),
            players.clone(),
        )?;
        let roots_of_unity_mode_info = Info::<MinPk, _>::new::<N3f1>(
            b"_COMMONWARE_CRYPTOGRAPHY_BLS12381_DKG_TEST",
            0,
            None,
            Mode::RootsOfUnity,
            dealers,
            players,
        )?;

        assert_ne!(default_mode_info, roots_of_unity_mode_info);
        Ok(())
    }

    #[test]
    fn resume_ignores_invalid_logged_ack_signature() -> Result<(), Error> {
        let dealer_sk = ed25519::PrivateKey::from_seed(11);
        let dealer_pk = dealer_sk.public_key();
        let player_sk = ed25519::PrivateKey::from_seed(22);
        let player_pk = player_sk.public_key();
        let dealers: Set<ed25519::PublicKey> = vec![dealer_pk.clone()].try_into().unwrap();
        let players: Set<ed25519::PublicKey> = vec![player_pk.clone()].try_into().unwrap();
        let info = Info::<MinPk, _>::new::<N3f1>(
            b"_COMMONWARE_CRYPTOGRAPHY_BLS12381_DKG_TEST",
            0,
            None,
            Default::default(),
            dealers.clone(),
            players.clone(),
        )?;
        let wrong_round_info = Info::<MinPk, _>::new::<N3f1>(
            b"_COMMONWARE_CRYPTOGRAPHY_BLS12381_DKG_TEST",
            1,
            None,
            Default::default(),
            dealers,
            players,
        )?;
        let (_, pub_msg, _) =
            Dealer::start::<N3f1>(&mut test_rng(), info.clone(), dealer_sk, None)?;
        let bad_ack = PlayerAck {
            sig: transcript_for_ack(
                &transcript_for_round(&wrong_round_info),
                &dealer_pk,
                &pub_msg,
            )
            .sign(&player_sk),
        };
        let results: Map<_, _> = vec![(player_pk, AckOrReveal::Ack(bad_ack))]
            .into_iter()
            .try_collect()
            .unwrap();
        let mut logs = BTreeMap::new();
        logs.insert(
            dealer_pk,
            DealerLog {
                pub_msg,
                results: DealerResult::Ok(results),
            },
        );

        let resumed = Player::resume::<N3f1>(info, player_sk, &logs, []);
        assert!(resumed.is_ok());
        let (_, acks) = resumed.unwrap();
        assert!(acks.is_empty());

        Ok(())
    }

    #[test]
    fn test_dealer_priv_msg_redacted() {
        let mut rng = test_rng();
        let msg = DealerPrivMsg::new(Scalar::random(&mut rng));
        let debug = format!("{:?}", msg);
        assert!(debug.contains("REDACTED"));
    }

    #[cfg(feature = "arbitrary")]
    mod conformance {
        use super::*;
        use commonware_codec::conformance::CodecConformance;

        commonware_conformance::conformance_tests! {
            CodecConformance<Output<MinPk, ed25519::PublicKey>>,
            CodecConformance<DealerPubMsg<MinPk>>,
            CodecConformance<DealerPrivMsg>,
            CodecConformance<PlayerAck<ed25519::PublicKey>>,
            CodecConformance<AckOrReveal<ed25519::PublicKey>>,
            CodecConformance<DealerResult<ed25519::PublicKey>>,
            CodecConformance<DealerLog<MinPk, ed25519::PublicKey>>,
            CodecConformance<SignedDealerLog<MinPk, ed25519::PrivateKey>>,
        }
    }
}