bicycl-rs 0.1.0

Safe Rust wrapper for BICYCL C API
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
//! Safe Rust bindings for the [BICYCL] cryptographic library.
//!
//! BICYCL implements class-group-based cryptographic schemes including:
//! - **Paillier** homomorphic encryption
//! - **Joye-Libert** homomorphic encryption
//! - **CL_HSMqk / CL_HSM2k** class-group encryption with homomorphic properties
//! - **ECDSA** signatures
//! - **Two-party ECDSA** threshold signing (2-of-2)
//! - **Threshold ECDSA** (t-of-n)
//! - **CL DLog proofs**
//!
//! # Build
//!
//! Requires CMake, GMP, and OpenSSL development headers at build time.
//!
//! # Thread safety
//!
//! The underlying C library is **not** thread-safe.  All wrapper types are
//! `!Send + !Sync` and must be used from a single thread.
//!
//! # License
//!
//! This crate is licensed under **GPL-3.0-or-later**.  Any crate or binary
//! that depends on it inherits the GPL-3.0 copyleft obligation.
//!
//! # Quick start
//!
//! ```no_run
//! use bicycl_rs::{Context, Error};
//!
//! fn main() -> Result<(), Error> {
//!     let ctx = Context::new()?;
//!     let mut rng = ctx.randgen_from_seed_decimal("12345")?;
//!     let paillier = ctx.paillier(512)?;
//!     let (sk, pk) = paillier.keygen(&ctx, &mut rng)?;
//!     let ct = paillier.encrypt_decimal(&ctx, &pk, &mut rng, "42")?;
//!     let plain = paillier.decrypt_decimal(&ctx, &pk, &sk, &ct)?;
//!     assert_eq!(plain, "42");
//!     Ok(())
//! }
//! ```
//!
//! [BICYCL]: https://gite.lirmm.fr/crypto/bicycl
#![deny(unsafe_op_in_unsafe_fn)]

mod error;

use core::ffi::{c_char, c_int, c_void};
use std::ffi::{CStr, CString};
use std::marker::PhantomData;
use std::ptr::NonNull;

pub use error::{Error, Result};

fn status_to_result(status: bicycl_rs_sys::bicycl_status_t) -> Result<()> {
    if status == bicycl_rs_sys::bicycl_status_t::BICYCL_OK {
        Ok(())
    } else {
        Err(Error::from_status(status))
    }
}

fn ffi_string_from_len<F>(mut f: F) -> Result<String>
where
    F: FnMut(*mut c_char, *mut usize) -> bicycl_rs_sys::bicycl_status_t,
{
    let buf = ffi_bytes_from_len(|buf, len| f(buf.cast::<c_char>(), len))?;
    let cstr = CStr::from_bytes_with_nul(&buf).map_err(|_| Error::Internal)?;
    Ok(cstr.to_str()?.to_owned())
}

fn ffi_bytes_from_len<F>(mut f: F) -> Result<Vec<u8>>
where
    F: FnMut(*mut u8, *mut usize) -> bicycl_rs_sys::bicycl_status_t,
{
    let mut len: usize = 0;
    let first = f(std::ptr::null_mut(), &mut len as *mut usize);
    if first != bicycl_rs_sys::bicycl_status_t::BICYCL_ERR_BUFFER_TOO_SMALL
        && first != bicycl_rs_sys::bicycl_status_t::BICYCL_OK
    {
        return Err(Error::from_status(first));
    }

    let mut buf = vec![0_u8; len];
    if len == 0 {
        return Ok(buf);
    }

    let second = f(buf.as_mut_ptr(), &mut len as *mut usize);
    status_to_result(second)?;
    buf.truncate(len);
    Ok(buf)
}

/// Returns the ABI version of the linked `bicycl_capi` C library.
///
/// Compare against [`bicycl_rs_sys::BICYCL_CAPI_VERSION`] to verify
/// the runtime library matches the headers this crate was compiled against.
pub fn abi_version() -> u32 {
    unsafe { bicycl_rs_sys::bicycl_get_abi_version() }
}

/// Returns the human-readable version string of the linked `bicycl_capi` library.
///
/// Returns an empty string if the library returns a null pointer.
pub fn version() -> &'static str {
    unsafe {
        let p = bicycl_rs_sys::bicycl_get_version();
        if p.is_null() {
            return "";
        }
        CStr::from_ptr(p).to_str().unwrap_or("")
    }
}

/// Overwrites the given byte buffer with zeros using a memory-safe barrier.
///
/// Unlike a plain `buf.fill(0)`, this call is guaranteed not to be optimised
/// away by the compiler, making it suitable for clearing sensitive key material.
pub fn zeroize(buf: &mut [u8]) {
    unsafe {
        bicycl_rs_sys::bicycl_zeroize(buf.as_mut_ptr().cast::<c_void>(), buf.len());
    }
}

/// The central BICYCL library context.
///
/// All cryptographic objects and operations require a reference to a `Context`.
/// The context acts as an error sink: it stores the last error message produced
/// by the C library and is passed to every operation so the library has
/// somewhere to record diagnostic information.
///
/// All derived objects (`RandGen`, scheme instances, keys, ciphertexts, etc.)
/// own their data independently and do **not** hold pointers into the context's
/// memory, so their drop order relative to `Context` does not affect memory
/// safety.  `Context` is `!Send + !Sync` because the underlying C library is
/// not thread-safe; all objects must be used from a single thread.
#[derive(Debug)]
pub struct Context {
    raw: NonNull<bicycl_rs_sys::bicycl_context_t>,
    _marker: PhantomData<*mut ()>,
}

impl Context {
    /// Creates a new library context.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying C allocation fails.
    pub fn new() -> Result<Self> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe { bicycl_rs_sys::bicycl_context_new(&mut raw as *mut _) };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_context_new returned null");
        Ok(Self {
            raw,
            _marker: PhantomData,
        })
    }

    /// Returns the last error message stored by the C library, or `""` if none.
    pub fn last_error(&self) -> &str {
        unsafe {
            let p = bicycl_rs_sys::bicycl_context_last_error(self.raw.as_ptr());
            if p.is_null() {
                return "";
            }
            CStr::from_ptr(p).to_str().unwrap_or("")
        }
    }

    /// Clears the last error message stored in the context.
    pub fn clear_error(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_context_clear_error(self.raw.as_ptr()) }
    }

    /// Creates a deterministic random number generator seeded from a decimal string.
    ///
    /// `seed_decimal` must be a valid decimal integer (e.g., `"12345"`).
    /// The same seed always produces the same sequence, which is useful for
    /// reproducible tests but **must not be used with a fixed seed in production**.
    pub fn randgen_from_seed_decimal(&self, seed_decimal: &str) -> Result<RandGen> {
        let seed_c = CString::new(seed_decimal)?;
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_randgen_new_from_seed_decimal(
                self.raw.as_ptr(),
                seed_c.as_ptr(),
                &mut raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_randgen_new_from_seed_decimal returned null");
        Ok(RandGen {
            raw,
            _marker: PhantomData,
        })
    }

    /// Creates a class group from a negative fundamental discriminant given as a decimal string.
    ///
    /// `discriminant_decimal` must be a negative integer (e.g., `"-23"`).
    pub fn classgroup_from_discriminant_decimal(
        &self,
        discriminant_decimal: &str,
    ) -> Result<ClassGroup> {
        let disc_c = CString::new(discriminant_decimal)?;
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_classgroup_new_from_discriminant_decimal(
                self.raw.as_ptr(),
                disc_c.as_ptr(),
                &mut raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw)
            .expect("bicycl_classgroup_new_from_discriminant_decimal returned null");
        Ok(ClassGroup {
            raw,
            _marker: PhantomData,
        })
    }

    /// Creates a Paillier cryptosystem instance with the given RSA modulus bit length.
    ///
    /// Typical values for `modulus_bits`: 512 (testing), 1024, 2048.
    pub fn paillier(&self, modulus_bits: u32) -> Result<Paillier> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_paillier_new(self.raw.as_ptr(), modulus_bits, &mut raw as *mut _)
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_paillier_new returned null");
        Ok(Paillier {
            raw,
            _marker: PhantomData,
        })
    }

    /// Creates a Joye-Libert cryptosystem instance.
    ///
    /// - `modulus_bits`: RSA modulus bit length (e.g., 1024, 2048).
    /// - `k`: plaintext bit length (must be ≤ `modulus_bits / 2`).
    pub fn joye_libert(&self, modulus_bits: u32, k: u32) -> Result<JoyeLibert> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_joye_libert_new(
                self.raw.as_ptr(),
                modulus_bits,
                k,
                &mut raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_joye_libert_new returned null");
        Ok(JoyeLibert {
            raw,
            _marker: PhantomData,
        })
    }

    /// Creates a CL_HSMqk instance.
    ///
    /// - `q_decimal`: the prime order `q` of the subgroup (decimal string).
    /// - `k`: the bit-size parameter `k` (plaintext space is `Z/q^k`).
    /// - `p_decimal`: the class-group prime `p` (decimal string).
    pub fn cl_hsmqk(&self, q_decimal: &str, k: u32, p_decimal: &str) -> Result<ClHsmqk> {
        let q_c = CString::new(q_decimal)?;
        let p_c = CString::new(p_decimal)?;
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsmqk_new(
                self.raw.as_ptr(),
                q_c.as_ptr(),
                k,
                p_c.as_ptr(),
                &mut raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_cl_hsmqk_new returned null");
        Ok(ClHsmqk {
            raw,
            _marker: PhantomData,
        })
    }

    /// Creates a CL_HSM2k instance.
    ///
    /// - `n_decimal`: the RSA-like composite modulus `n` (decimal string).
    /// - `k`: the bit-size parameter `k` (plaintext space is `Z/2^k`).
    pub fn cl_hsm2k(&self, n_decimal: &str, k: u32) -> Result<ClHsm2k> {
        let n_c = CString::new(n_decimal)?;
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsm2k_new(
                self.raw.as_ptr(),
                n_c.as_ptr(),
                k,
                &mut raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_cl_hsm2k_new returned null");
        Ok(ClHsm2k {
            raw,
            _marker: PhantomData,
        })
    }

    /// Creates an ECDSA instance at the given security level.
    ///
    /// `seclevel_bits` selects the elliptic curve (e.g., 112 → P-224, 128 → P-256).
    pub fn ecdsa(&self, seclevel_bits: u32) -> Result<Ecdsa> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_ecdsa_new(self.raw.as_ptr(), seclevel_bits, &mut raw as *mut _)
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_ecdsa_new returned null");
        Ok(Ecdsa {
            raw,
            _marker: PhantomData,
        })
    }

    /// Creates a new two-party ECDSA session at the given security level.
    ///
    /// Drive the session through the required keygen and sign rounds; see
    /// [`TwoPartyEcdsaSession`] for method details.
    pub fn two_party_ecdsa_session(
        &self,
        rng: &mut RandGen,
        seclevel_bits: u32,
    ) -> Result<TwoPartyEcdsaSession> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_two_party_ecdsa_session_new(
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                seclevel_bits,
                &mut raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_two_party_ecdsa_session_new returned null");
        Ok(TwoPartyEcdsaSession {
            raw,
            _state: PhantomData,
            _marker: PhantomData,
        })
    }

    /// Creates a new CL DLog proof session at the given security level.
    ///
    /// Use this for non-interactive zero-knowledge proofs of discrete
    /// logarithm in the class group.  See [`ClDlogSession`] for the
    /// prove/verify round methods.
    pub fn cl_dlog_session(&self, rng: &mut RandGen, seclevel_bits: u32) -> Result<ClDlogSession> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_session_new(
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                seclevel_bits,
                &mut raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_cl_dlog_session_new returned null");
        Ok(ClDlogSession {
            raw,
            _state: PhantomData,
            _marker: PhantomData,
        })
    }

    /// Creates a new threshold ECDSA session.
    ///
    /// - `n_players`: total number of participants.
    /// - `threshold_t`: minimum number of participants required to sign
    ///   (must satisfy `threshold_t < n_players`).
    pub fn threshold_ecdsa_session(
        &self,
        rng: &mut RandGen,
        seclevel_bits: u32,
        n_players: u32,
        threshold_t: u32,
    ) -> Result<ThresholdEcdsaSession> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_session_new(
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                seclevel_bits,
                n_players,
                threshold_t,
                &mut raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_threshold_ecdsa_session_new returned null");
        Ok(ThresholdEcdsaSession {
            raw,
            _state: PhantomData,
            _marker: PhantomData,
        })
    }
}

impl Drop for Context {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_context_free(self.raw.as_ptr()) }
    }
}

/// A deterministic pseudo-random number generator seeded from a decimal value.
///
/// Create via [`Context::randgen_from_seed_decimal`].
#[derive(Debug)]
pub struct RandGen {
    raw: NonNull<bicycl_rs_sys::bicycl_randgen_t>,
    _marker: PhantomData<*mut ()>,
}

impl Drop for RandGen {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_randgen_free(self.raw.as_ptr()) }
    }
}

/// An imaginary quadratic class group defined by its discriminant.
///
/// Create via [`Context::classgroup_from_discriminant_decimal`].
#[derive(Debug)]
pub struct ClassGroup {
    raw: NonNull<bicycl_rs_sys::bicycl_classgroup_t>,
    _marker: PhantomData<*mut ()>,
}

impl ClassGroup {
    /// Returns the identity element (principal form) of this class group.
    pub fn one(&self, ctx: &Context) -> Result<Qfi> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_classgroup_one(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                &mut raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_classgroup_one returned null");
        Ok(Qfi {
            raw,
            _marker: PhantomData,
        })
    }

    /// Computes the NUDUPL squaring of a QFI element (i.e., `input² = input ∘ input`).
    pub fn nudupl(&self, ctx: &Context, input: &Qfi) -> Result<Qfi> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_classgroup_nudupl(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                input.raw.as_ptr(),
                &mut raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_classgroup_nudupl returned null");
        Ok(Qfi {
            raw,
            _marker: PhantomData,
        })
    }
}

impl Drop for ClassGroup {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_classgroup_free(self.raw.as_ptr()) }
    }
}

/// A Quadratic Form element in a class group.
///
/// Obtained from [`ClassGroup::one`] or [`ClassGroup::nudupl`].
#[derive(Debug)]
pub struct Qfi {
    raw: NonNull<bicycl_rs_sys::bicycl_qfi_t>,
    _marker: PhantomData<*mut ()>,
}

impl Qfi {
    /// Returns `true` if this element is the identity element of the class group.
    pub fn is_one(&self, ctx: &Context) -> Result<bool> {
        let mut out: c_int = 0;
        let status = unsafe {
            bicycl_rs_sys::bicycl_qfi_is_one(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                &mut out as *mut _,
            )
        };
        status_to_result(status)?;
        Ok(out != 0)
    }

    /// Returns the discriminant of the class group this element belongs to, as a decimal string.
    pub fn discriminant_decimal(&self, ctx: &Context) -> Result<String> {
        ffi_string_from_len(|buf, len| unsafe {
            bicycl_rs_sys::bicycl_qfi_discriminant_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                buf,
                len,
            )
        })
    }
}

impl Drop for Qfi {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_qfi_free(self.raw.as_ptr()) }
    }
}

/// A Paillier homomorphic encryption scheme instance.
///
/// Create via [`Context::paillier`].
#[derive(Debug)]
pub struct Paillier {
    raw: NonNull<bicycl_rs_sys::bicycl_paillier_t>,
    _marker: PhantomData<*mut ()>,
}

/// A Paillier secret key.  Keep this private.
#[derive(Debug)]
pub struct PaillierSecretKey {
    raw: NonNull<bicycl_rs_sys::bicycl_paillier_sk_t>,
    _marker: PhantomData<*mut ()>,
}

/// A Paillier public key.  Safe to share.
#[derive(Debug)]
pub struct PaillierPublicKey {
    raw: NonNull<bicycl_rs_sys::bicycl_paillier_pk_t>,
    _marker: PhantomData<*mut ()>,
}

/// A Paillier ciphertext.
#[derive(Debug)]
pub struct PaillierCiphertext {
    raw: NonNull<bicycl_rs_sys::bicycl_paillier_ct_t>,
    _marker: PhantomData<*mut ()>,
}

impl Paillier {
    /// Generates a fresh Paillier key pair.
    ///
    /// Returns `(secret_key, public_key)`.
    pub fn keygen(
        &self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<(PaillierSecretKey, PaillierPublicKey)> {
        let mut sk_raw = std::ptr::null_mut();
        let mut pk_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_paillier_keygen(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                &mut sk_raw as *mut _,
                &mut pk_raw as *mut _,
            )
        };
        status_to_result(status)?;

        let sk = PaillierSecretKey {
            raw: NonNull::new(sk_raw).expect("bicycl_paillier_keygen/sk returned null"),
            _marker: PhantomData,
        };
        let pk = PaillierPublicKey {
            raw: NonNull::new(pk_raw).expect("bicycl_paillier_keygen/pk returned null"),
            _marker: PhantomData,
        };
        Ok((sk, pk))
    }

    /// Encrypts a plaintext given as a decimal string.
    ///
    /// The plaintext must lie in `[0, N)` where `N` is the Paillier modulus.
    pub fn encrypt_decimal(
        &self,
        ctx: &Context,
        pk: &PaillierPublicKey,
        rng: &mut RandGen,
        message_decimal: &str,
    ) -> Result<PaillierCiphertext> {
        let message_c = CString::new(message_decimal)?;
        let mut ct_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_paillier_encrypt_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                rng.raw.as_ptr(),
                message_c.as_ptr(),
                &mut ct_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(ct_raw).expect("bicycl_paillier_encrypt_decimal returned null");
        Ok(PaillierCiphertext {
            raw,
            _marker: PhantomData,
        })
    }

    /// Decrypts a ciphertext, returning the plaintext as a decimal string.
    ///
    /// Unlike the Joye-Libert and CL variants, Paillier decryption requires both
    /// `pk` and `sk` because the underlying C API uses the public key's modulus
    /// during the decryption computation.
    pub fn decrypt_decimal(
        &self,
        ctx: &Context,
        pk: &PaillierPublicKey,
        sk: &PaillierSecretKey,
        ct: &PaillierCiphertext,
    ) -> Result<String> {
        ffi_string_from_len(|buf, len| unsafe {
            bicycl_rs_sys::bicycl_paillier_decrypt_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                sk.raw.as_ptr(),
                ct.raw.as_ptr(),
                buf,
                len,
            )
        })
    }
}

impl Drop for Paillier {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_paillier_free(self.raw.as_ptr()) }
    }
}

impl Drop for PaillierSecretKey {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_paillier_sk_free(self.raw.as_ptr()) }
    }
}

impl Drop for PaillierPublicKey {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_paillier_pk_free(self.raw.as_ptr()) }
    }
}

impl Drop for PaillierCiphertext {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_paillier_ct_free(self.raw.as_ptr()) }
    }
}

/// A Joye-Libert homomorphic encryption scheme instance.
///
/// Create via [`Context::joye_libert`].
#[derive(Debug)]
pub struct JoyeLibert {
    raw: NonNull<bicycl_rs_sys::bicycl_joye_libert_t>,
    _marker: PhantomData<*mut ()>,
}

/// A Joye-Libert secret key.  Keep this private.
#[derive(Debug)]
pub struct JoyeLibertSecretKey {
    raw: NonNull<bicycl_rs_sys::bicycl_joye_libert_sk_t>,
    _marker: PhantomData<*mut ()>,
}

/// A Joye-Libert public key.  Safe to share.
#[derive(Debug)]
pub struct JoyeLibertPublicKey {
    raw: NonNull<bicycl_rs_sys::bicycl_joye_libert_pk_t>,
    _marker: PhantomData<*mut ()>,
}

/// A Joye-Libert ciphertext.
#[derive(Debug)]
pub struct JoyeLibertCiphertext {
    raw: NonNull<bicycl_rs_sys::bicycl_joye_libert_ct_t>,
    _marker: PhantomData<*mut ()>,
}

impl JoyeLibert {
    /// Generates a fresh Joye-Libert key pair.  Returns `(secret_key, public_key)`.
    pub fn keygen(
        &self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<(JoyeLibertSecretKey, JoyeLibertPublicKey)> {
        let mut sk_raw = std::ptr::null_mut();
        let mut pk_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_joye_libert_keygen(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                &mut sk_raw as *mut _,
                &mut pk_raw as *mut _,
            )
        };
        status_to_result(status)?;

        let sk = JoyeLibertSecretKey {
            raw: NonNull::new(sk_raw).expect("bicycl_joye_libert_keygen/sk returned null"),
            _marker: PhantomData,
        };
        let pk = JoyeLibertPublicKey {
            raw: NonNull::new(pk_raw).expect("bicycl_joye_libert_keygen/pk returned null"),
            _marker: PhantomData,
        };
        Ok((sk, pk))
    }

    /// Encrypts a plaintext given as a decimal string.
    ///
    /// The plaintext must be a non-negative integer less than `2^k`.
    pub fn encrypt_decimal(
        &self,
        ctx: &Context,
        pk: &JoyeLibertPublicKey,
        rng: &mut RandGen,
        message_decimal: &str,
    ) -> Result<JoyeLibertCiphertext> {
        let message_c = CString::new(message_decimal)?;
        let mut ct_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_joye_libert_encrypt_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                rng.raw.as_ptr(),
                message_c.as_ptr(),
                &mut ct_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(ct_raw).expect("bicycl_joye_libert_encrypt_decimal returned null");
        Ok(JoyeLibertCiphertext {
            raw,
            _marker: PhantomData,
        })
    }

    /// Decrypts a ciphertext, returning the plaintext as a decimal string.
    pub fn decrypt_decimal(
        &self,
        ctx: &Context,
        sk: &JoyeLibertSecretKey,
        ct: &JoyeLibertCiphertext,
    ) -> Result<String> {
        ffi_string_from_len(|buf, len| unsafe {
            bicycl_rs_sys::bicycl_joye_libert_decrypt_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                sk.raw.as_ptr(),
                ct.raw.as_ptr(),
                buf,
                len,
            )
        })
    }
}

impl Drop for JoyeLibert {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_joye_libert_free(self.raw.as_ptr()) }
    }
}

impl Drop for JoyeLibertSecretKey {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_joye_libert_sk_free(self.raw.as_ptr()) }
    }
}

impl Drop for JoyeLibertPublicKey {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_joye_libert_pk_free(self.raw.as_ptr()) }
    }
}

impl Drop for JoyeLibertCiphertext {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_joye_libert_ct_free(self.raw.as_ptr()) }
    }
}

/// A CL_HSMqk class-group encryption scheme with additive homomorphism over `Z/q^k`.
///
/// Create via [`Context::cl_hsmqk`].
#[derive(Debug)]
pub struct ClHsmqk {
    raw: NonNull<bicycl_rs_sys::bicycl_cl_hsmqk_t>,
    _marker: PhantomData<*mut ()>,
}

/// A CL_HSMqk secret key.  Keep this private.
#[derive(Debug)]
pub struct ClHsmqkSecretKey {
    raw: NonNull<bicycl_rs_sys::bicycl_cl_hsmqk_sk_t>,
    _marker: PhantomData<*mut ()>,
}

/// A CL_HSMqk public key.  Safe to share.
#[derive(Debug)]
pub struct ClHsmqkPublicKey {
    raw: NonNull<bicycl_rs_sys::bicycl_cl_hsmqk_pk_t>,
    _marker: PhantomData<*mut ()>,
}

/// A CL_HSMqk ciphertext.
#[derive(Debug)]
pub struct ClHsmqkCiphertext {
    raw: NonNull<bicycl_rs_sys::bicycl_cl_hsmqk_ct_t>,
    _marker: PhantomData<*mut ()>,
}

impl ClHsmqk {
    /// Generates a fresh CL_HSMqk key pair.  Returns `(secret_key, public_key)`.
    pub fn keygen(
        &self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<(ClHsmqkSecretKey, ClHsmqkPublicKey)> {
        let mut sk_raw = std::ptr::null_mut();
        let mut pk_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsmqk_keygen(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                &mut sk_raw as *mut _,
                &mut pk_raw as *mut _,
            )
        };
        status_to_result(status)?;

        let sk = ClHsmqkSecretKey {
            raw: NonNull::new(sk_raw).expect("bicycl_cl_hsmqk_keygen/sk returned null"),
            _marker: PhantomData,
        };
        let pk = ClHsmqkPublicKey {
            raw: NonNull::new(pk_raw).expect("bicycl_cl_hsmqk_keygen/pk returned null"),
            _marker: PhantomData,
        };
        Ok((sk, pk))
    }

    /// Encrypts a plaintext in `Z/q^k` given as a decimal string.
    pub fn encrypt_decimal(
        &self,
        ctx: &Context,
        pk: &ClHsmqkPublicKey,
        rng: &mut RandGen,
        message_decimal: &str,
    ) -> Result<ClHsmqkCiphertext> {
        let message_c = CString::new(message_decimal)?;
        let mut ct_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsmqk_encrypt_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                rng.raw.as_ptr(),
                message_c.as_ptr(),
                &mut ct_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(ct_raw).expect("bicycl_cl_hsmqk_encrypt_decimal returned null");
        Ok(ClHsmqkCiphertext {
            raw,
            _marker: PhantomData,
        })
    }

    /// Decrypts a CL_HSMqk ciphertext, returning the plaintext as a decimal string.
    pub fn decrypt_decimal(
        &self,
        ctx: &Context,
        sk: &ClHsmqkSecretKey,
        ct: &ClHsmqkCiphertext,
    ) -> Result<String> {
        ffi_string_from_len(|buf, len| unsafe {
            bicycl_rs_sys::bicycl_cl_hsmqk_decrypt_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                sk.raw.as_ptr(),
                ct.raw.as_ptr(),
                buf,
                len,
            )
        })
    }

    /// Homomorphically adds two ciphertexts: `Enc(a) ⊕ Enc(b) = Enc(a+b mod q^k)`.
    pub fn add_ciphertexts(
        &self,
        ctx: &Context,
        pk: &ClHsmqkPublicKey,
        rng: &mut RandGen,
        ca: &ClHsmqkCiphertext,
        cb: &ClHsmqkCiphertext,
    ) -> Result<ClHsmqkCiphertext> {
        let mut ct_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsmqk_add_ciphertexts(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                rng.raw.as_ptr(),
                ca.raw.as_ptr(),
                cb.raw.as_ptr(),
                &mut ct_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(ct_raw).expect("bicycl_cl_hsmqk_add_ciphertexts returned null");
        Ok(ClHsmqkCiphertext {
            raw,
            _marker: PhantomData,
        })
    }

    /// Homomorphically multiplies a ciphertext by a scalar: `Enc(m) * s = Enc(m*s mod q^k)`.
    ///
    /// `scalar_decimal` is the scalar as a decimal string.
    pub fn scal_ciphertext_decimal(
        &self,
        ctx: &Context,
        pk: &ClHsmqkPublicKey,
        rng: &mut RandGen,
        ct: &ClHsmqkCiphertext,
        scalar_decimal: &str,
    ) -> Result<ClHsmqkCiphertext> {
        let scalar_c = CString::new(scalar_decimal)?;
        let mut out_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsmqk_scal_ciphertext_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                rng.raw.as_ptr(),
                ct.raw.as_ptr(),
                scalar_c.as_ptr(),
                &mut out_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw =
            NonNull::new(out_raw).expect("bicycl_cl_hsmqk_scal_ciphertext_decimal returned null");
        Ok(ClHsmqkCiphertext {
            raw,
            _marker: PhantomData,
        })
    }

    /// Computes `Enc(a + b*s mod q^k)`: adds ciphertext `ca` to a scalar multiple of `cb`.
    ///
    /// Specifically, multiplies `cb` by `scalar_decimal` and adds the result to `ca`,
    /// equivalent to `scal_ciphertext_decimal(cb, s)` then `add_ciphertexts(ca, scaled_cb)`
    /// but in a single C call.  `scalar_decimal` is the scalar as a decimal string.
    pub fn addscal_ciphertexts_decimal(
        &self,
        ctx: &Context,
        pk: &ClHsmqkPublicKey,
        rng: &mut RandGen,
        ca: &ClHsmqkCiphertext,
        cb: &ClHsmqkCiphertext,
        scalar_decimal: &str,
    ) -> Result<ClHsmqkCiphertext> {
        let scalar_c = CString::new(scalar_decimal)?;
        let mut out_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsmqk_addscal_ciphertexts_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                rng.raw.as_ptr(),
                ca.raw.as_ptr(),
                cb.raw.as_ptr(),
                scalar_c.as_ptr(),
                &mut out_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(out_raw)
            .expect("bicycl_cl_hsmqk_addscal_ciphertexts_decimal returned null");
        Ok(ClHsmqkCiphertext {
            raw,
            _marker: PhantomData,
        })
    }
}

impl Drop for ClHsmqk {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_cl_hsmqk_free(self.raw.as_ptr()) }
    }
}

impl Drop for ClHsmqkSecretKey {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_cl_hsmqk_sk_free(self.raw.as_ptr()) }
    }
}

impl Drop for ClHsmqkPublicKey {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_cl_hsmqk_pk_free(self.raw.as_ptr()) }
    }
}

impl Drop for ClHsmqkCiphertext {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_cl_hsmqk_ct_free(self.raw.as_ptr()) }
    }
}

/// A CL_HSM2k class-group encryption scheme with additive homomorphism over `Z/2^k`.
///
/// Create via [`Context::cl_hsm2k`].
#[derive(Debug)]
pub struct ClHsm2k {
    raw: NonNull<bicycl_rs_sys::bicycl_cl_hsm2k_t>,
    _marker: PhantomData<*mut ()>,
}

/// A CL_HSM2k secret key.  Keep this private.
#[derive(Debug)]
pub struct ClHsm2kSecretKey {
    raw: NonNull<bicycl_rs_sys::bicycl_cl_hsm2k_sk_t>,
    _marker: PhantomData<*mut ()>,
}

/// A CL_HSM2k public key.  Safe to share.
#[derive(Debug)]
pub struct ClHsm2kPublicKey {
    raw: NonNull<bicycl_rs_sys::bicycl_cl_hsm2k_pk_t>,
    _marker: PhantomData<*mut ()>,
}

/// A CL_HSM2k ciphertext.
#[derive(Debug)]
pub struct ClHsm2kCiphertext {
    raw: NonNull<bicycl_rs_sys::bicycl_cl_hsm2k_ct_t>,
    _marker: PhantomData<*mut ()>,
}

impl ClHsm2k {
    /// Generates a fresh CL_HSM2k key pair.  Returns `(secret_key, public_key)`.
    pub fn keygen(
        &self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<(ClHsm2kSecretKey, ClHsm2kPublicKey)> {
        let mut sk_raw = std::ptr::null_mut();
        let mut pk_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsm2k_keygen(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                &mut sk_raw as *mut _,
                &mut pk_raw as *mut _,
            )
        };
        status_to_result(status)?;

        let sk = ClHsm2kSecretKey {
            raw: NonNull::new(sk_raw).expect("bicycl_cl_hsm2k_keygen/sk returned null"),
            _marker: PhantomData,
        };
        let pk = ClHsm2kPublicKey {
            raw: NonNull::new(pk_raw).expect("bicycl_cl_hsm2k_keygen/pk returned null"),
            _marker: PhantomData,
        };
        Ok((sk, pk))
    }

    /// Encrypts a plaintext in `Z/2^k` given as a decimal string.
    pub fn encrypt_decimal(
        &self,
        ctx: &Context,
        pk: &ClHsm2kPublicKey,
        rng: &mut RandGen,
        message_decimal: &str,
    ) -> Result<ClHsm2kCiphertext> {
        let message_c = CString::new(message_decimal)?;
        let mut ct_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsm2k_encrypt_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                rng.raw.as_ptr(),
                message_c.as_ptr(),
                &mut ct_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(ct_raw).expect("bicycl_cl_hsm2k_encrypt_decimal returned null");
        Ok(ClHsm2kCiphertext {
            raw,
            _marker: PhantomData,
        })
    }

    /// Decrypts a CL_HSM2k ciphertext, returning the plaintext as a decimal string.
    pub fn decrypt_decimal(
        &self,
        ctx: &Context,
        sk: &ClHsm2kSecretKey,
        ct: &ClHsm2kCiphertext,
    ) -> Result<String> {
        ffi_string_from_len(|buf, len| unsafe {
            bicycl_rs_sys::bicycl_cl_hsm2k_decrypt_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                sk.raw.as_ptr(),
                ct.raw.as_ptr(),
                buf,
                len,
            )
        })
    }

    /// Homomorphically adds two ciphertexts: `Enc(a) ⊕ Enc(b) = Enc(a+b mod 2^k)`.
    pub fn add_ciphertexts(
        &self,
        ctx: &Context,
        pk: &ClHsm2kPublicKey,
        rng: &mut RandGen,
        ca: &ClHsm2kCiphertext,
        cb: &ClHsm2kCiphertext,
    ) -> Result<ClHsm2kCiphertext> {
        let mut ct_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsm2k_add_ciphertexts(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                rng.raw.as_ptr(),
                ca.raw.as_ptr(),
                cb.raw.as_ptr(),
                &mut ct_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(ct_raw).expect("bicycl_cl_hsm2k_add_ciphertexts returned null");
        Ok(ClHsm2kCiphertext {
            raw,
            _marker: PhantomData,
        })
    }

    /// Homomorphically multiplies a ciphertext by a scalar: `Enc(m) * s = Enc(m*s mod 2^k)`.
    pub fn scal_ciphertext_decimal(
        &self,
        ctx: &Context,
        pk: &ClHsm2kPublicKey,
        rng: &mut RandGen,
        ct: &ClHsm2kCiphertext,
        scalar_decimal: &str,
    ) -> Result<ClHsm2kCiphertext> {
        let scalar_c = CString::new(scalar_decimal)?;
        let mut out_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsm2k_scal_ciphertext_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                rng.raw.as_ptr(),
                ct.raw.as_ptr(),
                scalar_c.as_ptr(),
                &mut out_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw =
            NonNull::new(out_raw).expect("bicycl_cl_hsm2k_scal_ciphertext_decimal returned null");
        Ok(ClHsm2kCiphertext {
            raw,
            _marker: PhantomData,
        })
    }

    /// Computes `Enc(a + b*s mod 2^k)`: adds ciphertext `ca` to a scalar multiple of `cb`.
    ///
    /// Specifically, multiplies `cb` by `scalar_decimal` and adds the result to `ca`,
    /// equivalent to `scal_ciphertext_decimal(cb, s)` then `add_ciphertexts(ca, scaled_cb)`
    /// but in a single C call.  `scalar_decimal` is the scalar as a decimal string.
    pub fn addscal_ciphertexts_decimal(
        &self,
        ctx: &Context,
        pk: &ClHsm2kPublicKey,
        rng: &mut RandGen,
        ca: &ClHsm2kCiphertext,
        cb: &ClHsm2kCiphertext,
        scalar_decimal: &str,
    ) -> Result<ClHsm2kCiphertext> {
        let scalar_c = CString::new(scalar_decimal)?;
        let mut out_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_hsm2k_addscal_ciphertexts_decimal(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                rng.raw.as_ptr(),
                ca.raw.as_ptr(),
                cb.raw.as_ptr(),
                scalar_c.as_ptr(),
                &mut out_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(out_raw)
            .expect("bicycl_cl_hsm2k_addscal_ciphertexts_decimal returned null");
        Ok(ClHsm2kCiphertext {
            raw,
            _marker: PhantomData,
        })
    }
}

impl Drop for ClHsm2k {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_cl_hsm2k_free(self.raw.as_ptr()) }
    }
}

impl Drop for ClHsm2kSecretKey {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_cl_hsm2k_sk_free(self.raw.as_ptr()) }
    }
}

impl Drop for ClHsm2kPublicKey {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_cl_hsm2k_pk_free(self.raw.as_ptr()) }
    }
}

impl Drop for ClHsm2kCiphertext {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_cl_hsm2k_ct_free(self.raw.as_ptr()) }
    }
}

/// An ECDSA signature scheme instance.
///
/// Create via [`Context::ecdsa`].
#[derive(Debug)]
pub struct Ecdsa {
    raw: NonNull<bicycl_rs_sys::bicycl_ecdsa_t>,
    _marker: PhantomData<*mut ()>,
}

/// An ECDSA secret (signing) key.  Keep this private.
#[derive(Debug)]
pub struct EcdsaSecretKey {
    raw: NonNull<bicycl_rs_sys::bicycl_ecdsa_sk_t>,
    _marker: PhantomData<*mut ()>,
}

/// An ECDSA public (verification) key.  Safe to share.
#[derive(Debug)]
pub struct EcdsaPublicKey {
    raw: NonNull<bicycl_rs_sys::bicycl_ecdsa_pk_t>,
    _marker: PhantomData<*mut ()>,
}

/// An ECDSA signature `(r, s)`.
#[derive(Debug)]
pub struct EcdsaSignature {
    raw: NonNull<bicycl_rs_sys::bicycl_ecdsa_sig_t>,
    _marker: PhantomData<*mut ()>,
}

impl Ecdsa {
    /// Generates a fresh ECDSA key pair.  Returns `(secret_key, public_key)`.
    pub fn keygen(
        &self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<(EcdsaSecretKey, EcdsaPublicKey)> {
        let mut sk_raw = std::ptr::null_mut();
        let mut pk_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_ecdsa_keygen(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                &mut sk_raw as *mut _,
                &mut pk_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let sk = EcdsaSecretKey {
            raw: NonNull::new(sk_raw).expect("bicycl_ecdsa_keygen/sk returned null"),
            _marker: PhantomData,
        };
        let pk = EcdsaPublicKey {
            raw: NonNull::new(pk_raw).expect("bicycl_ecdsa_keygen/pk returned null"),
            _marker: PhantomData,
        };
        Ok((sk, pk))
    }

    /// Signs a message with the given secret key.
    ///
    /// `msg` is the raw message bytes (not a hash).  The C library hashes it internally.
    pub fn sign_message(
        &self,
        ctx: &Context,
        rng: &mut RandGen,
        sk: &EcdsaSecretKey,
        msg: &[u8],
    ) -> Result<EcdsaSignature> {
        let mut sig_raw = std::ptr::null_mut();
        let status = unsafe {
            bicycl_rs_sys::bicycl_ecdsa_sign_message(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                sk.raw.as_ptr(),
                msg.as_ptr(),
                msg.len(),
                &mut sig_raw as *mut _,
            )
        };
        status_to_result(status)?;
        let raw = NonNull::new(sig_raw).expect("bicycl_ecdsa_sign_message returned null");
        Ok(EcdsaSignature {
            raw,
            _marker: PhantomData,
        })
    }

    /// Verifies a signature against a message and public key.
    ///
    /// Returns `true` if the signature is valid, `false` otherwise.
    /// Does **not** return an error on invalid signatures — errors indicate
    /// an internal failure (e.g., allocation), not a cryptographic mismatch.
    pub fn verify_message(
        &self,
        ctx: &Context,
        pk: &EcdsaPublicKey,
        msg: &[u8],
        sig: &EcdsaSignature,
    ) -> Result<bool> {
        let mut out_valid: c_int = 0;
        let status = unsafe {
            bicycl_rs_sys::bicycl_ecdsa_verify_message(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                pk.raw.as_ptr(),
                msg.as_ptr(),
                msg.len(),
                sig.raw.as_ptr(),
                &mut out_valid as *mut _,
            )
        };
        status_to_result(status)?;
        Ok(out_valid != 0)
    }
}

impl EcdsaSignature {
    /// Returns the `r` component of the signature as a decimal string.
    pub fn r_decimal(&self, ctx: &Context) -> Result<String> {
        ffi_string_from_len(|buf, len| unsafe {
            bicycl_rs_sys::bicycl_ecdsa_sig_r_decimal(ctx.raw.as_ptr(), self.raw.as_ptr(), buf, len)
        })
    }

    /// Returns the `s` component of the signature as a decimal string.
    pub fn s_decimal(&self, ctx: &Context) -> Result<String> {
        ffi_string_from_len(|buf, len| unsafe {
            bicycl_rs_sys::bicycl_ecdsa_sig_s_decimal(ctx.raw.as_ptr(), self.raw.as_ptr(), buf, len)
        })
    }
}

// ── Two-party ECDSA session with typestate ──

/// State markers for [`TwoPartyEcdsaSession`].
pub mod two_party {
    pub struct New;
    pub struct Keygen1;
    pub struct Keygen2;
    pub struct Keygen3;
    pub struct KeygenDone;
    pub struct Sign1;
    pub struct Sign2;
    pub struct Sign3;
    pub struct Sign4;
    pub struct SignDone;
}

/// A stateful session for the interactive two-party (2-of-2) ECDSA signing protocol.
///
/// Create via [`Context::two_party_ecdsa_session`].  Each round method consumes
/// the session and returns the next state on success.  On error, the session is
/// dropped (the protocol is broken and must be restarted from scratch).
///
/// ```text
/// New → keygen_round1 → Keygen1 → keygen_round2 → Keygen2
///     → keygen_round3 → Keygen3 → keygen_round4 → KeygenDone
///     → sign_round1 → Sign1 → sign_round2 → Sign2
///     → sign_round3 → Sign3 → sign_round4 → Sign4
///     → sign_finalize → SignDone
/// ```
///
/// Calling a method from the wrong state is a compile-time error:
///
/// ```compile_fail
/// # fn main() -> Result<(), bicycl_rs::Error> {
/// let ctx = bicycl_rs::Context::new()?;
/// let mut rng = ctx.randgen_from_seed_decimal("1")?;
/// let session = ctx.two_party_ecdsa_session(&mut rng, 112)?;
/// // ERROR: New state has no sign_round1
/// session.sign_round1(&ctx, &mut rng, b"msg")?;
/// # Ok(()) }
/// ```
pub struct TwoPartyEcdsaSession<S = two_party::New> {
    raw: NonNull<bicycl_rs_sys::bicycl_two_party_ecdsa_session_t>,
    _state: PhantomData<S>,
    _marker: PhantomData<*mut ()>,
}

impl<S> std::fmt::Debug for TwoPartyEcdsaSession<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TwoPartyEcdsaSession")
            .field("raw", &self.raw)
            .finish()
    }
}

impl<S> TwoPartyEcdsaSession<S> {
    fn transition<T>(self) -> TwoPartyEcdsaSession<T> {
        let raw = self.raw;
        std::mem::forget(self);
        TwoPartyEcdsaSession {
            raw,
            _state: PhantomData,
            _marker: PhantomData,
        }
    }
}

impl<S> Drop for TwoPartyEcdsaSession<S> {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_two_party_ecdsa_session_free(self.raw.as_ptr()) }
    }
}

impl TwoPartyEcdsaSession<two_party::New> {
    pub fn keygen_round1(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<TwoPartyEcdsaSession<two_party::Keygen1>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_two_party_ecdsa_keygen_round1(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl TwoPartyEcdsaSession<two_party::Keygen1> {
    pub fn keygen_round2(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<TwoPartyEcdsaSession<two_party::Keygen2>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_two_party_ecdsa_keygen_round2(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl TwoPartyEcdsaSession<two_party::Keygen2> {
    pub fn keygen_round3(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<TwoPartyEcdsaSession<two_party::Keygen3>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_two_party_ecdsa_keygen_round3(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl TwoPartyEcdsaSession<two_party::Keygen3> {
    pub fn keygen_round4(
        self,
        ctx: &Context,
    ) -> Result<TwoPartyEcdsaSession<two_party::KeygenDone>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_two_party_ecdsa_keygen_round4(ctx.raw.as_ptr(), self.raw.as_ptr())
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl TwoPartyEcdsaSession<two_party::KeygenDone> {
    pub fn sign_round1(
        self,
        ctx: &Context,
        rng: &mut RandGen,
        msg: &[u8],
    ) -> Result<TwoPartyEcdsaSession<two_party::Sign1>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_two_party_ecdsa_sign_round1(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                msg.as_ptr(),
                msg.len(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl TwoPartyEcdsaSession<two_party::Sign1> {
    pub fn sign_round2(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<TwoPartyEcdsaSession<two_party::Sign2>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_two_party_ecdsa_sign_round2(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl TwoPartyEcdsaSession<two_party::Sign2> {
    pub fn sign_round3(self, ctx: &Context) -> Result<TwoPartyEcdsaSession<two_party::Sign3>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_two_party_ecdsa_sign_round3(ctx.raw.as_ptr(), self.raw.as_ptr())
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl TwoPartyEcdsaSession<two_party::Sign3> {
    pub fn sign_round4(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<TwoPartyEcdsaSession<two_party::Sign4>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_two_party_ecdsa_sign_round4(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl TwoPartyEcdsaSession<two_party::Sign4> {
    /// Returns `true` if the produced signature is valid.
    pub fn sign_finalize(
        self,
        ctx: &Context,
    ) -> Result<(TwoPartyEcdsaSession<two_party::SignDone>, bool)> {
        let mut out_valid: c_int = 0;
        let status = unsafe {
            bicycl_rs_sys::bicycl_two_party_ecdsa_sign_finalize(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                &mut out_valid as *mut _,
            )
        };
        status_to_result(status)?;
        Ok((self.transition(), out_valid != 0))
    }
}

// ── CL DLog session with typestate ──

/// State markers for [`ClDlogSession`].
pub mod cl_dlog {
    pub struct New;
    pub struct Prepared;
    pub struct Proved;
    pub struct StatementImported;
    pub struct Ready;
}

/// A session for the interactive CL DLog (discrete logarithm) proof protocol.
///
/// Create via [`Context::cl_dlog_session`].
///
/// **Prover path:**
/// ```text
/// New → prepare_statement → Prepared → prove_round → Proved
/// ```
/// In the `Proved` state: `export_statement`, `export_proof`, `verify_round`.
///
/// **Verifier path:**
/// ```text
/// New → import_statement → StatementImported → import_proof → Ready
/// ```
/// In the `Ready` state: `verify_round`.
///
/// Calling a method from the wrong state is a compile-time error:
///
/// ```compile_fail
/// # fn main() -> Result<(), bicycl_rs::Error> {
/// let ctx = bicycl_rs::Context::new()?;
/// let mut rng = ctx.randgen_from_seed_decimal("1")?;
/// let session = ctx.cl_dlog_session(&mut rng, 112)?;
/// // ERROR: New state has no prove_round
/// session.prove_round(&ctx, &mut rng)?;
/// # Ok(()) }
/// ```
pub struct ClDlogSession<S = cl_dlog::New> {
    raw: NonNull<bicycl_rs_sys::bicycl_cl_dlog_session_t>,
    _state: PhantomData<S>,
    _marker: PhantomData<*mut ()>,
}

impl<S> std::fmt::Debug for ClDlogSession<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClDlogSession")
            .field("raw", &self.raw)
            .finish()
    }
}

impl<S> ClDlogSession<S> {
    fn transition<T>(self) -> ClDlogSession<T> {
        let raw = self.raw;
        std::mem::forget(self);
        ClDlogSession {
            raw,
            _state: PhantomData,
            _marker: PhantomData,
        }
    }
}

impl<S> Drop for ClDlogSession<S> {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_cl_dlog_session_free(self.raw.as_ptr()) }
    }
}

/// A serializable message container used to exchange statements and proofs
/// between prover and verifier in the CL DLog protocol.
///
/// Create with [`ClDlogMessage::new`] and serialise/deserialise with
/// [`to_bytes`][Self::to_bytes] / [`load_bytes`][Self::load_bytes].
#[derive(Debug)]
pub struct ClDlogMessage {
    raw: NonNull<bicycl_rs_sys::bicycl_cl_dlog_message_t>,
    _marker: PhantomData<*mut ()>,
}

impl ClDlogSession<cl_dlog::New> {
    /// Prepares the statement (prover path).
    pub fn prepare_statement(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<ClDlogSession<cl_dlog::Prepared>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_session_prepare_statement(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }

    /// Imports the prover's statement (verifier path).
    pub fn import_statement(
        self,
        ctx: &Context,
        msg: &ClDlogMessage,
    ) -> Result<ClDlogSession<cl_dlog::StatementImported>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_session_import_statement(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                msg.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ClDlogSession<cl_dlog::Prepared> {
    /// Executes the prover's round (generates the DLog proof).
    pub fn prove_round(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<ClDlogSession<cl_dlog::Proved>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_session_prove_round(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ClDlogSession<cl_dlog::Proved> {
    /// Exports the statement into `out_msg` so it can be sent to the verifier.
    pub fn export_statement(&self, ctx: &Context, out_msg: &mut ClDlogMessage) -> Result<()> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_session_export_statement(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                out_msg.raw.as_ptr(),
            )
        };
        status_to_result(status)
    }

    /// Exports the proof into `out_msg` so it can be sent to the verifier.
    pub fn export_proof(&self, ctx: &Context, out_msg: &mut ClDlogMessage) -> Result<()> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_session_export_proof(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                out_msg.raw.as_ptr(),
            )
        };
        status_to_result(status)
    }

    /// Verifies the proof (self-check).  Returns `true` if valid.
    pub fn verify_round(&self, ctx: &Context) -> Result<bool> {
        let mut out_valid: c_int = 0;
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_session_verify_round(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                &mut out_valid as *mut _,
            )
        };
        status_to_result(status)?;
        Ok(out_valid != 0)
    }
}

impl ClDlogSession<cl_dlog::StatementImported> {
    /// Imports the proof (on the verifier side).
    pub fn import_proof(
        self,
        ctx: &Context,
        msg: &ClDlogMessage,
    ) -> Result<ClDlogSession<cl_dlog::Ready>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_session_import_proof(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                msg.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ClDlogSession<cl_dlog::Ready> {
    /// Executes the verifier's round.  Returns `true` if the proof is valid.
    pub fn verify_round(&self, ctx: &Context) -> Result<bool> {
        let mut out_valid: c_int = 0;
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_session_verify_round(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                &mut out_valid as *mut _,
            )
        };
        status_to_result(status)?;
        Ok(out_valid != 0)
    }
}

impl ClDlogMessage {
    /// Creates an empty message container.
    pub fn new() -> Result<Self> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe { bicycl_rs_sys::bicycl_cl_dlog_message_new(&mut raw as *mut _) };
        status_to_result(status)?;
        let raw = NonNull::new(raw).expect("bicycl_cl_dlog_message_new returned null");
        Ok(Self {
            raw,
            _marker: PhantomData,
        })
    }

    /// Serializes the message to bytes for transmission.
    pub fn to_bytes(&self, ctx: &Context) -> Result<Vec<u8>> {
        ffi_bytes_from_len(|buf, len| unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_message_export_bytes(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                buf,
                len,
            )
        })
    }

    /// Deserializes bytes into this message container (overwrites any previous content).
    pub fn load_bytes(&mut self, ctx: &Context, bytes: &[u8]) -> Result<()> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_cl_dlog_message_import_bytes(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                bytes.as_ptr(),
                bytes.len(),
            )
        };
        status_to_result(status)
    }
}

impl Drop for ClDlogMessage {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_cl_dlog_message_free(self.raw.as_ptr()) }
    }
}

// ── Threshold ECDSA session with typestate ──

/// State markers for [`ThresholdEcdsaSession`].
pub mod threshold {
    pub struct New;
    pub struct Keygen1;
    pub struct Keygen2;
    pub struct KeygenDone;
    pub struct Sign1;
    pub struct Sign2;
    pub struct Sign3;
    pub struct Sign4;
    pub struct Sign5;
    pub struct Sign6;
    pub struct Sign7;
    pub struct Sign8;
    pub struct SignDone;
}

/// A stateful session for the threshold (t-of-n) ECDSA signing protocol.
///
/// Create via [`Context::threshold_ecdsa_session`].
///
/// ```text
/// New → keygen_round1 → Keygen1 → keygen_round2 → Keygen2
///     → keygen_finalize → KeygenDone
///     → sign_round1 → Sign1 → ... → Sign8
///     → sign_finalize → SignDone (signature_valid)
/// ```
///
/// Calling a method from the wrong state is a compile-time error:
///
/// ```compile_fail
/// # fn main() -> Result<(), bicycl_rs::Error> {
/// let ctx = bicycl_rs::Context::new()?;
/// let mut rng = ctx.randgen_from_seed_decimal("1")?;
/// let session = ctx.threshold_ecdsa_session(&mut rng, 112, 2, 1)?;
/// // ERROR: New state has no sign_round1
/// session.sign_round1(&ctx, &mut rng, b"msg")?;
/// # Ok(()) }
/// ```
pub struct ThresholdEcdsaSession<S = threshold::New> {
    raw: NonNull<bicycl_rs_sys::bicycl_threshold_ecdsa_session_t>,
    _state: PhantomData<S>,
    _marker: PhantomData<*mut ()>,
}

impl<S> std::fmt::Debug for ThresholdEcdsaSession<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ThresholdEcdsaSession")
            .field("raw", &self.raw)
            .finish()
    }
}

impl<S> ThresholdEcdsaSession<S> {
    fn transition<T>(self) -> ThresholdEcdsaSession<T> {
        let raw = self.raw;
        std::mem::forget(self);
        ThresholdEcdsaSession {
            raw,
            _state: PhantomData,
            _marker: PhantomData,
        }
    }
}

impl<S> Drop for ThresholdEcdsaSession<S> {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_threshold_ecdsa_session_free(self.raw.as_ptr()) }
    }
}

impl ThresholdEcdsaSession<threshold::New> {
    pub fn keygen_round1(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<ThresholdEcdsaSession<threshold::Keygen1>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_keygen_round1(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::Keygen1> {
    pub fn keygen_round2(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<ThresholdEcdsaSession<threshold::Keygen2>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_keygen_round2(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::Keygen2> {
    pub fn keygen_finalize(
        self,
        ctx: &Context,
    ) -> Result<ThresholdEcdsaSession<threshold::KeygenDone>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_keygen_finalize(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::KeygenDone> {
    pub fn sign_round1(
        self,
        ctx: &Context,
        rng: &mut RandGen,
        msg: &[u8],
    ) -> Result<ThresholdEcdsaSession<threshold::Sign1>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_sign_round1(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
                msg.as_ptr(),
                msg.len(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::Sign1> {
    pub fn sign_round2(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<ThresholdEcdsaSession<threshold::Sign2>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_sign_round2(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::Sign2> {
    pub fn sign_round3(self, ctx: &Context) -> Result<ThresholdEcdsaSession<threshold::Sign3>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_sign_round3(ctx.raw.as_ptr(), self.raw.as_ptr())
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::Sign3> {
    pub fn sign_round4(self, ctx: &Context) -> Result<ThresholdEcdsaSession<threshold::Sign4>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_sign_round4(ctx.raw.as_ptr(), self.raw.as_ptr())
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::Sign4> {
    pub fn sign_round5(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<ThresholdEcdsaSession<threshold::Sign5>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_sign_round5(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::Sign5> {
    pub fn sign_round6(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<ThresholdEcdsaSession<threshold::Sign6>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_sign_round6(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::Sign6> {
    pub fn sign_round7(
        self,
        ctx: &Context,
        rng: &mut RandGen,
    ) -> Result<ThresholdEcdsaSession<threshold::Sign7>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_sign_round7(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                rng.raw.as_ptr(),
            )
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::Sign7> {
    pub fn sign_round8(self, ctx: &Context) -> Result<ThresholdEcdsaSession<threshold::Sign8>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_sign_round8(ctx.raw.as_ptr(), self.raw.as_ptr())
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::Sign8> {
    pub fn sign_finalize(
        self,
        ctx: &Context,
    ) -> Result<ThresholdEcdsaSession<threshold::SignDone>> {
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_sign_finalize(ctx.raw.as_ptr(), self.raw.as_ptr())
        };
        status_to_result(status)?;
        Ok(self.transition())
    }
}

impl ThresholdEcdsaSession<threshold::SignDone> {
    /// Returns `true` if the threshold signature produced by this session is valid.
    pub fn signature_valid(&self, ctx: &Context) -> Result<bool> {
        let mut out_valid: c_int = 0;
        let status = unsafe {
            bicycl_rs_sys::bicycl_threshold_ecdsa_signature_valid(
                ctx.raw.as_ptr(),
                self.raw.as_ptr(),
                &mut out_valid as *mut _,
            )
        };
        status_to_result(status)?;
        Ok(out_valid != 0)
    }
}

impl Drop for Ecdsa {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_ecdsa_free(self.raw.as_ptr()) }
    }
}

impl Drop for EcdsaSecretKey {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_ecdsa_sk_free(self.raw.as_ptr()) }
    }
}

impl Drop for EcdsaPublicKey {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_ecdsa_pk_free(self.raw.as_ptr()) }
    }
}

impl Drop for EcdsaSignature {
    fn drop(&mut self) {
        unsafe { bicycl_rs_sys::bicycl_ecdsa_sig_free(self.raw.as_ptr()) }
    }
}