commonware-cryptography 2026.10.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
//! Cryptographic primitives for generating and verifying certificates.
//!
//! This module provides the [`Verifier`] and [`Scheme`] traits and implementations for
//! producing signatures, validating them (individually or in batches), assembling certificates, and
//! verifying recovered certificates.
//!
//! # Pluggable Cryptography
//!
//! Certificates are generic over the signing scheme, allowing users to choose
//! the scheme best suited for their requirements:
//!
//! - [`ed25519`]: Attributable signatures with individual verification. HSM-friendly, no trusted
//!   setup required, and widely supported. Certificates contain individual signatures from each
//!   signer.
//!
//! - [`secp256r1`]: Attributable signatures with individual verification. HSM-friendly, no trusted
//!   setup required, and widely supported by hardware security modules. Unlike ed25519, does not
//!   benefit from batch verification. Certificates contain individual signatures from each signer.
#![cfg_attr(
    feature = "bls12381",
    doc = "
- [`bls12381_multisig`]: Attributable signatures with aggregated verification. Signatures
  can be aggregated into a single multi-signature for compact certificates while preserving
  attribution (signer indices are stored alongside the aggregated signature). Callers must verify
  a proof of possession for every BLS signing key before constructing the scheme.

- [`bls12381_threshold`]: Non-attributable threshold signatures. Produces succinct
  certificates that are constant-size regardless of committee size. Requires a trusted
  setup (distributed key generation) and cannot attribute signatures to individual signers.
"
)]
//! # Attributable Schemes and Fault Evidence
//!
//! Signing schemes differ in whether per-participant activities can be used as evidence of
//! either liveness or of committing a fault:
//!
//! - **Attributable Schemes**: Individual signatures can be presented to some third party as
//!   evidence of either liveness or of committing a fault. Certificates contain signer indices
//!   alongside individual signatures, enabling secure per-participant activity tracking and
//!   conflict detection.
//!
//! - **Non-Attributable Schemes**: Individual signatures cannot be presented to some third party
//!   as evidence because they can be forged after collecting a quorum of partial signatures.
//!   Authenticated peer connections allow this evidence to be used locally, but not by an external
//!   observer.
//!
//! The [`Scheme::is_attributable()`] associated function signals whether evidence can be safely
//! exposed to third parties.
//!
//! # Identity Keys vs Signing Keys
//!
//! A participant may supply both an identity key and a signing key. The identity key
//! is used for assigning a unique order to the participant set and authenticating connections
//! whereas the signing key is used for producing and verifying signatures/certificates.
//!
#![cfg_attr(
    feature = "bls12381",
    doc = "Some cryptographic schemes are only performant when used in batch verification (like
[`bls12381_multisig`]) and/or are refreshed frequently (like [`bls12381_threshold`])."
)]
//! Refer to [ed25519] for an example of a scheme that uses the same key for both purposes.

#[cfg(feature = "bls12381")]
pub use crate::bls12381::certificate::{
    multisig as bls12381_multisig, threshold as bls12381_threshold,
};
pub use crate::ed25519::certificate as ed25519;
#[commonware_macros::stability(ALPHA)]
pub use crate::secp256r1::certificate as secp256r1;
use crate::{Digest, PublicKey};
#[cfg(not(feature = "std"))]
use alloc::{collections::BTreeSet, sync::Arc, vec, vec::Vec};
use bytes::{BufMut, Bytes};
use commonware_codec::{
    Buf, Codec, CodecFixed, EncodeSize, Error as CodecError, FixedSize, MaxEncodeSize, Read,
    ReadExt, Write, types::lazy::Lazy, util::max_items_size,
};
use commonware_parallel::Strategy;
use commonware_utils::{Faults, Participant, Widen, bitmap::BitMap, iter::NonEmpty, ordered::Set};
use core::{fmt::Debug, hash::Hash};
use rand_chacha::ChaCha20Rng;
use rand_core::{CryptoRng, SeedableRng};
#[cfg(feature = "std")]
use std::{collections::BTreeSet, sync::Arc, vec::Vec};
use thiserror::Error;

/// The scheme's own place in the participant set.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Membership {
    /// A participant that holds signing material at this index.
    Signer(Participant),
    /// A participant without signing material at this index.
    Member(Participant),
}

impl Membership {
    /// Returns the participant's index.
    pub const fn index(&self) -> Participant {
        match self {
            Self::Signer(index) | Self::Member(index) => *index,
        }
    }

    /// Returns the participant's index if it holds signing material.
    pub const fn signer(&self) -> Option<Participant> {
        match self {
            Self::Signer(index) => Some(*index),
            Self::Member(_) => None,
        }
    }
}

/// A participant's attestation for a certificate.
#[derive(Clone, Debug)]
pub struct Attestation<S: Scheme> {
    /// Index of the signer inside the participant set.
    pub signer: Participant,
    /// Scheme-specific signature or share produced for a given subject.
    pub signature: Lazy<S::Signature>,
}

impl<S: Scheme> PartialEq for Attestation<S> {
    fn eq(&self, other: &Self) -> bool {
        self.signer == other.signer && self.signature == other.signature
    }
}

impl<S: Scheme> Eq for Attestation<S> {}

impl<S: Scheme> Hash for Attestation<S> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.signer.hash(state);
        self.signature.hash(state);
    }
}

impl<S: Scheme> Write for Attestation<S> {
    fn write(&self, writer: &mut impl BufMut) {
        self.signer.write(writer);
        self.signature.write(writer);
    }
}

impl<S: Scheme> EncodeSize for Attestation<S> {
    fn encode_size(&self) -> usize {
        self.signer.encode_size() + self.signature.encode_size()
    }
}

impl<S: Scheme> MaxEncodeSize for Attestation<S> {
    const MAX_ENCODE_SIZE: usize = Participant::MAX_ENCODE_SIZE + S::Signature::SIZE;
}

impl<S: Scheme> Read for Attestation<S> {
    type Cfg = ();

    fn read_cfg(reader: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
        let signer = Participant::read(reader)?;
        let signature = ReadExt::read(reader)?;

        Ok(Self { signer, signature })
    }
}

#[cfg(feature = "arbitrary")]
impl<S: Scheme> arbitrary::Arbitrary<'_> for Attestation<S>
where
    S::Signature: for<'a> arbitrary::Arbitrary<'a>,
{
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let signer = Participant::arbitrary(u)?;
        let signature = S::Signature::arbitrary(u)?;
        Ok(Self {
            signer,
            signature: signature.into(),
        })
    }
}

/// Result of batch-verifying attestations.
pub struct Verification<S: Scheme> {
    /// Contains the attestations accepted by the scheme.
    pub verified: Vec<Attestation<S>>,
    /// Identifies the participant indices rejected during batch verification.
    pub invalid: Vec<Participant>,
}

impl<S: Scheme> Verification<S> {
    /// Creates a new `Verification` result.
    pub const fn new(verified: Vec<Attestation<S>>, invalid: Vec<Participant>) -> Self {
        Self { verified, invalid }
    }
}

/// Errors returned while assembling attestations into a certificate.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum AssemblyError {
    /// Structurally valid attestations do not meet the scheme's quorum.
    #[error("insufficient attestations: expected={0}, found={1}")]
    InsufficientAttestations(u32, u32),
    /// An attestation references an index outside the participant set.
    #[error("unknown signer: {0}")]
    UnknownSigner(Participant),
    /// More than one attestation references the same signer.
    #[error("duplicate signer: {0}")]
    DuplicateSigner(Participant),
    /// An attestation contains a malformed encoded signature.
    #[error("malformed signature from signer: {0}")]
    MalformedSignature(Participant),
    /// The scheme could not recover a certificate from structurally valid attestations.
    #[error("certificate recovery failed")]
    RecoveryFailed,
}

/// Trait for namespace types that can derive themselves from a base namespace.
///
/// This trait is implemented by namespace types to define how they are computed
/// from a base namespace string.
pub trait Namespace: Clone + Send + Sync {
    /// Derive a namespace from the given base.
    fn derive(namespace: &[u8]) -> Self;
}

impl Namespace for Vec<u8> {
    fn derive(namespace: &[u8]) -> Self {
        namespace.to_vec()
    }
}

/// Identifies the subject of a signature or certificate.
pub trait Subject: Clone + Debug + Send + Sync {
    /// Pre-computed namespace(s) for this subject type.
    type Namespace: Namespace;

    /// Get the namespace bytes for this subject instance.
    fn namespace<'a>(&self, derived: &'a Self::Namespace) -> &'a [u8];

    /// Get the message bytes for this subject instance.
    fn message(&self) -> Bytes;
}

/// Cryptographic surface for recovered certificate verification.
///
/// A `Verifier` verifies recovered certificates, but does not expose participant
/// metadata or signing operations.
pub trait Verifier: Clone + Debug + Send + Sync + 'static {
    /// Subject type for certificate verification.
    type Subject<'a, D: Digest>: Subject;

    /// Fault model used to compute certificate quorums.
    type Faults: Faults;

    /// Public key type for participant identity used to order and index the participant set.
    type PublicKey: PublicKey;

    /// Certificate assembled from a set of attestations.
    type Certificate: Clone + Debug + Eq + Hash + Send + Sync + Codec;

    /// Verifies a certificate that was recovered or received from the network.
    ///
    /// Acceptance authenticates a quorum for `subject` under the scheme's key setup, fault model,
    /// and cryptographic assumptions. It need not authenticate the individual attestations used
    /// to assemble the certificate.
    fn verify_certificate<R, D>(
        &self,
        rng: &mut R,
        subject: Self::Subject<'_, D>,
        certificate: &Self::Certificate,
        strategy: &impl Strategy,
    ) -> bool
    where
        R: CryptoRng,
        D: Digest;

    /// Verifies a non-empty stream of certificates, returning `false` at the first verification
    /// failure.
    fn verify_certificates<'a, R, D, I>(
        &self,
        rng: &mut R,
        certificates: NonEmpty<I>,
        strategy: &impl Strategy,
    ) -> bool
    where
        R: CryptoRng,
        D: Digest,
        I: Iterator<Item = (Self::Subject<'a, D>, &'a Self::Certificate)>,
    {
        for (subject, certificate) in certificates {
            if !self.verify_certificate(rng, subject, certificate, strategy) {
                return false;
            }
        }

        true
    }

    /// Batch-verifies certificates and returns a per-item result.
    ///
    /// For batchable schemes, attempts batch verification first and bisects
    /// on failure to efficiently identify invalid certificates. For
    /// non-batchable schemes, verifies each certificate individually.
    /// Empty input returns an empty result.
    fn verify_certificates_bisect<'a, R, D>(
        &self,
        rng: &mut R,
        certificates: &[(Self::Subject<'a, D>, &'a Self::Certificate)],
        strategy: &impl Strategy,
    ) -> Vec<bool>
    where
        R: CryptoRng,
        D: Digest,
        Self::Subject<'a, D>: Copy,
    {
        let len = certificates.len();
        let mut verified = vec![false; len];
        if len == 0 {
            return verified;
        }

        // Non-batchable schemes (e.g. secp256r1) gain nothing from bisection
        // since verify_certificates already checks one-by-one.
        if !Self::is_batchable() {
            for (i, (subject, certificate)) in certificates.iter().enumerate() {
                verified[i] = self.verify_certificate(rng, *subject, certificate, strategy);
            }
            return verified;
        }

        // Iterative bisection: try the full range first. If batch verification
        // passes, mark the entire range valid. If it fails, split in half and
        // retry each half. Singletons that fail remain false.
        //
        //       [0..8) fail
        //      /            \
        //   [0..4) pass   [4..8) fail
        //                /          \
        //            [4..6) pass  [6..8) fail
        //                        /        \
        //                    [6..7) pass  [7..8) fail
        let mut stack = vec![(0, len)];
        while let Some((start, end)) = stack.pop() {
            let (first, rest) = certificates[start..end]
                .split_first()
                .expect("bisection ranges are non-empty");
            let certificates = NonEmpty::new(*first, rest.iter().copied());
            if self.verify_certificates(rng, certificates, strategy) {
                verified[start..end].fill(true);
            } else if end - start > 1 {
                let mid = start + (end - start) / 2;
                stack.push((mid, end));
                stack.push((start, mid));
            }
        }

        verified
    }

    /// Returns whether this scheme benefits from batch verification.
    ///
    /// Schemes that benefit from batch verification should return `true`, allowing callers to
    /// optimize by deferring verification until multiple signatures are available.
    ///
    /// Schemes that don't benefit from batch verification (like [`secp256r1`]) should
    /// return `false`, indicating that eager per-signature verification is preferred.
    fn is_batchable() -> bool;

    /// Returns an upper bound on the encoded size of a certificate that decodes under
    /// [`Self::certificate_codec_config`] for a verifier over at most `participants` participants.
    fn max_certificate_size(participants: u32) -> usize;

    /// Encoding configuration for bounded-size certificate decoding used in network payloads.
    fn certificate_codec_config(&self) -> <Self::Certificate as Read>::Cfg;

    /// Encoding configuration that allows unbounded certificate decoding.
    ///
    /// Only use this when decoding data from trusted local storage, it must not be exposed to
    /// adversarial inputs or network payloads.
    fn certificate_codec_config_unbounded() -> <Self::Certificate as Read>::Cfg;
}

/// Cryptographic surface for multi-party certificate schemes.
///
/// A `Scheme` extends [`Verifier`] with the signing surface: it produces attestations, validates
/// them (individually or in batches), and assembles certificates. Implementations may override the
/// provided defaults to take advantage of scheme-specific batching strategies.
pub trait Scheme: Verifier {
    /// Signature emitted by individual participants.
    type Signature: Clone + Debug + Eq + Hash + Send + Sync + CodecFixed<Cfg = ()>;

    /// Returns the scheme's own [`Membership`] in [`Self::participants`], or `None` if it
    /// holds no participant identity.
    fn me(&self) -> Option<Membership>;

    /// Returns the ordered set of participant public identity keys managed by the scheme.
    fn participants(&self) -> &Set<Self::PublicKey>;

    /// Signs a subject, or returns `None` if the scheme cannot sign (a verifier or member
    /// instance).
    fn sign<D: Digest>(&self, subject: Self::Subject<'_, D>) -> Option<Attestation<Self>>;

    /// Verifies a single attestation against the participant material managed by the scheme.
    fn verify_attestation<R, D>(
        &self,
        rng: &mut R,
        subject: Self::Subject<'_, D>,
        attestation: &Attestation<Self>,
        strategy: &impl Strategy,
    ) -> bool
    where
        R: CryptoRng,
        D: Digest;

    /// Batch-verifies attestations and separates valid attestations from signer indices that failed
    /// verification. Empty input produces an empty result in both sets.
    ///
    /// Callers must not include duplicate attestations from the same signer: duplicates may
    /// produce incorrect results.
    fn verify_attestations<R, D, I>(
        &self,
        rng: &mut R,
        subject: Self::Subject<'_, D>,
        attestations: I,
        strategy: &impl Strategy,
    ) -> Verification<Self>
    where
        R: CryptoRng,
        D: Digest,
        I: IntoIterator<Item = Attestation<Self>>,
        I::IntoIter: Send,
    {
        let mut invalid = BTreeSet::new();

        let verified = attestations.into_iter().filter_map(|attestation| {
            if self.verify_attestation(&mut *rng, subject.clone(), &attestation, strategy) {
                Some(attestation)
            } else {
                invalid.insert(attestation.signer);
                None
            }
        });

        Verification::new(verified.collect(), invalid.into_iter().collect())
    }

    /// Attempts to construct an authenticated certificate from pending and verified attestations.
    ///
    /// `verified` must already be valid for this exact scheme configuration and `subject`.
    /// Signers must be unique across both inputs. Only pending attestations undergo fallback
    /// verification.
    ///
    /// `Ok` authenticates the certificate for `subject`, but does not guarantee that each pending
    /// attestation was individually verified. Callers requiring individual correctness should use
    /// [`Self::verify_attestations`] followed by [`Self::assemble`].
    ///
    /// On failure, `Err` contains the verification results for `pending`. Accepted attestations
    /// can be retained alongside `verified` for subsequent assembly, and may already form a quorum.
    fn optimistic_assemble<'a, R, D, I, J>(
        &self,
        rng: &mut R,
        subject: Self::Subject<'_, D>,
        pending: I,
        verified: J,
        strategy: &impl Strategy,
    ) -> Result<Self::Certificate, Verification<Self>>
    where
        R: CryptoRng,
        D: Digest,
        I: IntoIterator<Item = Attestation<Self>>,
        I::IntoIter: ExactSizeIterator + Send,
        J: IntoIterator<Item = &'a Attestation<Self>>,
        J::IntoIter: Send;

    /// Assembles a non-empty stream of attestations into a candidate certificate.
    ///
    /// Inputs may be unverified. `Ok` does not authenticate them or the resulting certificate.
    /// Callers using such inputs must call [`Verifier::verify_certificate`] for the intended subject.
    ///
    /// Insufficient input returns [`AssemblyError::InsufficientAttestations`].
    /// A signer-unique quorum already verified for one subject must assemble successfully into a
    /// certificate that verifies for that subject.
    fn assemble<I>(
        &self,
        attestations: NonEmpty<I>,
        strategy: &impl Strategy,
    ) -> Result<Self::Certificate, AssemblyError>
    where
        I: Iterator<Item = Attestation<Self>> + Send;

    /// Returns whether per-participant fault evidence can be safely exposed.
    ///
    /// Schemes where individual signatures can be safely reported as fault evidence should
    /// return `true`.
    fn is_attributable() -> bool;
}

/// Verifies pending attestations before assembling them with verified attestations.
///
/// Inputs must satisfy [`Scheme::optimistic_assemble`]'s requirements.
/// Rejected attestations return `Err` even if the remaining attestations could certify,
/// preserving fault evidence for the caller. Assembly failure also returns the pending results.
pub fn verify_then_assemble<'a, S, R, D, I, J>(
    scheme: &S,
    rng: &mut R,
    subject: S::Subject<'_, D>,
    pending: I,
    verified: J,
    strategy: &impl Strategy,
) -> Result<S::Certificate, Verification<S>>
where
    S: Scheme,
    R: CryptoRng,
    D: Digest,
    I: IntoIterator<Item = Attestation<S>>,
    I::IntoIter: Send,
    J: IntoIterator<Item = &'a Attestation<S>>,
    J::IntoIter: Send,
{
    // Empty input already has a known verification result. Preserve rejected signer
    // evidence for non-empty input even when the accepted attestations could certify.
    let result = NonEmpty::try_new(pending.into_iter()).map_or_else(
        || Verification::new(Vec::new(), Vec::new()),
        |pending| scheme.verify_attestations::<_, D, _>(rng, subject, pending, strategy),
    );
    if !result.invalid.is_empty() {
        return Err(result);
    }

    // A verified quorum needs no further authentication. Keep the pending results
    // available if assembly fails.
    let Some(attestations) = NonEmpty::try_new(
        result
            .verified
            .iter()
            .cloned()
            .chain(verified.into_iter().cloned()),
    ) else {
        return Err(result);
    };

    scheme.assemble(attestations, strategy).map_err(|_| result)
}

/// Authenticates a candidate certificate first, verifying pending attestations only on failure.
///
/// Implements [`Scheme::optimistic_assemble`]'s input and result contract. A quorum consisting
/// entirely of verified attestations is assembled without another certificate check.
pub fn optimistic_assemble<'a, S, R, D, I, J>(
    scheme: &S,
    rng: &mut R,
    subject: S::Subject<'_, D>,
    pending: I,
    verified: J,
    strategy: &impl Strategy,
) -> Result<S::Certificate, Verification<S>>
where
    S: Scheme,
    R: CryptoRng,
    D: Digest,
    I: IntoIterator<Item = Attestation<S>>,
    I::IntoIter: ExactSizeIterator + Send,
    J: IntoIterator<Item = &'a Attestation<S>>,
    J::IntoIter: Send,
{
    let pending = pending.into_iter();
    let verified = verified.into_iter();

    // A verified-only quorum needs no further authentication.
    if pending.len() == 0 {
        return verify_then_assemble::<_, _, D, _, _>(
            scheme, rng, subject, pending, verified, strategy,
        );
    }

    // Decode through the strategy before cloning so assembly and fallback reuse
    // the decoded values.
    let mut pending = strategy.map_collect_vec(pending, |attestation| {
        let _ = attestation.signature.get();
        attestation
    });
    let attestations = pending.iter().cloned().chain(verified.cloned());
    if let Some(attestations) = NonEmpty::try_new(attestations)
        && let Ok(certificate) = scheme.assemble(attestations, strategy)
        && scheme.verify_certificate::<_, D>(rng, subject.clone(), &certificate, strategy)
    {
        return Ok(certificate);
    }

    // A single pending attestation is the leaf of the fallback search.
    if pending.len() == 1 {
        return Err(scheme.verify_attestations::<_, D, _>(rng, subject, pending, strategy));
    }

    // Each half needs ordinary verification, including every signed component
    // of schemes with more than one signature per attestation. Independent RNGs
    // allow both halves to run concurrently without sharing the caller's RNG.
    let rest = pending.split_off(pending.len().div_ceil(2));
    let mut first_rng = ChaCha20Rng::from_rng(&mut *rng);
    let mut rest_rng = ChaCha20Rng::from_rng(rng);
    let first_subject = subject.clone();
    let (mut result, rest) = strategy.join(
        || scheme.verify_attestations::<_, D, _>(&mut first_rng, first_subject, pending, strategy),
        || scheme.verify_attestations::<_, D, _>(&mut rest_rng, subject, rest, strategy),
    );
    result.verified.extend(rest.verified);
    result.invalid.extend(rest.invalid);
    Err(result)
}

/// A scheme handle returned by a [`Provider`] for one scope.
///
/// Always usable as a [`Verifier`] for certificate verification. The full signing scheme is
/// recoverable with [`Scoped::into_scheme`] only when the scope was built with [`Scoped::scheme`].
/// A scope built with [`Scoped::verifier`] yields `None`.
#[derive(Clone, Debug)]
pub struct Scoped<S: Scheme> {
    scheme: Arc<S>,
    can_sign: bool,
}

impl<S: Scheme> Scoped<S> {
    /// Builds a verify-only scope.
    pub const fn verifier(scheme: Arc<S>) -> Self {
        Self {
            scheme,
            can_sign: false,
        }
    }

    /// Builds a full signing scope.
    pub const fn scheme(scheme: Arc<S>) -> Self {
        Self {
            scheme,
            can_sign: true,
        }
    }

    /// Returns the full signing scheme, or `None` for a verify-only scope.
    pub fn into_scheme(self) -> Option<Arc<S>> {
        self.can_sign.then_some(self.scheme)
    }
}

impl<S: Scheme> Verifier for Scoped<S> {
    type Subject<'a, D: Digest> = S::Subject<'a, D>;
    type Faults = S::Faults;
    type PublicKey = S::PublicKey;
    type Certificate = S::Certificate;

    fn verify_certificate<R, D>(
        &self,
        rng: &mut R,
        subject: Self::Subject<'_, D>,
        certificate: &Self::Certificate,
        strategy: &impl Strategy,
    ) -> bool
    where
        R: CryptoRng,
        D: Digest,
    {
        self.scheme
            .verify_certificate(rng, subject, certificate, strategy)
    }

    fn verify_certificates<'a, R, D, I>(
        &self,
        rng: &mut R,
        certificates: NonEmpty<I>,
        strategy: &impl Strategy,
    ) -> bool
    where
        R: CryptoRng,
        D: Digest,
        I: Iterator<Item = (Self::Subject<'a, D>, &'a Self::Certificate)>,
    {
        self.scheme.verify_certificates(rng, certificates, strategy)
    }

    fn is_batchable() -> bool {
        S::is_batchable()
    }

    fn max_certificate_size(participants: u32) -> usize {
        S::max_certificate_size(participants)
    }

    fn certificate_codec_config(&self) -> <Self::Certificate as Read>::Cfg {
        self.scheme.certificate_codec_config()
    }

    fn certificate_codec_config_unbounded() -> <Self::Certificate as Read>::Cfg {
        S::certificate_codec_config_unbounded()
    }
}

/// Supplies the signing scheme for a given scope.
///
/// This trait uses an associated `Scope` type, allowing implementations to work
/// with any scope representation (e.g., epoch numbers, block heights, etc.).
pub trait Provider: Clone + Send + Sync + 'static {
    /// The scope type used to look up schemes.
    type Scope: Clone + Send + Sync + 'static;
    /// The signing scheme to provide.
    type Scheme: Scheme;

    /// Return a [`Scoped`] for `scope` capable of verifying certificates produced under it.
    ///
    /// A scheme that can verify certificates from any scope without scope-specific state should
    /// return a verify-only [`Scoped`] (via [`Scoped::verifier`]) for every scope. A fixed group
    /// public key that survives committee rotation is one such case. A scheme that needs
    /// scope-specific verification state should return `None` once that state is unavailable.
    fn scoped(&self, scope: Self::Scope) -> Option<Scoped<Self::Scheme>>;

    /// Return the full signing scheme that corresponds to `scope`, if available.
    ///
    /// The default returns a scheme only when [`Provider::scoped`] yields a signing scope, so a
    /// verify-only scope produces `None`. Override this when the signing scheme is available even
    /// for scopes that [`Provider::scoped`] serves with a verify-only result.
    fn scheme(&self, scope: Self::Scope) -> Option<Arc<Self::Scheme>> {
        self.scoped(scope).and_then(Scoped::into_scheme)
    }
}

/// Bitmap wrapper that tracks which participants signed a certificate.
///
/// Internally, it stores bits in 1-byte chunks for compact encoding.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Signers {
    bitmap: BitMap<1>,
}

impl Signers {
    /// Returns the largest encoded size of a signer bitmap over at most `participants`
    /// participants.
    pub(crate) fn max_encode_size(participants: u32) -> usize {
        BitMap::<1>::max_encode_size(u64::from(participants))
    }

    /// Builds [`Signers`] from an iterator of signer indices.
    ///
    /// Indices need not be sorted: some signing schemes aggregate commutatively, so ordering
    /// is left to the caller.
    pub fn new(
        participants: u32,
        signers: impl IntoIterator<Item = Participant>,
    ) -> Result<Self, AssemblyError> {
        let mut bitmap = BitMap::zeroes(u64::from(participants));
        for signer in signers.into_iter() {
            let index = u64::from(signer.get());
            if index >= bitmap.len() {
                return Err(AssemblyError::UnknownSigner(signer));
            }
            if bitmap.get(index) {
                return Err(AssemblyError::DuplicateSigner(signer));
            }
            bitmap.set(index, true);
        }

        Ok(Self { bitmap })
    }

    /// Requires at least `required` signers in an already validated set.
    pub(crate) fn require(self, required: u32) -> Result<Self, AssemblyError> {
        let found = u32::try_from(self.count()).expect("signer count exceeds u32::MAX");
        if found < required {
            return Err(AssemblyError::InsufficientAttestations(required, found));
        }

        Ok(self)
    }

    /// Returns the length of the bitmap (the size of the participant set).
    #[allow(clippy::len_without_is_empty)]
    pub const fn len(&self) -> usize {
        self.bitmap.len() as usize
    }

    /// Returns how many participants are marked as signers.
    pub fn count(&self) -> usize {
        self.bitmap.count_ones() as usize
    }

    /// Iterates over signer indices in ascending order.
    pub fn iter(&self) -> impl Iterator<Item = Participant> + '_ {
        self.bitmap
            .ones_iter()
            .map(|index| Participant::from_usize(index as usize))
    }
}

/// Returns an upper bound on the encoded size of a certificate with a signer bitmap over at most
/// `participants` participants and one `signature_size`-byte signature per signer.
pub(crate) fn max_individual_certificate_size(participants: u32, signature_size: usize) -> usize {
    Signers::max_encode_size(participants)
        + max_items_size(Widen::widen(participants), signature_size)
}

/// Builds [`Signers`] using the participant set as the valid signer-index range.
///
/// # Panics
///
/// Panics if the participant count exceeds `u32::MAX`.
impl<'a, P, I> TryFrom<(&'a Set<P>, I)> for Signers
where
    I: IntoIterator<Item = Participant>,
{
    type Error = AssemblyError;

    fn try_from((participants, signers): (&'a Set<P>, I)) -> Result<Self, Self::Error> {
        let total = u32::try_from(participants.len()).expect("participant count exceeds u32::MAX");
        Self::new(total, signers)
    }
}

impl Write for Signers {
    fn write(&self, writer: &mut impl BufMut) {
        self.bitmap.write(writer);
    }
}

impl EncodeSize for Signers {
    fn encode_size(&self) -> usize {
        self.bitmap.encode_size()
    }
}

impl Read for Signers {
    type Cfg = usize;

    fn read_cfg(reader: &mut impl Buf, max_participants: &usize) -> Result<Self, CodecError> {
        let bitmap = BitMap::read_cfg(reader, &(..=*max_participants as u64).into())?;
        // The participant count is treated as an upper bound for decoding flexibility, e.g. one
        // might use `Scheme::certificate_codec_config_unbounded` for decoding certificates from
        // local storage.
        //
        // Exact length validation **must** be enforced at verification time by the signing schemes
        // against the actual participant set size.
        Ok(Self { bitmap })
    }
}

#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary<'_> for Signers {
    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
        let participants = u.arbitrary_len::<u8>()? % 10;
        let signer_count = u.arbitrary_len::<u8>()?.min(participants);
        let signers = (0..u32::try_from(signer_count).expect("signer count exceeds u32::MAX"))
            .map(Participant::new)
            .collect::<Vec<_>>();
        Ok(Self::new(participants.try_into().unwrap(), signers)
            .expect("indices are unique and in range"))
    }
}

/// A scheme provider that always returns the same scheme regardless of scope.
#[derive(Clone, Debug)]
pub struct ConstantProvider<S: Scheme, Sc = ()> {
    scheme: Arc<S>,
    _scope: core::marker::PhantomData<Sc>,
}

impl<S: Scheme, Sc> ConstantProvider<S, Sc> {
    /// Creates a new provider that always returns the given scheme.
    pub fn new(scheme: S) -> Self {
        Self {
            scheme: Arc::new(scheme),
            _scope: core::marker::PhantomData,
        }
    }
}

impl<S: Scheme, Sc: Clone + Send + Sync + 'static> crate::certificate::Provider
    for ConstantProvider<S, Sc>
{
    type Scope = Sc;
    type Scheme = S;

    fn scoped(&self, _: Sc) -> Option<Scoped<S>> {
        Some(Scoped::scheme(self.scheme.clone()))
    }
}

#[cfg(feature = "mocks")]
pub mod mocks;

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(feature = "bls12381")]
    use crate::bls12381::{
        dkg::feldman_desmedt as dkg,
        primitives::{
            group::Private as BlsPrivate,
            ops::{compute_public, sign_proof_of_possession, verify_proof_of_possession},
            sharing::Mode,
            variant::{MinPk, MinSig, Variant},
        },
    };
    use crate::{
        Signer as _,
        ed25519::{PrivateKey, Signature},
        sha256::Digest as Sha256Digest,
    };
    use commonware_codec::{Decode, Encode, varint::MAX_U32_VARINT_SIZE};
    use commonware_math::algebra::Random;
    use commonware_parallel::Sequential;
    use commonware_utils::{
        N3f1, TryCollect, Widen, non_empty,
        ordered::{Quorum as _, Set},
        test_rng,
    };
    #[cfg(feature = "bls12381")]
    use commonware_utils::{NZU32, ordered::BiMap, sync::Mutex};
    #[cfg(feature = "bls12381")]
    use core::sync::atomic::{AtomicUsize, Ordering};
    use ed25519_fixture::{Scheme as Ed25519Scheme, TestSubject};

    #[test]
    fn test_max_individual_certificate_size() {
        // The bound covers every signature and never decreases as the committee grows.
        let mut previous = 0;
        for n in [0, 1, 7, 8, 9, 127, 128] {
            let signers = Signers::new(n, (0..n).map(Participant::new)).unwrap();
            let signatures = vec![[0u8; Signature::SIZE]; Widen::widen(n)];
            assert_eq!(Signers::max_encode_size(n), signers.encode().len());
            let size = max_individual_certificate_size(n, Signature::SIZE);
            assert_eq!(
                size,
                signers.encode().len() + MAX_U32_VARINT_SIZE + signatures.len() * Signature::SIZE
            );
            assert!(signers.encode().len() + signatures.encode().len() <= size);
            assert!(size >= previous);
            previous = size;
        }

        // Counts up to `u32::MAX` fit the signature length prefix.
        let n: usize = Widen::widen(u32::MAX);
        assert_eq!(
            max_individual_certificate_size(u32::MAX, Signature::SIZE),
            u64::SIZE + n.div_ceil(8) + MAX_U32_VARINT_SIZE + n * Signature::SIZE,
        );
    }

    #[test]
    fn test_new_signers() {
        let signers = Signers::new(6, [0, 3, 5].map(Participant::new)).unwrap();
        let collected: Vec<_> = signers.iter().collect();
        assert_eq!(
            collected,
            vec![0, 3, 5]
                .into_iter()
                .map(Participant::new)
                .collect::<Vec<_>>()
        );
        assert_eq!(signers.count(), 3);
    }

    #[test]
    fn test_new_out_of_bounds() {
        assert_eq!(
            Signers::new(4, [0, 4].map(Participant::new)),
            Err(AssemblyError::UnknownSigner(Participant::new(4)))
        );
    }

    #[test]
    fn test_new_duplicate() {
        assert_eq!(
            Signers::new(4, [0, 0, 1].map(Participant::new)),
            Err(AssemblyError::DuplicateSigner(Participant::new(0)))
        );
    }

    #[test]
    fn test_new_not_increasing() {
        assert!(Signers::new(4, [2, 1].map(Participant::new)).is_ok());
    }

    #[test]
    fn test_try_from_set_and_require() {
        let participants = Set::from_iter_dedup(0..4);
        let signers = Signers::try_from((&participants, [0, 2, 3].map(Participant::new)))
            .unwrap()
            .require(3)
            .unwrap();
        assert_eq!(signers.count(), 3);
        assert_eq!(
            Signers::try_from((&participants, [0, 2].map(Participant::new)))
                .unwrap()
                .require(3),
            Err(AssemblyError::InsufficientAttestations(3, 2))
        );
    }

    #[test]
    fn test_try_from_set_checks_signer_bounds() {
        let participants = Set::<u8>::default();
        let signer = Participant::new(0);
        assert_eq!(
            Signers::try_from((&participants, [signer])),
            Err(AssemblyError::UnknownSigner(signer))
        );
    }

    #[test]
    fn test_codec_round_trip() {
        let signers = Signers::new(9, [1, 6].map(Participant::new)).unwrap();
        let encoded = signers.encode();
        let decoded = Signers::decode_cfg(encoded, &9).unwrap();
        assert_eq!(decoded, signers);
    }

    #[test]
    fn test_decode_respects_participant_limit() {
        let signers = Signers::new(8, [0, 3, 7].map(Participant::new)).unwrap();
        let encoded = signers.encode();
        // More participants than expected should fail.
        assert!(Signers::decode_cfg(encoded.clone(), &2).is_err());
        // Exact participant bound succeeds.
        assert!(Signers::decode_cfg(encoded.clone(), &8).is_ok());
        // Less participants than expected succeeds (upper bound).
        assert!(Signers::decode_cfg(encoded, &10).is_ok());
    }

    mod ed25519_fixture {
        use crate::{certificate::Subject, impl_certificate_ed25519};
        use commonware_utils::N3f1;

        /// Test subject for certificate verification tests.
        #[derive(Copy, Clone, Debug)]
        pub struct TestSubject {
            pub message: &'static [u8],
        }

        impl Subject for TestSubject {
            type Namespace = Vec<u8>;

            fn namespace<'a>(&self, derived: &'a Self::Namespace) -> &'a [u8] {
                derived
            }

            fn message(&self) -> bytes::Bytes {
                bytes::Bytes::from_static(self.message)
            }
        }

        // Use the macro to generate the test scheme
        impl_certificate_ed25519!(TestSubject, Vec<u8>, N3f1);
    }

    const NAMESPACE: &[u8] = b"test-bisect";
    const MESSAGE: &[u8] = b"good message";
    const BAD_MESSAGE: &[u8] = b"bad message";

    fn make_certificate(
        schemes: &[Ed25519Scheme],
        message: &'static [u8],
    ) -> <Ed25519Scheme as Verifier>::Certificate {
        let attestations: Vec<_> = schemes
            .iter()
            .filter_map(|s| s.sign::<Sha256Digest>(TestSubject { message }))
            .collect();
        schemes[0]
            .assemble(non_empty![@attestations], &Sequential)
            .expect("assembly failed")
    }

    fn setup_ed25519(n: u32) -> (Vec<Ed25519Scheme>, Ed25519Scheme) {
        let mut rng = test_rng();
        let private_keys: Vec<_> = (0..n).map(|_| PrivateKey::random(&mut rng)).collect();
        let participants: Set<crate::ed25519::PublicKey> = private_keys
            .iter()
            .map(|sk| sk.public_key())
            .try_collect()
            .unwrap();
        let signers: Vec<_> = private_keys
            .into_iter()
            .map(|sk| Ed25519Scheme::signer(NAMESPACE, participants.clone(), sk).unwrap())
            .collect();
        let verifier = Ed25519Scheme::verifier(NAMESPACE, participants);
        (signers, verifier)
    }

    /// Signers report a signing membership, members report a non-signing one at their
    /// identity key's position, and an identity-less verifier reports none.
    #[test]
    fn membership_reports_index_and_signing() {
        let (signers, verifier) = setup_ed25519(4);
        let participants = verifier.participants().clone();
        let signer = signers[0].me().unwrap();
        let index = signer.index();
        let key = participants.key(index).unwrap().clone();

        let member = Ed25519Scheme::member(NAMESPACE, participants, &key).unwrap();
        assert_eq!(member.me(), Some(Membership::Member(index)));
        assert_eq!(member.me().unwrap().index(), index);
        assert_eq!(member.me().unwrap().signer(), None);

        assert_eq!(signer, Membership::Signer(index));
        assert_eq!(signer.signer(), Some(index));

        assert_eq!(verifier.me(), None);
    }

    #[test]
    fn test_bisect_empty() {
        let mut rng = test_rng();
        let (_, verifier) = setup_ed25519(4);
        let result =
            verifier.verify_certificates_bisect::<_, Sha256Digest>(&mut rng, &[], &Sequential);
        assert!(result.is_empty());
    }

    #[test]
    fn test_bisect_all_valid() {
        let mut rng = test_rng();
        let (schemes, verifier) = setup_ed25519(4);
        let cert = make_certificate(&schemes, MESSAGE);
        let good = TestSubject { message: MESSAGE };
        let pairs: Vec<_> = (0..5).map(|_| (good, &cert)).collect();
        let result =
            verifier.verify_certificates_bisect::<_, Sha256Digest>(&mut rng, &pairs, &Sequential);
        assert_eq!(result, vec![true; 5]);
    }

    #[test]
    fn test_bisect_mixed() {
        let mut rng = test_rng();
        let (schemes, verifier) = setup_ed25519(4);
        let cert = make_certificate(&schemes, MESSAGE);
        let good = TestSubject { message: MESSAGE };
        let bad = TestSubject {
            message: BAD_MESSAGE,
        };
        let pairs = vec![
            (good, &cert),
            (bad, &cert),
            (good, &cert),
            (bad, &cert),
            (good, &cert),
            (good, &cert),
            (bad, &cert),
            (bad, &cert),
        ];
        let expected = vec![true, false, true, false, true, true, false, false];
        let result =
            verifier.verify_certificates_bisect::<_, Sha256Digest>(&mut rng, &pairs, &Sequential);
        assert_eq!(result, expected);
    }

    #[test]
    fn test_bisect_all_invalid() {
        let mut rng = test_rng();
        let (schemes, verifier) = setup_ed25519(4);
        let cert = make_certificate(&schemes, MESSAGE);
        let bad = TestSubject {
            message: BAD_MESSAGE,
        };
        let pairs: Vec<_> = (0..4).map(|_| (bad, &cert)).collect();
        let result =
            verifier.verify_certificates_bisect::<_, Sha256Digest>(&mut rng, &pairs, &Sequential);
        assert_eq!(result, vec![false; 4]);
    }

    #[test]
    fn test_bisect_single_valid() {
        let mut rng = test_rng();
        let (schemes, verifier) = setup_ed25519(4);
        let cert = make_certificate(&schemes, MESSAGE);
        let pairs = vec![(TestSubject { message: MESSAGE }, &cert)];
        let result =
            verifier.verify_certificates_bisect::<_, Sha256Digest>(&mut rng, &pairs, &Sequential);
        assert_eq!(result, vec![true]);
    }

    #[test]
    fn test_bisect_single_invalid() {
        let mut rng = test_rng();
        let (schemes, verifier) = setup_ed25519(4);
        let cert = make_certificate(&schemes, MESSAGE);
        let pairs = vec![(
            TestSubject {
                message: BAD_MESSAGE,
            },
            &cert,
        )];
        let result =
            verifier.verify_certificates_bisect::<_, Sha256Digest>(&mut rng, &pairs, &Sequential);
        assert_eq!(result, vec![false]);
    }

    #[test]
    fn test_scoped_verifies_and_into_scheme() {
        let mut rng = test_rng();
        let (schemes, verifier) = setup_ed25519(4);
        let cert = make_certificate(&schemes, MESSAGE);
        let subject = TestSubject { message: MESSAGE };

        let as_verifier = Scoped::verifier(Arc::new(verifier));
        let as_scheme = Scoped::scheme(Arc::new(schemes[0].clone()));

        // Both scopes verify a valid certificate through the `Verifier` impl.
        assert!(as_verifier.verify_certificate::<_, Sha256Digest>(
            &mut rng,
            subject,
            &cert,
            &Sequential,
        ));
        assert!(as_scheme.verify_certificate::<_, Sha256Digest>(
            &mut rng,
            subject,
            &cert,
            &Sequential,
        ));
        let pairs = [(subject, &cert)];
        assert!(as_verifier.verify_certificates::<_, Sha256Digest, _>(
            &mut rng,
            non_empty![@pairs.iter().copied()],
            &Sequential,
        ));
        assert_eq!(
            <Scoped<Ed25519Scheme> as Verifier>::is_batchable(),
            <Ed25519Scheme as Verifier>::is_batchable(),
        );
        assert_eq!(
            as_verifier.certificate_codec_config(),
            schemes[0].certificate_codec_config(),
        );
        for participants in [0, 4, 128] {
            assert_eq!(
                <Scoped<Ed25519Scheme> as Verifier>::max_certificate_size(participants),
                <Ed25519Scheme as Verifier>::max_certificate_size(participants),
            );
        }
        let _ = <Scoped<Ed25519Scheme> as Verifier>::certificate_codec_config_unbounded();

        // A verify-only scope never yields its scheme; a full scope always does.
        assert!(as_verifier.into_scheme().is_none());
        assert!(as_scheme.into_scheme().is_some());

        let provider = ConstantProvider::<_, ()>::new(schemes[0].clone());
        assert!(provider.scoped(()).is_some());
        assert!(provider.scheme(()).is_some());
    }

    #[cfg(feature = "bls12381")]
    #[allow(dead_code)]
    mod threshold {
        use super::TestSubject;
        use crate::impl_certificate_bls12381_threshold;
        use commonware_utils::N3f1;

        impl_certificate_bls12381_threshold!(TestSubject, Vec<u8>, N3f1);
    }

    #[cfg(feature = "bls12381")]
    #[allow(dead_code)]
    mod multisig {
        use super::TestSubject;
        use crate::impl_certificate_bls12381_multisig;
        use commonware_utils::N3f1;

        impl_certificate_bls12381_multisig!(TestSubject, Vec<u8>, N3f1);
    }

    const SUBJECT: TestSubject = TestSubject {
        message: b"subject",
    };
    const OTHER_SUBJECT: TestSubject = TestSubject {
        message: b"other-subject",
    };

    #[cfg(feature = "bls12381")]
    const THRESHOLD_NAMESPACE: &[u8] =
        b"_COMMONWARE_CRYPTOGRAPHY_CERTIFICATE_THRESHOLD_OPTIMISTIC_ASSEMBLE";
    #[cfg(feature = "bls12381")]
    const MULTISIG_NAMESPACE: &[u8] =
        b"_COMMONWARE_CRYPTOGRAPHY_CERTIFICATE_MULTISIG_OPTIMISTIC_ASSEMBLE";
    #[cfg(feature = "bls12381")]
    const MULTISIG_POP_NAMESPACE: &[u8] =
        b"_COMMONWARE_CRYPTOGRAPHY_CERTIFICATE_MULTISIG_OPTIMISTIC_ASSEMBLE_POP";

    #[cfg(feature = "bls12381")]
    fn threshold_signers<V: Variant>(
        rng: &mut impl CryptoRng,
        n: u32,
    ) -> Vec<threshold::Scheme<crate::ed25519::PublicKey, V>> {
        let participants: Set<crate::ed25519::PublicKey> = (0..n)
            .map(|_| PrivateKey::random(&mut *rng).public_key())
            .try_collect()
            .unwrap();
        let (polynomial, shares) =
            dkg::deal_anonymous::<V, N3f1>(&mut *rng, Mode::NonZeroCounter, NZU32!(n));
        shares
            .into_iter()
            .map(|share| {
                threshold::Scheme::signer(
                    THRESHOLD_NAMESPACE,
                    participants.clone(),
                    polynomial.clone(),
                    share,
                )
                .unwrap()
            })
            .collect()
    }

    #[cfg(feature = "bls12381")]
    fn multisig_signers<V: Variant>(
        rng: &mut impl CryptoRng,
        n: u32,
    ) -> Vec<multisig::Scheme<crate::ed25519::PublicKey, V>> {
        let identity_keys: Vec<_> = (0..n).map(|_| PrivateKey::random(&mut *rng)).collect();
        let signing_keys: Vec<_> = (0..n).map(|_| BlsPrivate::random(&mut *rng)).collect();
        let signing_publics: Vec<_> = signing_keys.iter().map(compute_public::<V>).collect();

        for (private, public) in signing_keys.iter().zip(&signing_publics) {
            let proof = sign_proof_of_possession::<V>(private, MULTISIG_POP_NAMESPACE);
            verify_proof_of_possession::<V>(public, MULTISIG_POP_NAMESPACE, &proof)
                .expect("proof of possession must verify");
        }

        let participants: BiMap<_, _> = identity_keys
            .iter()
            .map(|key| key.public_key())
            .zip(signing_publics)
            .try_collect()
            .unwrap();
        signing_keys
            .into_iter()
            .map(|private| {
                multisig::Scheme::signer(MULTISIG_NAMESPACE, participants.clone(), private)
                    .expect("signer must be a participant")
            })
            .collect()
    }

    #[cfg(feature = "bls12381")]
    fn threshold_success<V: Variant>() {
        let mut rng = test_rng();
        let schemes = threshold_signers::<V>(&mut rng, 5);
        let quorum = N3f1::quorum(schemes.len()) as usize;
        let attestations: Vec<_> = schemes
            .iter()
            .take(quorum)
            .map(|scheme| scheme.sign::<Sha256Digest>(SUBJECT).unwrap())
            .collect();
        let expected = schemes[0]
            .assemble(non_empty![@attestations.clone()], &Sequential)
            .unwrap();
        let prior: Vec<_> = attestations[..1]
            .iter()
            .cloned()
            .map(Recording::outer)
            .collect();
        let calls = Arc::new(RecordingCalls::default());
        let verifier = Recording {
            inner: schemes[0].clone(),
            calls: Arc::clone(&calls),
        };

        let result = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
            &mut rng,
            SUBJECT,
            attestations[1..].iter().cloned().map(Recording::outer),
            &prior,
            &Sequential,
        );
        let certificate = result.ok().expect("valid quorum must certify");
        assert_eq!(certificate, expected);
        assert!(calls.attestations.lock().is_empty());
        assert!(schemes[0].verify_certificate::<_, Sha256Digest>(
            &mut rng,
            SUBJECT,
            &certificate,
            &Sequential,
        ));
        assert!(!schemes[0].verify_certificate::<_, Sha256Digest>(
            &mut rng,
            OTHER_SUBJECT,
            &certificate,
            &Sequential,
        ));

        // Threshold recovery uses the lowest quorum of signer indices.
        let unused_bad = schemes[quorum].sign::<Sha256Digest>(OTHER_SUBJECT).unwrap();
        let pending: Vec<_> = attestations
            .into_iter()
            .chain([unused_bad])
            .map(Recording::outer)
            .collect();
        let result = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
            &mut rng,
            SUBJECT,
            pending,
            std::iter::empty(),
            &Sequential,
        );
        assert_eq!(result.ok(), Some(expected));
        assert!(calls.attestations.lock().is_empty());
    }

    #[cfg(feature = "bls12381")]
    #[test]
    fn test_threshold_recovers_exact_certificate_with_verified_attestations() {
        threshold_success::<MinPk>();
        threshold_success::<MinSig>();
    }

    #[cfg(feature = "bls12381")]
    fn multisig_optimistic_assemble_uses_one_certificate_check<V: Variant>() {
        let mut rng = test_rng();
        let schemes = multisig_signers::<V>(&mut rng, 5);
        let quorum = N3f1::quorum(schemes.len()) as usize;
        let attestations: Vec<_> = schemes
            .iter()
            .take(quorum)
            .map(|scheme| scheme.sign::<Sha256Digest>(SUBJECT).unwrap())
            .collect();
        let prior: Vec<_> = attestations[..1]
            .iter()
            .cloned()
            .map(Recording::outer)
            .collect();
        let calls = Arc::new(RecordingCalls::default());
        let verifier = Recording {
            inner: schemes[0].clone(),
            calls: Arc::clone(&calls),
        };

        let certificate = verifier
            .optimistic_assemble::<_, Sha256Digest, _, _>(
                &mut rng,
                SUBJECT,
                attestations[1..].iter().cloned().map(Recording::outer),
                &prior,
                &Sequential,
            )
            .ok()
            .expect("valid mixed quorum must certify");

        assert_eq!(calls.certificates.load(Ordering::Relaxed), 1);
        assert!(calls.attestations.lock().is_empty());
        assert!(schemes[0].verify_certificate::<_, Sha256Digest>(
            &mut rng,
            SUBJECT,
            &certificate,
            &Sequential,
        ));
        assert!(!schemes[0].verify_certificate::<_, Sha256Digest>(
            &mut rng,
            OTHER_SUBJECT,
            &certificate,
            &Sequential,
        ));
    }

    #[cfg(feature = "bls12381")]
    #[test]
    fn test_multisig_optimistic_assemble_uses_one_certificate_check() {
        multisig_optimistic_assemble_uses_one_certificate_check::<MinPk>();
        multisig_optimistic_assemble_uses_one_certificate_check::<MinSig>();
    }

    #[test]
    fn test_optimistic_assemble_individual_inputs() {
        let mut rng = test_rng();
        let (schemes, verifier) = setup_ed25519(5);
        let empty = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
            &mut rng,
            SUBJECT,
            Vec::new(),
            std::iter::empty(),
            &Sequential,
        );
        let verification = empty.unwrap_err();
        assert!(verification.verified.is_empty());
        assert!(verification.invalid.is_empty());

        let pending: Vec<_> = schemes
            .iter()
            .map(|scheme| scheme.sign::<Sha256Digest>(SUBJECT).unwrap())
            .collect();
        let certificate = verifier
            .optimistic_assemble::<_, Sha256Digest, _, _>(
                &mut rng,
                SUBJECT,
                pending,
                std::iter::empty(),
                &Sequential,
            )
            .ok()
            .expect("valid quorum must certify");
        assert!(verifier.verify_certificate::<_, Sha256Digest>(
            &mut rng,
            SUBJECT,
            &certificate,
            &Sequential,
        ));

        let pending: Vec<_> = schemes
            .iter()
            .enumerate()
            .map(|(i, scheme)| {
                scheme
                    .sign::<Sha256Digest>(if i == 0 { OTHER_SUBJECT } else { SUBJECT })
                    .unwrap()
            })
            .collect();
        let signers: Vec<_> = pending.iter().map(|a| a.signer).collect();
        let result = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
            &mut rng,
            SUBJECT,
            pending,
            std::iter::empty(),
            &Sequential,
        );
        let verification = result.unwrap_err();
        assert_eq!(verification.invalid, vec![signers[0]]);
        assert_eq!(
            verification
                .verified
                .iter()
                .map(|a| a.signer)
                .collect::<Vec<_>>(),
            signers[1..]
        );
        let certificate = verifier
            .assemble(non_empty![@verification.verified], &Sequential)
            .unwrap();
        assert!(verifier.verify_certificate::<_, Sha256Digest>(
            &mut rng,
            SUBJECT,
            &certificate,
            &Sequential,
        ));
    }

    #[test]
    fn test_optimistic_assemble_individual_quorum() {
        let mut rng = test_rng();
        let (schemes, verifier) = setup_ed25519(5);
        let quorum = N3f1::quorum(schemes.len()) as usize;
        let attestations: Vec<_> = schemes
            .iter()
            .take(quorum)
            .map(|s| s.sign::<Sha256Digest>(SUBJECT).unwrap())
            .collect();

        // Both pending-only and verified-only inputs require quorum. On failure,
        // the result contains only pending attestations, never retained inputs.
        for count in [0, quorum - 1, quorum] {
            for pending in [0, count] {
                let result = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
                    &mut rng,
                    SUBJECT,
                    attestations[..pending].iter().cloned(),
                    &attestations[pending..count],
                    &Sequential,
                );
                assert_eq!(result.is_ok(), count == quorum);
                match result {
                    Ok(certificate) => assert!(verifier.verify_certificate::<_, Sha256Digest>(
                        &mut rng,
                        SUBJECT,
                        &certificate,
                        &Sequential,
                    )),
                    Err(verification) => {
                        assert_eq!(verification.verified, attestations[..pending]);
                        assert!(verification.invalid.is_empty());
                    }
                }
            }
        }
    }

    #[test]
    fn test_optimistic_assemble_empty_committee() {
        let mut rng = test_rng();
        let (_, verifier) = setup_ed25519(0);
        let (schemes, _) = setup_ed25519(1);
        let unknown = schemes[0].sign::<Sha256Digest>(SUBJECT).unwrap();
        for pending in [Vec::new(), vec![unknown]] {
            let expected: Vec<_> = pending.iter().map(|a| a.signer).collect();
            let result = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
                &mut rng,
                SUBJECT,
                pending,
                std::iter::empty(),
                &Sequential,
            );
            let verification = result.unwrap_err();
            assert!(verification.verified.is_empty());
            assert_eq!(verification.invalid, expected);
        }
    }

    #[cfg(feature = "bls12381")]
    #[derive(Debug, Default)]
    struct RecordingCalls {
        attestations: Mutex<Vec<Vec<Participant>>>,
        assemblies: AtomicUsize,
        certificates: AtomicUsize,
    }

    #[cfg(feature = "bls12381")]
    #[derive(Clone, Debug)]
    struct Recording<S> {
        inner: S,
        calls: Arc<RecordingCalls>,
    }

    #[cfg(feature = "bls12381")]
    impl<S: Scheme> Recording<S> {
        fn inner(attestation: Attestation<Self>) -> Attestation<S> {
            Attestation {
                signer: attestation.signer,
                signature: attestation.signature,
            }
        }

        fn outer(attestation: Attestation<S>) -> Attestation<Self> {
            Attestation {
                signer: attestation.signer,
                signature: attestation.signature,
            }
        }
    }

    #[cfg(feature = "bls12381")]
    impl<S: Scheme> Verifier for Recording<S> {
        type Subject<'a, D: Digest> = S::Subject<'a, D>;
        type Faults = S::Faults;
        type PublicKey = S::PublicKey;
        type Certificate = S::Certificate;

        fn verify_certificate<R, D>(
            &self,
            rng: &mut R,
            subject: Self::Subject<'_, D>,
            certificate: &Self::Certificate,
            strategy: &impl Strategy,
        ) -> bool
        where
            R: CryptoRng,
            D: Digest,
        {
            self.calls.certificates.fetch_add(1, Ordering::Relaxed);
            self.inner
                .verify_certificate(rng, subject, certificate, strategy)
        }

        fn is_batchable() -> bool {
            S::is_batchable()
        }

        fn max_certificate_size(participants: u32) -> usize {
            S::max_certificate_size(participants)
        }

        fn certificate_codec_config(&self) -> <Self::Certificate as Read>::Cfg {
            self.inner.certificate_codec_config()
        }

        fn certificate_codec_config_unbounded() -> <Self::Certificate as Read>::Cfg {
            S::certificate_codec_config_unbounded()
        }
    }

    #[cfg(feature = "bls12381")]
    impl<S: Scheme> Scheme for Recording<S> {
        type Signature = S::Signature;

        fn me(&self) -> Option<Membership> {
            self.inner.me()
        }

        fn participants(&self) -> &Set<Self::PublicKey> {
            self.inner.participants()
        }

        fn sign<D: Digest>(&self, subject: Self::Subject<'_, D>) -> Option<Attestation<Self>> {
            self.inner.sign(subject).map(Self::outer)
        }

        fn verify_attestation<R, D>(
            &self,
            rng: &mut R,
            subject: Self::Subject<'_, D>,
            attestation: &Attestation<Self>,
            strategy: &impl Strategy,
        ) -> bool
        where
            R: CryptoRng,
            D: Digest,
        {
            self.calls
                .attestations
                .lock()
                .push(vec![attestation.signer]);
            self.inner
                .verify_attestation(rng, subject, &Self::inner(attestation.clone()), strategy)
        }

        fn verify_attestations<R, D, I>(
            &self,
            rng: &mut R,
            subject: Self::Subject<'_, D>,
            attestations: I,
            strategy: &impl Strategy,
        ) -> Verification<Self>
        where
            R: CryptoRng,
            D: Digest,
            I: IntoIterator<Item = Attestation<Self>>,
            I::IntoIter: Send,
        {
            let attestations: Vec<_> = attestations.into_iter().collect();
            self.calls
                .attestations
                .lock()
                .push(attestations.iter().map(|a| a.signer).collect());
            let result = self.inner.verify_attestations(
                rng,
                subject,
                attestations.into_iter().map(Self::inner),
                strategy,
            );
            Verification::new(
                result.verified.into_iter().map(Self::outer).collect(),
                result.invalid,
            )
        }

        fn optimistic_assemble<'a, R, D, I, J>(
            &self,
            rng: &mut R,
            subject: Self::Subject<'_, D>,
            pending: I,
            verified: J,
            strategy: &impl Strategy,
        ) -> Result<Self::Certificate, Verification<Self>>
        where
            R: CryptoRng,
            D: Digest,
            I: IntoIterator<Item = Attestation<Self>>,
            I::IntoIter: ExactSizeIterator + Send,
            J: IntoIterator<Item = &'a Attestation<Self>>,
            J::IntoIter: Send,
        {
            crate::certificate::optimistic_assemble::<Self, _, D, _, _>(
                self, rng, subject, pending, verified, strategy,
            )
        }

        fn assemble<I>(
            &self,
            attestations: NonEmpty<I>,
            strategy: &impl Strategy,
        ) -> Result<Self::Certificate, AssemblyError>
        where
            I: Iterator<Item = Attestation<Self>> + Send,
        {
            self.calls.assemblies.fetch_add(1, Ordering::Relaxed);
            self.inner.assemble(
                non_empty![@attestations.into_iter().map(Self::inner)],
                strategy,
            )
        }

        fn is_attributable() -> bool {
            S::is_attributable()
        }
    }

    #[cfg(feature = "bls12381")]
    fn expected_halves(len: usize) -> Vec<Vec<Participant>> {
        let middle = len.div_ceil(2);
        let first = (0..middle).map(Participant::from_usize).collect();
        if middle == len {
            vec![first]
        } else {
            vec![first, (middle..len).map(Participant::from_usize).collect()]
        }
    }

    #[cfg(feature = "bls12381")]
    #[test]
    fn test_rejected_certificate_verifies_pending_halves_directly() {
        for n in [1, 5, 7] {
            let mut rng = test_rng();
            let schemes = threshold_signers::<MinPk>(&mut rng, n);
            let calls = Arc::new(RecordingCalls::default());
            let verifier = Recording {
                inner: schemes[0].clone(),
                calls: Arc::clone(&calls),
            };
            let quorum = N3f1::quorum(n) as usize;
            let pending: Vec<_> = schemes
                .iter()
                .take(quorum)
                .map(|s| Recording::outer(s.sign::<Sha256Digest>(OTHER_SUBJECT).unwrap()))
                .collect();
            let result = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
                &mut rng,
                SUBJECT,
                pending,
                std::iter::empty(),
                &Sequential,
            );
            let verification = result.unwrap_err();
            assert!(verification.verified.is_empty());
            assert_eq!(
                verification.invalid,
                (0..quorum).map(Participant::from_usize).collect::<Vec<_>>()
            );
            assert_eq!(*calls.attestations.lock(), expected_halves(quorum));
        }
    }

    #[cfg(feature = "bls12381")]
    #[test]
    fn test_malformed_assembly_falls_back_to_pending_halves() {
        let mut rng = test_rng();
        let schemes = threshold_signers::<MinPk>(&mut rng, 5);
        let quorum = N3f1::quorum(schemes.len()) as usize;
        for count in [quorum, schemes.len()] {
            let calls = Arc::new(RecordingCalls::default());
            let verifier = Recording {
                inner: schemes[0].clone(),
                calls: Arc::clone(&calls),
            };
            let mut pending: Vec<_> = schemes
                .iter()
                .take(count)
                .map(|s| Recording::outer(s.sign::<Sha256Digest>(SUBJECT).unwrap()))
                .collect();
            let mut malformed = Bytes::from_static(&[0]);
            pending[0].signature = Lazy::deferred(&mut malformed, ());
            let result = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
                &mut rng,
                SUBJECT,
                pending,
                std::iter::empty(),
                &Sequential,
            );
            let verification = result.unwrap_err();
            assert_eq!(verification.verified.len(), count - 1);
            assert_eq!(verification.invalid, vec![Participant::new(0)]);
            assert_eq!(*calls.attestations.lock(), expected_halves(count));
            if count > quorum {
                let certificate = verifier
                    .assemble(non_empty![@verification.verified], &Sequential)
                    .unwrap();
                assert!(verifier.verify_certificate::<_, Sha256Digest>(
                    &mut rng,
                    SUBJECT,
                    &certificate,
                    &Sequential,
                ));
            }
        }
    }

    #[cfg(feature = "bls12381")]
    #[test]
    fn test_optimistic_assemble_retains_verified_inputs() {
        let mut rng = test_rng();
        let schemes = threshold_signers::<MinPk>(&mut rng, 5);
        let mut prior: Vec<_> = schemes[..2]
            .iter()
            .map(|s| Recording::outer(s.sign::<Sha256Digest>(SUBJECT).unwrap()))
            .collect();
        let accepted = Recording::outer(schemes[2].sign::<Sha256Digest>(SUBJECT).unwrap());
        let rejected = Recording::outer(schemes[3].sign::<Sha256Digest>(OTHER_SUBJECT).unwrap());
        let invalid = rejected.signer;
        let calls = Arc::new(RecordingCalls::default());
        let verifier = Recording {
            inner: schemes[0].clone(),
            calls: Arc::clone(&calls),
        };
        let result = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
            &mut rng,
            SUBJECT,
            vec![accepted.clone(), rejected],
            &prior,
            &Sequential,
        );
        let verification = result.unwrap_err();
        assert_eq!(verification.verified, vec![accepted.clone()]);
        assert_eq!(verification.invalid, vec![invalid]);
        assert_eq!(
            *calls.attestations.lock(),
            vec![vec![accepted.signer], vec![invalid]]
        );

        prior.extend(verification.verified);
        calls.attestations.lock().clear();
        let replacement = Recording::outer(schemes[4].sign::<Sha256Digest>(SUBJECT).unwrap());
        let signer = replacement.signer;
        let verification = verifier.verify_attestations::<_, Sha256Digest, _>(
            &mut rng,
            SUBJECT,
            vec![replacement.clone()],
            &Sequential,
        );
        assert_eq!(verification.verified, vec![replacement]);
        assert!(verification.invalid.is_empty());
        assert_eq!(*calls.attestations.lock(), vec![vec![signer]]);
        prior.extend(verification.verified);
        let certificate = verifier.assemble(non_empty![@prior], &Sequential).unwrap();
        assert!(verifier.verify_certificate::<_, Sha256Digest>(
            &mut rng,
            SUBJECT,
            &certificate,
            &Sequential,
        ));
    }

    #[cfg(feature = "bls12381")]
    #[test]
    fn test_optimistic_assemble_with_verified_votes() {
        let mut rng = test_rng();
        let schemes = threshold_signers::<MinPk>(&mut rng, 5);
        let quorum = N3f1::quorum(schemes.len()) as usize;
        let attestations: Vec<_> = schemes[..quorum]
            .iter()
            .map(|scheme| scheme.sign::<Sha256Digest>(SUBJECT).unwrap())
            .collect();

        for pending_len in [0, 1, 2] {
            // Retained votes are authenticated for this configuration and subject.
            // The remaining votes cover empty, singleton, and evenly split inputs.
            let (prior, pending) = attestations.split_at(quorum - pending_len);
            let prior = schemes[0].verify_attestations::<_, Sha256Digest, _>(
                &mut rng,
                SUBJECT,
                prior.iter().cloned(),
                &Sequential,
            );
            assert!(prior.invalid.is_empty());
            let prior: Vec<_> = prior.verified.into_iter().map(Recording::outer).collect();
            let calls = Arc::new(RecordingCalls::default());
            let verifier = Recording {
                inner: schemes[0].clone(),
                calls: Arc::clone(&calls),
            };
            let certificate = verifier
                .optimistic_assemble::<_, Sha256Digest, _, _>(
                    &mut rng,
                    SUBJECT,
                    pending.iter().cloned().map(Recording::outer),
                    &prior,
                    &Sequential,
                )
                .ok()
                .expect("verified quorum must certify");

            // Pending votes require certificate authentication, even when most
            // inputs are already verified. A verified-only quorum needs assembly alone.
            assert_eq!(calls.assemblies.load(Ordering::Relaxed), 1);
            assert_eq!(
                calls.certificates.load(Ordering::Relaxed),
                usize::from(pending_len != 0)
            );
            assert!(calls.attestations.lock().is_empty());
            assert!(schemes[0].verify_certificate::<_, Sha256Digest>(
                &mut rng,
                SUBJECT,
                &certificate,
                &Sequential,
            ));
        }
    }

    #[cfg(feature = "bls12381")]
    #[test]
    fn test_optimistic_assemble_retries_with_replacements() {
        let mut rng = test_rng();
        let schemes = threshold_signers::<MinPk>(&mut rng, 10);
        let quorum = N3f1::quorum(schemes.len()) as usize;

        for failures in [1, 2] {
            let calls = Arc::new(RecordingCalls::default());
            let verifier = Recording {
                inner: schemes[0].clone(),
                calls: Arc::clone(&calls),
            };

            // Ten participants permit three faulty signers across these attempts.
            // A failed initial quorum retains the local vote and its valid peer votes.
            let own = schemes[0].verify_attestations::<_, Sha256Digest, _>(
                &mut rng,
                SUBJECT,
                [schemes[0].sign::<Sha256Digest>(SUBJECT).unwrap()],
                &Sequential,
            );
            assert!(own.invalid.is_empty());
            let mut prior: Vec<_> = own.verified.into_iter().map(Recording::outer).collect();
            let pending: Vec<_> = schemes[1..quorum]
                .iter()
                .enumerate()
                .map(|(index, scheme)| {
                    let subject = if index + 1 >= quorum - failures {
                        OTHER_SUBJECT
                    } else {
                        SUBJECT
                    };
                    Recording::outer(scheme.sign::<Sha256Digest>(subject).unwrap())
                })
                .collect();
            let result = verifier
                .optimistic_assemble::<_, Sha256Digest, _, _>(
                    &mut rng,
                    SUBJECT,
                    pending,
                    &prior,
                    &Sequential,
                )
                .unwrap_err();
            assert_eq!(result.invalid.len(), failures);
            prior.extend(result.verified);
            assert_eq!(prior.len(), quorum - failures);

            // A new faulty signer is mixed with any honest replacements. The
            // candidate fails authentication, so fallback identifies the bad vote.
            let pending: Vec<_> = schemes[quorum..quorum + failures]
                .iter()
                .enumerate()
                .map(|(index, scheme)| {
                    let subject = if index + 1 == failures {
                        OTHER_SUBJECT
                    } else {
                        SUBJECT
                    };
                    Recording::outer(scheme.sign::<Sha256Digest>(subject).unwrap())
                })
                .collect();
            let signers: Vec<_> = pending.iter().map(|vote| vote.signer).collect();
            let invalid = *signers.last().unwrap();
            calls.attestations.lock().clear();
            calls.assemblies.store(0, Ordering::Relaxed);
            calls.certificates.store(0, Ordering::Relaxed);
            let result = verifier
                .optimistic_assemble::<_, Sha256Digest, _, _>(
                    &mut rng,
                    SUBJECT,
                    pending,
                    &prior,
                    &Sequential,
                )
                .unwrap_err();
            assert_eq!(result.invalid, vec![invalid]);
            assert_eq!(result.verified.len(), failures - 1);
            assert_eq!(calls.assemblies.load(Ordering::Relaxed), 1);
            assert_eq!(calls.certificates.load(Ordering::Relaxed), 1);
            assert_eq!(
                *calls.attestations.lock(),
                signers
                    .into_iter()
                    .map(|signer| vec![signer])
                    .collect::<Vec<_>>()
            );
            prior.extend(result.verified);
            assert_eq!(prior.len(), quorum - 1);

            // The last honest replacement completes the same authenticated subject.
            let replacement = Recording::outer(
                schemes[quorum + failures]
                    .sign::<Sha256Digest>(SUBJECT)
                    .unwrap(),
            );
            calls.attestations.lock().clear();
            calls.assemblies.store(0, Ordering::Relaxed);
            calls.certificates.store(0, Ordering::Relaxed);
            let certificate = verifier
                .optimistic_assemble::<_, Sha256Digest, _, _>(
                    &mut rng,
                    SUBJECT,
                    [replacement],
                    &prior,
                    &Sequential,
                )
                .ok()
                .expect("valid replacement must certify");
            assert_eq!(calls.assemblies.load(Ordering::Relaxed), 1);
            assert_eq!(calls.certificates.load(Ordering::Relaxed), 1);
            assert!(calls.attestations.lock().is_empty());
            assert!(schemes[0].verify_certificate::<_, Sha256Digest>(
                &mut rng,
                SUBJECT,
                &certificate,
                &Sequential,
            ));
            assert!(!schemes[0].verify_certificate::<_, Sha256Digest>(
                &mut rng,
                OTHER_SUBJECT,
                &certificate,
                &Sequential,
            ));
        }
    }

    #[cfg(feature = "bls12381")]
    #[test]
    fn test_optimistic_assemble_below_quorum() {
        let mut rng = test_rng();
        let schemes = threshold_signers::<MinPk>(&mut rng, 5);
        let pending: Vec<_> = schemes[..2]
            .iter()
            .map(|s| Recording::outer(s.sign::<Sha256Digest>(SUBJECT).unwrap()))
            .collect();
        let expected = pending.clone();
        let calls = Arc::new(RecordingCalls::default());
        let verifier = Recording {
            inner: schemes[0].clone(),
            calls: Arc::clone(&calls),
        };
        let result = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
            &mut rng,
            SUBJECT,
            pending,
            std::iter::empty(),
            &Sequential,
        );
        let verification = result.unwrap_err();
        assert_eq!(verification.verified, expected);
        assert!(verification.invalid.is_empty());
        assert_eq!(*calls.attestations.lock(), expected_halves(expected.len()));
    }

    #[cfg(feature = "bls12381")]
    #[test]
    fn test_optimistic_assemble_unknown_pending_signer() {
        let mut rng = test_rng();
        let schemes = threshold_signers::<MinPk>(&mut rng, 5);
        let quorum = N3f1::quorum(schemes.len()) as usize;
        let mut pending: Vec<_> = schemes
            .iter()
            .take(quorum)
            .map(|s| Recording::outer(s.sign::<Sha256Digest>(SUBJECT).unwrap()))
            .collect();
        pending[0].signer = Participant::new(999);
        let calls = Arc::new(RecordingCalls::default());
        let verifier = Recording {
            inner: schemes[0].clone(),
            calls: Arc::clone(&calls),
        };
        let result = verifier.optimistic_assemble::<_, Sha256Digest, _, _>(
            &mut rng,
            SUBJECT,
            pending,
            std::iter::empty(),
            &Sequential,
        );
        let verification = result.unwrap_err();
        assert_eq!(verification.verified.len(), quorum - 1);
        assert_eq!(verification.invalid, vec![Participant::new(999)]);
        assert_eq!(
            *calls.attestations.lock(),
            vec![
                vec![Participant::new(999), Participant::new(1)],
                vec![Participant::new(2), Participant::new(3)],
            ]
        );
    }

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

        commonware_conformance::conformance_tests! {
            CodecConformance<Signers>,
            CodecConformance<Attestation<Scheme>>,
        }
    }
}