stoffel-vm 0.1.0

Register-based virtual machine runtime and MPC execution engine for Stoffel programs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
//! C Foreign Function Interface (CFFI) for StoffelVM
//!
//! This module provides a C-compatible API for interacting with StoffelVM from languages
//! like C, Go, Nim, JavaScript, Python, etc. It allows external code to:
//!
//! - Create and manage VM instances
//! - Register foreign functions with the VM
//! - Execute VM functions and retrieve results
//! - Convert between VM and C-compatible types
//!
//! # Safety
//!
//! This module contains unsafe code due to the nature of FFI. Care must be taken when
//! using these functions from other languages to ensure memory safety and proper resource
//! management.
//!
//! # Example (C)
//!
//! ```c
//! #include "stoffel_vm.h"
//! #include <stdio.h>
//!
//! // Example C callback function
//! int double_value(StoffelValue* args, int arg_count, StoffelValue* result) {
//!     if (arg_count != 1 || args[0].value_type != STOFFEL_VALUE_INT) {
//!         return -1; // Error
//!     }
//!     
//!     result->value_type = STOFFEL_VALUE_INT;
//!     result->data.int_val = args[0].data.int_val * 2;
//!     return 0; // Success
//! }
//!
//! int main() {
//!     // Create a VM instance
//!     VMHandle vm = stoffel_create_vm();
//!     
//!     // Register a foreign function
//!     stoffel_register_foreign_function(vm, "double", double_value);
//!     
//!     // Execute a VM function
//!     StoffelValue result;
//!     int status = stoffel_execute(vm, "test_double", &result);
//!     
//!     // Clean up
//!     stoffel_destroy_vm(vm);
//!     return 0;
//! }
//! ```

use std::ffi::{c_char, CStr, CString};
use std::io::Cursor;
use std::marker::PhantomPinned;
use std::os::raw::{c_int, c_void};
use std::ptr::NonNull;
use std::sync::Arc;

use crate::core_vm::VirtualMachine;
use crate::foreign_functions::ForeignFunctionContext;
use crate::net::hb_engine::{
    HoneyBadgerEngineConfig, HoneyBadgerMpcEngine, HoneyBadgerPreprocessingConfig,
};
use crate::net::mpc_engine::MpcEngine;
use stoffel_vm_types::compiled_binary::CompiledBinary;
use stoffel_vm_types::core_types::{
    ArrayRef, ForeignObjectRef, ObjectRef, ShareType, Value, DEFAULT_FIXED_POINT_FRACTIONAL_BITS,
    F64,
};
use stoffelnet::transports::quic::QuicNetworkManager;

/// Maximum share buffer size accepted from FFI callers (1 MB).
/// Prevents accidental or malicious oversized allocations from C/SDK code.
const MAX_FFI_SHARE_LEN: usize = 1_048_576;

/// Write a `Vec<u8>` result through FFI out-pointers using the boxed-slice pattern.
///
/// The Vec is shrunk to exact length via `into_boxed_slice()`, then leaked as a raw
/// pointer. The caller must free with the corresponding `*_free_bytes` function which
/// reconstructs the `Box<[u8]>`.
///
/// # Safety
/// `result_ptr` and `result_len_ptr` must be valid, non-null, aligned pointers.
unsafe fn write_ffi_result_bytes(
    bytes: Vec<u8>,
    result_ptr: *mut *mut u8,
    result_len_ptr: *mut usize,
) {
    let boxed = bytes.into_boxed_slice();
    let len = boxed.len();
    let ptr = Box::into_raw(boxed) as *mut u8;
    *result_ptr = ptr;
    *result_len_ptr = len;
}

/// Free bytes previously allocated via [`write_ffi_result_bytes`].
///
/// Reconstructs the `Box<[u8]>` and drops it.
///
/// # Safety
/// `ptr` must have been produced by `write_ffi_result_bytes` with the matching `len`,
/// and must not have been freed already.
unsafe fn free_ffi_result_bytes(ptr: *mut u8, len: usize) {
    if !ptr.is_null() {
        let _ = Box::from_raw(std::ptr::slice_from_raw_parts_mut(ptr, len));
    }
}

/// Opaque pointer type for the VM
pub type VMHandle = *mut c_void;

/// Value types in StoffelVM exposed to C
#[repr(C)]
pub enum StoffelValueType {
    /// Unit/void value
    Unit = 0,
    /// Integer value
    Int = 1,
    /// Float value
    Float = 2,
    /// Boolean value
    Bool = 3,
    /// String value
    String = 4,
    /// Object reference
    Object = 5,
    /// Array reference
    Array = 6,
    /// Foreign object reference
    Foreign = 7,
    /// Function closure
    Closure = 8,
}

/// Union to hold the actual value data
#[repr(C)]
pub union StoffelValueData {
    /// Integer value
    pub int_val: i64,
    /// Float value
    pub float_val: f64,
    /// Boolean value
    pub bool_val: bool,
    /// String value (C string)
    pub string_val: *const c_char,
    /// Object ID
    pub object_id: usize,
    /// Array ID
    pub array_id: usize,
    /// Foreign object ID
    pub foreign_id: usize,
    /// Closure ID (for future use)
    pub closure_id: usize,
}

/// C-compatible representation of a StoffelVM value
#[repr(C)]
pub struct StoffelValue {
    /// Type of the value
    pub value_type: StoffelValueType,
    /// Actual value data
    pub data: StoffelValueData,
}

/// Type for C callback functions
pub type CForeignFunction =
    extern "C" fn(args: *const StoffelValue, arg_count: c_int, result: *mut StoffelValue) -> c_int;

// ============================================================================
// HoneyBadgerMpcEngine FFI Types
// ============================================================================
/// Opaque pointer type for HoneyBadgerMpcEngine
///
/// This type is used to pass engine handles across the FFI boundary.
/// The actual `Arc<HoneyBadgerMpcEngine>` is stored inside a Box for stable pointer.
#[repr(C)]
pub struct HBEngineOpaque {
    _data: (),
    _marker: core::marker::PhantomData<(*mut u8, PhantomPinned)>,
}
/// Opaque pointer type for QuicNetworkManager
///
/// This type is used to pass network handles across the FFI boundary.
#[repr(C)]
pub struct HBNetworkOpaque {
    _data: (),
    _marker: core::marker::PhantomData<(*mut u8, PhantomPinned)>,
}
/// Error codes for HoneyBadgerMpcEngine FFI operations
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HBEngineErrorCode {
    /// Operation succeeded
    HBEngineSuccess = 0,
    /// Null pointer provided
    HBEngineNullPointer = 1,
    /// Engine not ready (preprocessing not complete)
    HBEngineNotReady = 2,
    /// Network error during MPC operation
    HBEngineNetworkError = 3,
    /// Preprocessing failed
    HBEnginePreprocessingFailed = 4,
    /// Multiplication operation failed
    HBEngineMultiplyFailed = 5,
    /// Share opening/reconstruction failed
    HBEngineOpenShareFailed = 6,
    /// Serialization/deserialization error
    HBEngineSerializationError = 7,
    /// Invalid share type provided
    HBEngineInvalidShareType = 8,
    /// Client input initialization failed
    HBEngineClientInputFailed = 9,
    /// Client shares retrieval failed
    HBEngineGetClientSharesFailed = 10,
    /// Tokio runtime creation failed
    HBEngineRuntimeError = 11,
    /// Invalid configuration parameters
    HBEngineInvalidConfig = 12,
}

/// C-compatible representation of ShareType
///
/// The `kind` field indicates the type:
/// - 0 = Int (width is the value)
/// - 1 = Bool (width is 1 for true, 0 for false)
/// - 2 = Float (width is the value)
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct CShareType {
    /// Type kind: 0=Int, 1=Bool, 2=Float
    pub kind: u8,
    /// Width/value depending on kind
    pub width: i64,
}

impl TryFrom<CShareType> for ShareType {
    type Error = String;

    fn try_from(c: CShareType) -> Result<Self, Self::Error> {
        match c.kind {
            // kind 0 = SecretInt with bit_length
            0 => {
                let bit_length = positive_ffi_width(c.width, "secret integer bit length")?;
                ShareType::try_secret_int(bit_length).map_err(String::from)
            }
            // kind 1 = Boolean (1-bit SecretInt)
            1 => Ok(ShareType::boolean()),
            // kind 2 = SecretFixedPoint (width encodes total_bits, fractional_bits assumed default)
            2 => {
                let total_bits = positive_ffi_width(c.width, "fixed-point total bits")?;
                if total_bits <= 1 {
                    return Err("fixed-point total bits must be greater than one".to_string());
                }
                let fractional_bits = DEFAULT_FIXED_POINT_FRACTIONAL_BITS.min(total_bits - 1);
                ShareType::try_secret_fixed_point_from_bits(total_bits, fractional_bits)
                    .map_err(String::from)
            }
            // kind 3 = SecretUInt with bit_length
            3 => {
                let bit_length = positive_ffi_width(c.width, "secret unsigned integer bit length")?;
                ShareType::try_secret_uint(bit_length).map_err(String::from)
            }
            _ => Err(format!("unknown share type kind {}", c.kind)),
        }
    }
}

impl TryFrom<ShareType> for CShareType {
    type Error = String;

    fn try_from(st: ShareType) -> Result<Self, Self::Error> {
        match st {
            ShareType::SecretInt { bit_length } => Ok(CShareType {
                kind: if bit_length == 1 { 1 } else { 0 },
                width: i64::try_from(bit_length)
                    .map_err(|_| "secret integer bit length exceeds C ABI range".to_string())?,
            }),
            ShareType::SecretUInt { bit_length } => Ok(CShareType {
                kind: 3,
                width: i64::try_from(bit_length).map_err(|_| {
                    "secret unsigned integer bit length exceeds C ABI range".to_string()
                })?,
            }),
            ShareType::SecretFixedPoint { precision } => Ok(CShareType {
                kind: 2,
                width: i64::try_from(precision.k())
                    .map_err(|_| "fixed-point total bits exceeds C ABI range".to_string())?,
            }),
        }
    }
}

fn positive_ffi_width(width: i64, name: &str) -> Result<usize, String> {
    let value = usize::try_from(width).map_err(|_| format!("{name} must be non-negative"))?;
    if value == 0 {
        return Err(format!("{name} must be positive"));
    }
    Ok(value)
}

/// Creates a new VM instance
///
/// # Returns
///
/// A handle to the VM instance, or NULL if creation failed
///
/// # Safety
///
/// The returned handle must be freed with `stoffel_destroy_vm` to avoid memory leaks.
#[no_mangle]
pub extern "C" fn stoffel_create_vm() -> VMHandle {
    let vm = Box::new(VirtualMachine::new());
    Box::into_raw(vm) as VMHandle
}

/// Destroys a VM instance
///
/// # Arguments
///
/// * `handle` - Handle to the VM instance
///
/// # Safety
///
/// `handle` must be null or a live handle returned by `stoffel_create_vm`.
/// It must not be used after this function is called, and it must not be freed
/// more than once.
#[no_mangle]
pub unsafe extern "C" fn stoffel_destroy_vm(handle: VMHandle) {
    if !handle.is_null() {
        unsafe {
            let _ = Box::from_raw(handle as *mut VirtualMachine);
        }
    }
}

/// Executes a VM function and returns the result
///
/// # Arguments
///
/// * `handle` - Handle to the VM instance
/// * `function_name` - Name of the function to execute
/// * `result` - Pointer to a StoffelValue to store the result
///
/// # Returns
///
/// 0 on success, non-zero on error
///
/// # Safety
///
/// `handle` must be a live VM handle returned by `stoffel_create_vm`.
/// The function_name must be a valid null-terminated C string.
/// The result pointer must be valid and point to enough memory to store a StoffelValue.
#[no_mangle]
pub unsafe extern "C" fn stoffel_execute(
    handle: VMHandle,
    function_name: *const c_char,
    result: *mut StoffelValue,
) -> c_int {
    if handle.is_null() || function_name.is_null() || result.is_null() {
        return -1;
    }

    let vm = unsafe { &mut *(handle as *mut VirtualMachine) };
    let c_str = unsafe { CStr::from_ptr(function_name) };
    let function_name = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    match vm.execute(function_name) {
        Ok(value) => match value_to_stoffel_value(&value) {
            Ok(converted) => {
                unsafe {
                    *result = converted;
                }
                0
            }
            Err(_) => -4,
        },
        Err(_) => -3,
    }
}

/// Executes a VM function with arguments and returns the result
///
/// # Arguments
///
/// * `handle` - Handle to the VM instance
/// * `function_name` - Name of the function to execute
/// * `args` - Array of StoffelValue arguments
/// * `arg_count` - Number of arguments
/// * `result` - Pointer to a StoffelValue to store the result
///
/// # Returns
///
/// 0 on success, non-zero on error
///
/// # Safety
///
/// `handle` must be a live VM handle returned by `stoffel_create_vm`.
/// The function_name must be a valid null-terminated C string.
/// The args pointer must be valid and point to at least arg_count StoffelValue structs.
/// The result pointer must be valid and point to enough memory to store a StoffelValue.
#[no_mangle]
pub unsafe extern "C" fn stoffel_execute_with_args(
    handle: VMHandle,
    function_name: *const c_char,
    args: *const StoffelValue,
    arg_count: c_int,
    result: *mut StoffelValue,
) -> c_int {
    if handle.is_null()
        || function_name.is_null()
        || (arg_count > 0 && args.is_null())
        || result.is_null()
    {
        return -1;
    }

    let vm = unsafe { &mut *(handle as *mut VirtualMachine) };
    let c_str = unsafe { CStr::from_ptr(function_name) };
    let function_name = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    // Guard against unreasonable arg counts from C callers
    let arg_count = match usize::try_from(arg_count) {
        Ok(count) if count <= 1024 => count,
        _ => return -1,
    };

    if arg_count > 0 && args.is_null() {
        return -1;
    }

    // Convert C args to Rust Values
    let mut rust_args = Vec::with_capacity(arg_count);
    for i in 0..arg_count {
        let arg = unsafe { &*args.add(i) };
        match stoffel_value_to_value(arg) {
            Ok(value) => rust_args.push(value),
            Err(_) => return -3,
        }
    }

    match vm.execute_with_args(function_name, &rust_args) {
        Ok(value) => match value_to_stoffel_value(&value) {
            Ok(converted) => {
                unsafe {
                    *result = converted;
                }
                0
            }
            Err(_) => -5,
        },
        Err(_) => -4,
    }
}

/// Wrapper for C foreign functions to be called from Rust
struct CForeignFunctionWrapper {
    func: CForeignFunction,
}

impl CForeignFunctionWrapper {
    fn call(&self, ctx: ForeignFunctionContext) -> Result<Value, String> {
        // Convert Rust args to C args
        let c_args: Vec<StoffelValue> = ctx
            .args()
            .iter()
            .map(value_to_stoffel_value)
            .collect::<Result<Vec<_>, _>>()?;

        let mut result = StoffelValue {
            value_type: StoffelValueType::Unit,
            data: StoffelValueData { int_val: 0 },
        };

        // Call the C function
        let arg_count = c_int::try_from(c_args.len())
            .map_err(|_| "Too many C callback arguments".to_string())?;
        let status = (self.func)(c_args.as_ptr(), arg_count, &mut result);

        if status != 0 {
            return Err(format!("Foreign function returned error code: {}", status));
        }

        // Convert C result back to Rust
        stoffel_value_to_value(&result)
    }
}

/// Registers a C function with the VM
///
/// # Arguments
///
/// * `handle` - Handle to the VM instance
/// * `name` - Name of the function to register
/// * `func` - Pointer to the C function
///
/// # Returns
///
/// 0 on success, non-zero on error
///
/// # Safety
///
/// `handle` must be a live VM handle returned by `stoffel_create_vm`.
/// The name must be a valid null-terminated C string.
/// The func pointer must be valid and point to a function with the correct signature.
#[no_mangle]
pub unsafe extern "C" fn stoffel_register_foreign_function(
    handle: VMHandle,
    name: *const c_char,
    func: CForeignFunction,
) -> c_int {
    if handle.is_null() || name.is_null() {
        return -1;
    }

    let vm = unsafe { &mut *(handle as *mut VirtualMachine) };
    let c_str = unsafe { CStr::from_ptr(name) };
    let name = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let wrapper = CForeignFunctionWrapper { func };

    match vm.try_register_foreign_function(name, move |ctx| wrapper.call(ctx)) {
        Ok(()) => 0,
        Err(_) => -3,
    }
}

/// Thread-safe wrapper for C pointers
///
/// This struct wraps a raw pointer in a way that makes it safe to share
/// between threads. The actual safety is the responsibility of the C code
/// that manages the pointer.
///
/// # Safety
///
/// The user must ensure that the pointer remains valid for the lifetime of this wrapper
/// and that any operations on the pointer are thread-safe.
#[allow(dead_code)]
struct CForeignObject {
    ptr: NonNull<c_void>,
}

// SAFETY: FFI callers opt into sharing this opaque pointer across VM threads.
// The VM never dereferences it directly; synchronization and validity are the
// responsibility of the foreign object implementation.
unsafe impl Send for CForeignObject {}
unsafe impl Sync for CForeignObject {}

impl CForeignObject {
    /// Creates a new CForeignObject from a raw pointer
    ///
    /// # Safety
    ///
    /// The pointer must be valid and must remain valid for the lifetime of the wrapper.
    fn new(ptr: *mut c_void) -> Option<Self> {
        NonNull::new(ptr).map(|ptr| CForeignObject { ptr })
    }

    /// Gets the raw pointer
    ///
    /// # Safety
    ///
    /// The caller must ensure that any operations on the pointer are thread-safe.
    #[allow(dead_code)]
    fn get_ptr(&self) -> *mut c_void {
        self.ptr.as_ptr()
    }
}

/// Registers a foreign object with the VM
///
/// # Arguments
///
/// * `handle` - Handle to the VM instance
/// * `object` - Pointer to the object
/// * `result` - Pointer to a StoffelValue to store the result
///
/// # Returns
///
/// 0 on success, non-zero on error
///
/// # Safety
///
/// `handle` must be a live VM handle returned by `stoffel_create_vm`.
/// The object pointer must be valid and must remain valid for the lifetime of the VM.
/// The result pointer must be valid and point to enough memory to store a StoffelValue.
///
/// # Notes
///
/// This function wraps the raw pointer in a thread-safe wrapper that implements
/// Send and Sync. The actual safety of the pointer is the responsibility of the
/// C code that manages it.
#[no_mangle]
pub unsafe extern "C" fn stoffel_register_foreign_object(
    handle: VMHandle,
    object: *mut c_void,
    result: *mut StoffelValue,
) -> c_int {
    if handle.is_null() || object.is_null() || result.is_null() {
        return -1;
    }

    let vm = unsafe { &mut *(handle as *mut VirtualMachine) };

    // Create a thread-safe wrapper around the raw pointer
    let foreign_object = match CForeignObject::new(object) {
        Some(object) => object,
        None => return -1,
    };

    // Register the wrapped object with the VM
    let value = match vm.try_register_foreign_object_value(foreign_object) {
        Ok(value) => value,
        Err(_) => return -2,
    };

    // Convert the result to a StoffelValue
    let converted = match value_to_stoffel_value(&value) {
        Ok(converted) => converted,
        Err(_) => return -2,
    };
    unsafe {
        *result = converted;
    }

    0
}

/// Creates a new string in the VM
///
/// # Arguments
///
/// * `handle` - Handle to the VM instance
/// * `str` - Pointer to a null-terminated C string
/// * `result` - Pointer to a StoffelValue to store the result
///
/// # Returns
///
/// 0 on success, non-zero on error
///
/// # Safety
///
/// `handle` must be a live VM handle returned by `stoffel_create_vm`.
/// The str pointer must be a valid null-terminated C string.
/// The result pointer must be valid and point to enough memory to store a StoffelValue.
#[no_mangle]
pub unsafe extern "C" fn stoffel_create_string(
    handle: VMHandle,
    str: *const c_char,
    result: *mut StoffelValue,
) -> c_int {
    if handle.is_null() || str.is_null() || result.is_null() {
        return -1;
    }

    let c_str = unsafe { CStr::from_ptr(str) };
    let rust_str = match c_str.to_str() {
        Ok(s) => s,
        Err(_) => return -2,
    };

    let value = Value::String(rust_str.to_string());

    let converted = match value_to_stoffel_value(&value) {
        Ok(converted) => converted,
        Err(_) => return -3,
    };
    unsafe {
        *result = converted;
    }

    0
}

/// Converts a Rust Value to a C-compatible StoffelValue
///
/// # Arguments
///
/// * `value` - Reference to a Rust Value
///
/// # Returns
///
/// A C-compatible StoffelValue or an error if no safe ABI conversion exists
fn value_to_stoffel_value(value: &Value) -> Result<StoffelValue, String> {
    match value {
        Value::Unit => Ok(StoffelValue {
            value_type: StoffelValueType::Unit,
            data: StoffelValueData { int_val: 0 },
        }),
        Value::I64(n) => Ok(StoffelValue {
            value_type: StoffelValueType::Int,
            data: StoffelValueData { int_val: *n },
        }),
        Value::I32(n) => Ok(StoffelValue {
            value_type: StoffelValueType::Int,
            data: StoffelValueData {
                int_val: i64::from(*n),
            },
        }),
        Value::I16(n) => Ok(StoffelValue {
            value_type: StoffelValueType::Int,
            data: StoffelValueData {
                int_val: i64::from(*n),
            },
        }),
        Value::I8(n) => Ok(StoffelValue {
            value_type: StoffelValueType::Int,
            data: StoffelValueData {
                int_val: i64::from(*n),
            },
        }),
        Value::U8(n) => Ok(StoffelValue {
            value_type: StoffelValueType::Int,
            data: StoffelValueData {
                int_val: i64::from(*n),
            },
        }),
        Value::U16(n) => Ok(StoffelValue {
            value_type: StoffelValueType::Int,
            data: StoffelValueData {
                int_val: i64::from(*n),
            },
        }),
        Value::U32(n) => Ok(StoffelValue {
            value_type: StoffelValueType::Int,
            data: StoffelValueData {
                int_val: i64::from(*n),
            },
        }),
        Value::U64(n) => {
            let int_val =
                i64::try_from(*n).map_err(|_| format!("u64 value {n} exceeds C ABI int range"))?;
            Ok(StoffelValue {
                value_type: StoffelValueType::Int,
                data: StoffelValueData { int_val },
            })
        }
        Value::Float(f) => Ok(StoffelValue {
            value_type: StoffelValueType::Float,
            data: StoffelValueData { float_val: f.0 },
        }),
        Value::Bool(b) => Ok(StoffelValue {
            value_type: StoffelValueType::Bool,
            data: StoffelValueData { bool_val: *b },
        }),
        Value::String(s) => {
            // Note: This creates a memory leak as we're not freeing the CString
            // In a real implementation, you would need to handle this properly
            let c_string = CString::new(s.as_str())
                .map_err(|_| "String contains interior null byte".to_string())?;
            let ptr = c_string.into_raw();
            Ok(StoffelValue {
                value_type: StoffelValueType::String,
                data: StoffelValueData { string_val: ptr },
            })
        }
        Value::Object(object_ref) => Ok(StoffelValue {
            value_type: StoffelValueType::Object,
            data: StoffelValueData {
                object_id: object_ref.id(),
            },
        }),
        Value::Array(array_ref) => Ok(StoffelValue {
            value_type: StoffelValueType::Array,
            data: StoffelValueData {
                array_id: array_ref.id(),
            },
        }),
        Value::Foreign(foreign_ref) => Ok(StoffelValue {
            value_type: StoffelValueType::Foreign,
            data: StoffelValueData {
                foreign_id: foreign_ref.id(),
            },
        }),
        Value::Closure(_) => Ok(StoffelValue {
            value_type: StoffelValueType::Closure,
            data: StoffelValueData { closure_id: 0 }, // Simplified
        }),
        Value::Share(_, _) => Err("Cannot convert secret share value to C ABI".to_string()),
    }
}

/// Converts a C-compatible StoffelValue to a Rust Value
///
/// # Arguments
///
/// * `value` - Reference to a C-compatible StoffelValue
///
/// # Returns
///
/// A Result containing either the converted Rust Value or an error message
fn stoffel_value_to_value(value: &StoffelValue) -> Result<Value, String> {
    match value.value_type {
        StoffelValueType::Unit => Ok(Value::Unit),
        StoffelValueType::Int => unsafe { Ok(Value::I64(value.data.int_val)) },
        StoffelValueType::Float => unsafe { Ok(Value::Float(F64(value.data.float_val))) },
        StoffelValueType::Bool => unsafe { Ok(Value::Bool(value.data.bool_val)) },
        StoffelValueType::String => unsafe {
            if value.data.string_val.is_null() {
                return Err("Null string pointer".to_string());
            }
            let c_str = CStr::from_ptr(value.data.string_val);
            match c_str.to_str() {
                Ok(s) => Ok(Value::String(s.to_string())),
                Err(_) => Err("Invalid UTF-8 in string".to_string()),
            }
        },
        StoffelValueType::Object => unsafe {
            Ok(Value::from(ObjectRef::new(value.data.object_id)))
        },
        StoffelValueType::Array => unsafe { Ok(Value::from(ArrayRef::new(value.data.array_id))) },
        StoffelValueType::Foreign => unsafe {
            Ok(Value::from(ForeignObjectRef::new(value.data.foreign_id)))
        },
        StoffelValueType::Closure => Err("Closure conversion not implemented".to_string()),
    }
}

/// Frees a string created by the VM
///
/// # Arguments
///
/// * `str` - Pointer to a C string created by the VM
///
/// # Safety
///
/// The str pointer must have been created by stoffel_create_string or similar functions.
/// After this function is called, the pointer must not be used.
#[no_mangle]
pub unsafe extern "C" fn stoffel_free_string(str: *mut c_char) {
    if !str.is_null() {
        unsafe {
            let _ = CString::from_raw(str);
        }
    }
}

/// Loads bytecode into the VM
///
/// # Arguments
///
/// * `handle` - Handle to the VM instance
/// * `bytecode` - Pointer to bytecode data
/// * `bytecode_len` - Length of bytecode data in bytes
///
/// # Returns
///
/// 0 on success, non-zero on error:
/// - -1: Null handle or bytecode pointer
/// - -2: Bytecode deserialization failed
/// - -3: Function registration failed
///
/// # Safety
///
/// `handle` must be a live VM handle returned by `stoffel_create_vm`.
/// The bytecode pointer must be valid and point to at least `bytecode_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn stoffel_load_bytecode(
    handle: VMHandle,
    bytecode: *const u8,
    bytecode_len: usize,
) -> c_int {
    if handle.is_null() || bytecode.is_null() {
        return -1;
    }

    let vm = unsafe { &mut *(handle as *mut VirtualMachine) };

    // Create a byte slice from the raw pointer
    let bytes = unsafe { std::slice::from_raw_parts(bytecode, bytecode_len) };

    // Deserialize the compiled binary
    let mut cursor = Cursor::new(bytes);
    let compiled_binary = match CompiledBinary::deserialize(&mut cursor) {
        Ok(binary) => binary,
        Err(_) => return -2,
    };

    // Convert to VM functions and register them
    let vm_functions = match compiled_binary.try_to_vm_functions() {
        Ok(functions) => functions,
        Err(_) => return -3,
    };

    for function in vm_functions {
        if vm.try_register_function(function).is_err() {
            return -3;
        }
    }

    0
}

// ============================================================================
// HoneyBadgerMpcEngine FFI Functions
// ============================================================================
/// Creates a new HoneyBadgerMpcEngine
///
/// # Arguments
///
/// * `instance_id` - Unique identifier for this MPC instance
/// * `party_id` - This party's ID (0 to n-1)
/// * `n` - Total number of parties
/// * `t` - Threshold (corruption tolerance)
/// * `n_triples` - Number of Beaver triples to generate
/// * `n_random` - Number of random shares to generate
/// * `network_ptr` - Pointer to HBNetworkOpaque (QuicNetworkManager)
///
/// # Returns
///
/// Pointer to opaque engine handle, or null on failure
///
/// # Safety
///
/// `network_ptr` must be a valid, live pointer to an `HBNetworkOpaque`
/// allocated by this FFI layer.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_new(
    instance_id: u64,
    party_id: usize,
    n: usize,
    t: usize,
    n_triples: usize,
    n_random: usize,
    network_ptr: *mut HBNetworkOpaque,
) -> *mut HBEngineOpaque {
    if network_ptr.is_null() {
        return std::ptr::null_mut();
    }

    // Extract Arc<QuicNetworkManager> from the opaque pointer
    let net: Arc<QuicNetworkManager> = unsafe {
        let boxed = &*(network_ptr as *const Arc<QuicNetworkManager>);
        Arc::clone(boxed)
    };

    let session = match crate::net::MpcSessionConfig::try_new(instance_id, party_id, n, t, net) {
        Ok(session) => session,
        Err(_) => return std::ptr::null_mut(),
    };
    let config = HoneyBadgerEngineConfig::new(
        session,
        HoneyBadgerPreprocessingConfig::new(n_triples, n_random),
    );

    match HoneyBadgerMpcEngine::<ark_bls12_381::Fr, ark_bls12_381::G1Projective>::from_config(
        config,
    ) {
        Ok(engine) => {
            // engine is Arc<HoneyBadgerMpcEngine>, box it for stable FFI pointer
            Box::into_raw(Box::new(engine)) as *mut HBEngineOpaque
        }
        Err(_) => std::ptr::null_mut(),
    }
}
/// Frees a HoneyBadgerMpcEngine instance
///
/// # Safety
///
/// `engine_ptr` must be null or a live pointer created by `hb_engine_new`.
/// It must not be used after this call, and it must not be freed more than once.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_free(engine_ptr: *mut HBEngineOpaque) {
    if !engine_ptr.is_null() {
        unsafe {
            let _ = Box::from_raw(engine_ptr as *mut Arc<HoneyBadgerMpcEngine>);
        }
    }
}
/// Runs preprocessing (generates Beaver triples and random shares)
///
/// This is a blocking call that runs the async preprocessing protocol.
/// Must be called before any computation operations.
///
/// # Returns
///
/// * HBEngineSuccess on success
/// * Error code on failure
///
/// # Safety
///
/// `engine_ptr` must be null or a live pointer created by `hb_engine_new`.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_start_async(
    engine_ptr: *mut HBEngineOpaque,
) -> HBEngineErrorCode {
    if engine_ptr.is_null() {
        return HBEngineErrorCode::HBEngineNullPointer;
    }

    let engine = unsafe { &*(engine_ptr as *const Arc<HoneyBadgerMpcEngine>) };

    // Create tokio runtime for blocking on async
    let rt = match tokio::runtime::Runtime::new() {
        Ok(rt) => rt,
        Err(_) => return HBEngineErrorCode::HBEngineRuntimeError,
    };

    match rt.block_on(engine.start_async()) {
        Ok(()) => HBEngineErrorCode::HBEngineSuccess,
        Err(_) => HBEngineErrorCode::HBEnginePreprocessingFailed,
    }
}
/// Checks if the engine is ready (preprocessing complete)
///
/// # Returns
///
/// 1 if ready, 0 if not ready or null pointer
///
/// # Safety
///
/// `engine_ptr` must be null or a live pointer created by `hb_engine_new`.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_is_ready(engine_ptr: *mut HBEngineOpaque) -> c_int {
    if engine_ptr.is_null() {
        return 0;
    }

    let engine = unsafe { &*(engine_ptr as *const Arc<HoneyBadgerMpcEngine>) };
    if engine.is_ready() {
        1
    } else {
        0
    }
}
/// Performs secure multiplication of two shares
///
/// # Arguments
///
/// * `engine_ptr` - Engine handle
/// * `share_type` - Type information for the shares
/// * `left_ptr` - Pointer to left share bytes
/// * `left_len` - Length of left share
/// * `right_ptr` - Pointer to right share bytes
/// * `right_len` - Length of right share
/// * `result_ptr` - Output: pointer to result bytes (caller must free with hb_free_bytes)
/// * `result_len_ptr` - Output: length of result bytes
///
/// # Returns
///
/// * HBEngineSuccess on success, error code on failure
///
/// # Safety
///
/// `engine_ptr` must be a live pointer created by `hb_engine_new`.
/// `left_ptr` and `right_ptr` must point to `left_len` and `right_len` bytes
/// respectively. `result_ptr` and `result_len_ptr` must be valid output
/// pointers; successful results must be released with `hb_free_bytes`.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_multiply_share_async(
    engine_ptr: *mut HBEngineOpaque,
    share_type: CShareType,
    left_ptr: *const u8,
    left_len: usize,
    right_ptr: *const u8,
    right_len: usize,
    result_ptr: *mut *mut u8,
    result_len_ptr: *mut usize,
) -> HBEngineErrorCode {
    if engine_ptr.is_null()
        || left_ptr.is_null()
        || right_ptr.is_null()
        || result_ptr.is_null()
        || result_len_ptr.is_null()
    {
        return HBEngineErrorCode::HBEngineNullPointer;
    }

    if left_len > MAX_FFI_SHARE_LEN || right_len > MAX_FFI_SHARE_LEN {
        return HBEngineErrorCode::HBEngineInvalidShareType;
    }
    let engine = unsafe { &*(engine_ptr as *const Arc<HoneyBadgerMpcEngine>) };
    let left = unsafe { std::slice::from_raw_parts(left_ptr, left_len) };
    let right = unsafe { std::slice::from_raw_parts(right_ptr, right_len) };
    let ty = match ShareType::try_from(share_type) {
        Ok(ty) => ty,
        Err(_) => return HBEngineErrorCode::HBEngineInvalidShareType,
    };

    let rt = match tokio::runtime::Runtime::new() {
        Ok(rt) => rt,
        Err(_) => return HBEngineErrorCode::HBEngineRuntimeError,
    };

    match rt.block_on(engine.multiply_share_async(ty, left, right)) {
        Ok(result) => {
            unsafe {
                write_ffi_result_bytes(result.into_bytes(), result_ptr, result_len_ptr);
            }
            HBEngineErrorCode::HBEngineSuccess
        }
        Err(_) => HBEngineErrorCode::HBEngineMultiplyFailed,
    }
}
/// Opens (reconstructs) a shared value
///
/// # Arguments
///
/// * `engine_ptr` - Engine handle
/// * `share_type` - Type information for the share
/// * `share_ptr` - Pointer to share bytes
/// * `share_len` - Length of share bytes
/// * `result_ptr` - Output: StoffelValue containing the reconstructed value
///
/// # Returns
///
/// * HBEngineSuccess on success, error code on failure
///
/// # Safety
///
/// `engine_ptr` must be a live pointer created by `hb_engine_new`.
/// `share_ptr` must point to `share_len` bytes, and `result_ptr` must be a
/// valid output pointer.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_open_share(
    engine_ptr: *mut HBEngineOpaque,
    share_type: CShareType,
    share_ptr: *const u8,
    share_len: usize,
    result_ptr: *mut StoffelValue,
) -> HBEngineErrorCode {
    if engine_ptr.is_null() || share_ptr.is_null() || result_ptr.is_null() {
        return HBEngineErrorCode::HBEngineNullPointer;
    }

    if share_len > MAX_FFI_SHARE_LEN {
        return HBEngineErrorCode::HBEngineInvalidShareType;
    }
    let engine = unsafe { &*(engine_ptr as *const Arc<HoneyBadgerMpcEngine>) };
    let share_bytes = unsafe { std::slice::from_raw_parts(share_ptr, share_len) };
    let ty = match ShareType::try_from(share_type) {
        Ok(ty) => ty,
        Err(_) => return HBEngineErrorCode::HBEngineInvalidShareType,
    };

    // open_share is sync in the current implementation (uses global registry)
    match engine.open_share(ty, share_bytes) {
        Ok(value) => {
            let value = crate::net::curve::clear_share_value_to_vm_value(ty, value);
            let converted = match value_to_stoffel_value(&value) {
                Ok(converted) => converted,
                Err(_) => return HBEngineErrorCode::HBEngineOpenShareFailed,
            };
            unsafe {
                *result_ptr = converted;
            }
            HBEngineErrorCode::HBEngineSuccess
        }
        Err(_) => HBEngineErrorCode::HBEngineOpenShareFailed,
    }
}
/// Initialize input shares from a client
///
/// # Arguments
///
/// * `engine_ptr` - Engine handle
/// * `client_id` - Client identifier
/// * `shares_data` - Serialized shares data (ark_serialize compressed format)
/// * `shares_len` - Length of shares data
///
/// # Returns
///
/// * HBEngineSuccess on success, error code on failure
///
/// # Note
///
/// The shares_data must be serialized using ark_serialize compressed format.
/// Format: [num_shares: u32][share1_bytes][share2_bytes]...
///
/// # Safety
///
/// `engine_ptr` must be a live pointer created by `hb_engine_new`.
/// `shares_data` must point to `shares_len` bytes.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_init_client_input(
    engine_ptr: *mut HBEngineOpaque,
    client_id: u64,
    shares_data: *const u8,
    shares_len: usize,
) -> HBEngineErrorCode {
    use ark_bls12_381::Fr;
    use ark_serialize::CanonicalDeserialize;
    use stoffelmpc_mpc::honeybadger::robust_interpolate::robust_interpolate::RobustShare;

    if engine_ptr.is_null() || shares_data.is_null() {
        return HBEngineErrorCode::HBEngineNullPointer;
    }

    let engine = unsafe { &*(engine_ptr as *const Arc<HoneyBadgerMpcEngine>) };
    let shares_bytes = unsafe { std::slice::from_raw_parts(shares_data, shares_len) };

    // Deserialize shares from bytes using ark_serialize
    // Format: [num_shares: u32][share1_bytes][share2_bytes]...
    if shares_len < 4 {
        return HBEngineErrorCode::HBEngineSerializationError;
    }
    let num_shares = match usize::try_from(u32::from_le_bytes([
        shares_bytes[0],
        shares_bytes[1],
        shares_bytes[2],
        shares_bytes[3],
    ])) {
        Ok(num_shares) => num_shares,
        Err(_) => return HBEngineErrorCode::HBEngineSerializationError,
    };
    let mut cursor = &shares_bytes[4..];
    let mut shares: Vec<RobustShare<Fr>> = Vec::with_capacity(num_shares);

    for _ in 0..num_shares {
        match RobustShare::<Fr>::deserialize_compressed(&mut cursor) {
            Ok(share) => shares.push(share),
            Err(_) => return HBEngineErrorCode::HBEngineSerializationError,
        }
    }

    let rt = match tokio::runtime::Runtime::new() {
        Ok(rt) => rt,
        Err(_) => return HBEngineErrorCode::HBEngineRuntimeError,
    };

    let client_id = match usize::try_from(client_id) {
        Ok(client_id) => client_id,
        Err(_) => return HBEngineErrorCode::HBEngineInvalidConfig,
    };

    match rt.block_on(engine.init_client_input(client_id, shares)) {
        Ok(()) => HBEngineErrorCode::HBEngineSuccess,
        Err(_) => HBEngineErrorCode::HBEngineClientInputFailed,
    }
}
/// Get shares for a specific client
///
/// # Arguments
///
/// * `engine_ptr` - Engine handle
/// * `client_id` - Client identifier
/// * `result_ptr` - Output: pointer to serialized shares (ark_serialize compressed format)
/// * `result_len_ptr` - Output: length of result
///
/// # Returns
///
/// * HBEngineSuccess on success, error code on failure
///
/// # Note
///
/// Caller must free the result bytes with hb_free_bytes.
/// Format: [num_shares: u32][share1_bytes][share2_bytes]...
///
/// # Safety
///
/// `engine_ptr` must be a live pointer created by `hb_engine_new`.
/// `result_ptr` and `result_len_ptr` must be valid output pointers; successful
/// results must be released with `hb_free_bytes`.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_get_client_shares(
    engine_ptr: *mut HBEngineOpaque,
    client_id: u64,
    result_ptr: *mut *mut u8,
    result_len_ptr: *mut usize,
) -> HBEngineErrorCode {
    use ark_serialize::CanonicalSerialize;

    if engine_ptr.is_null() || result_ptr.is_null() || result_len_ptr.is_null() {
        return HBEngineErrorCode::HBEngineNullPointer;
    }

    let engine = unsafe { &*(engine_ptr as *const Arc<HoneyBadgerMpcEngine>) };

    let rt = match tokio::runtime::Runtime::new() {
        Ok(rt) => rt,
        Err(_) => return HBEngineErrorCode::HBEngineRuntimeError,
    };

    let client_id = match usize::try_from(client_id) {
        Ok(client_id) => client_id,
        Err(_) => return HBEngineErrorCode::HBEngineInvalidConfig,
    };

    match rt.block_on(engine.get_client_shares(client_id)) {
        Ok(shares) => {
            // Serialize shares using ark_serialize
            // Format: [num_shares: u32][share1_bytes][share2_bytes]...
            let mut bytes = Vec::new();
            let share_count = match u32::try_from(shares.len()) {
                Ok(count) => count,
                Err(_) => return HBEngineErrorCode::HBEngineSerializationError,
            };
            bytes.extend_from_slice(&share_count.to_le_bytes());
            for share in &shares {
                if share.serialize_compressed(&mut bytes).is_err() {
                    return HBEngineErrorCode::HBEngineSerializationError;
                }
            }
            unsafe {
                write_ffi_result_bytes(bytes, result_ptr, result_len_ptr);
            }
            HBEngineErrorCode::HBEngineSuccess
        }
        Err(_) => HBEngineErrorCode::HBEngineGetClientSharesFailed,
    }
}
/// Get the party ID of the engine
///
/// # Safety
///
/// `engine_ptr` must be null or a live pointer created by `hb_engine_new`.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_party_id(engine_ptr: *mut HBEngineOpaque) -> usize {
    if engine_ptr.is_null() {
        return 0;
    }
    let engine = unsafe { &*(engine_ptr as *const Arc<HoneyBadgerMpcEngine>) };
    engine.party().id()
}
/// Get the instance ID of the engine
///
/// # Safety
///
/// `engine_ptr` must be null or a live pointer created by `hb_engine_new`.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_instance_id(engine_ptr: *mut HBEngineOpaque) -> u64 {
    if engine_ptr.is_null() {
        return 0;
    }
    let engine = unsafe { &*(engine_ptr as *const Arc<HoneyBadgerMpcEngine>) };
    engine.instance().id()
}
/// Get the protocol name (returns static string, do not free)
///
/// # Safety
///
/// `engine_ptr` must be null or a live pointer created by `hb_engine_new`.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_protocol_name(engine_ptr: *mut HBEngineOpaque) -> *const c_char {
    static PROTOCOL_NAME: &[u8] = b"honeybadger-mpc\0";
    if engine_ptr.is_null() {
        return std::ptr::null();
    }
    PROTOCOL_NAME.as_ptr() as *const c_char
}
/// Get the network handle from the engine
///
/// Returns a cloned network pointer. Caller must free with hb_network_free.
///
/// # Safety
///
/// `engine_ptr` must be null or a live pointer created by `hb_engine_new`.
#[no_mangle]
pub unsafe extern "C" fn hb_engine_get_network(
    engine_ptr: *mut HBEngineOpaque,
) -> *mut HBNetworkOpaque {
    if engine_ptr.is_null() {
        return std::ptr::null_mut();
    }

    let engine = unsafe { &*(engine_ptr as *const Arc<HoneyBadgerMpcEngine>) };
    let net = engine.net();

    // Box the Arc for stable FFI pointer
    Box::into_raw(Box::new(net)) as *mut HBNetworkOpaque
}
/// Free a network handle obtained from hb_engine_get_network
///
/// # Safety
///
/// `network_ptr` must be null or a live pointer returned by
/// `hb_engine_get_network`. It must not be used after this call, and it must not
/// be freed more than once.
#[no_mangle]
pub unsafe extern "C" fn hb_network_free(network_ptr: *mut HBNetworkOpaque) {
    if !network_ptr.is_null() {
        unsafe {
            let _ = Box::from_raw(network_ptr as *mut Arc<QuicNetworkManager>);
        }
    }
}
/// Free bytes allocated by engine functions (e.g., multiply_share_async result)
///
/// # Safety
///
/// `ptr` must be null or a pointer returned by an FFI function in this module
/// with exactly the same `len`.
#[no_mangle]
pub unsafe extern "C" fn hb_free_bytes(ptr: *mut u8, len: usize) {
    unsafe {
        free_ffi_result_bytes(ptr, len);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn c_foreign_object_rejects_null_pointer() {
        assert!(CForeignObject::new(std::ptr::null_mut()).is_none());
    }

    #[test]
    fn c_foreign_object_preserves_opaque_pointer() {
        let mut value = 42u8;
        let ptr = (&mut value as *mut u8).cast::<c_void>();

        let object = CForeignObject::new(ptr).expect("non-null pointer is accepted");

        assert_eq!(object.get_ptr(), ptr);
    }
}

// ============================================================================
// HoneyBadgerMpcEngine FFI - Unit Tests
// ============================================================================

#[cfg(test)]
mod hb_engine_tests {
    use super::*;

    #[test]
    fn test_share_type_conversion_int() {
        let c_int = CShareType { kind: 0, width: 64 };
        let st = ShareType::try_from(c_int).expect("valid secret int share type");
        assert!(matches!(st, ShareType::SecretInt { bit_length: 64 }));
    }

    #[test]
    fn test_share_type_conversion_bool() {
        // Both width values should result in boolean (1-bit SecretInt)
        let c_bool_true = CShareType { kind: 1, width: 1 };
        let st = ShareType::try_from(c_bool_true).expect("valid boolean share type");
        assert!(matches!(st, ShareType::SecretInt { bit_length: 1 }));

        let c_bool_false = CShareType { kind: 1, width: 0 };
        let st = ShareType::try_from(c_bool_false).expect("valid boolean share type");
        assert!(matches!(st, ShareType::SecretInt { bit_length: 1 }));
    }

    #[test]
    fn test_share_type_conversion_float() {
        let c_float = CShareType { kind: 2, width: 42 };
        let st = ShareType::try_from(c_float).expect("valid fixed-point share type");
        assert!(matches!(st, ShareType::SecretFixedPoint { .. }));
    }

    #[test]
    fn share_type_conversion_rejects_invalid_int_width() {
        assert!(ShareType::try_from(CShareType { kind: 0, width: 0 }).is_err());
        assert!(ShareType::try_from(CShareType { kind: 0, width: -1 }).is_err());
    }

    #[test]
    fn share_type_conversion_rejects_invalid_kind() {
        assert!(ShareType::try_from(CShareType {
            kind: 99,
            width: 64
        })
        .is_err());
    }

    #[test]
    fn share_type_conversion_to_c_preserves_kind_and_width() {
        let c_int =
            CShareType::try_from(ShareType::secret_int(64)).expect("secret int should fit C ABI");
        assert_eq!(c_int.kind, 0);
        assert_eq!(c_int.width, 64);

        let c_bool = CShareType::try_from(ShareType::boolean()).expect("bool should fit C ABI");
        assert_eq!(c_bool.kind, 1);
        assert_eq!(c_bool.width, 1);

        let c_fixed = CShareType::try_from(ShareType::secret_fixed_point_from_bits(42, 16))
            .expect("fixed-point should fit C ABI");
        assert_eq!(c_fixed.kind, 2);
        assert_eq!(c_fixed.width, 42);
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn share_type_conversion_to_c_rejects_unrepresentable_width() {
        let too_wide = ShareType::SecretInt {
            bit_length: usize::MAX,
        };

        assert!(CShareType::try_from(too_wide).is_err());
    }

    #[test]
    fn test_null_pointer_handling() {
        unsafe {
            assert_eq!(
                hb_engine_start_async(std::ptr::null_mut()),
                HBEngineErrorCode::HBEngineNullPointer
            );

            assert_eq!(hb_engine_is_ready(std::ptr::null_mut()), 0);
            assert!(hb_engine_get_network(std::ptr::null_mut()).is_null());
            assert_eq!(hb_engine_party_id(std::ptr::null_mut()), 0);
            assert_eq!(hb_engine_instance_id(std::ptr::null_mut()), 0);
            assert!(hb_engine_protocol_name(std::ptr::null_mut()).is_null());
        }
    }

    #[test]
    fn test_hb_engine_new_null_network() {
        let engine = unsafe { hb_engine_new(1, 0, 5, 1, 8, 16, std::ptr::null_mut()) };
        assert!(engine.is_null());
    }

    #[test]
    fn test_hb_engine_new_invalid_topology_rejected() {
        let net = Arc::new(QuicNetworkManager::new());
        let net_ptr = &net as *const Arc<QuicNetworkManager> as *mut HBNetworkOpaque;

        let engine = unsafe { hb_engine_new(1, 5, 5, 1, 8, 16, net_ptr) };

        assert!(engine.is_null(), "party id outside n must be rejected");
    }

    #[test]
    fn test_hb_engine_free_null() {
        // Should not crash
        unsafe { hb_engine_free(std::ptr::null_mut()) };
    }

    #[test]
    fn test_hb_network_free_null() {
        // Should not crash
        unsafe { hb_network_free(std::ptr::null_mut()) };
    }

    #[test]
    fn test_hb_free_bytes_null() {
        // Should not crash
        unsafe {
            hb_free_bytes(std::ptr::null_mut(), 0);
            hb_free_bytes(std::ptr::null_mut(), 10);
        }
    }
}

// ============================================================================
// AVSS Engine FFI Types and Functions
//
// FFI export names keep the `adkg_` prefix for ABI compatibility with existing
// C/SDK consumers. Internal Rust types use the `Avss` prefix.
// ============================================================================
mod avss_ffi {
    use super::*;
    use crate::net::avss_engine::{AvssEngineConfig, AvssMpcEngine, AvssOperations};
    use crate::net::mpc_engine::MpcEngine;
    use ark_serialize::CanonicalDeserialize;
    use ark_std::rand::SeedableRng;
    use std::future::Future;
    use std::sync::Arc;
    use stoffelnet::transports::quic::QuicNetworkManager;

    fn block_on_avss<Fut, T>(fut: Fut) -> Result<T, String>
    where
        Fut: Future<Output = Result<T, String>> + Send + 'static,
        T: Send + 'static,
    {
        match tokio::runtime::Handle::try_current() {
            Ok(handle) =>
            {
                #[allow(deprecated)]
                match handle.runtime_flavor() {
                    tokio::runtime::RuntimeFlavor::MultiThread => {
                        tokio::task::block_in_place(|| handle.block_on(fut))
                    }
                    tokio::runtime::RuntimeFlavor::CurrentThread => std::thread::spawn(move || {
                        let rt = tokio::runtime::Builder::new_current_thread()
                            .enable_all()
                            .build()
                            .map_err(|e| format!("failed to build tokio runtime: {}", e))?;
                        rt.block_on(fut)
                    })
                    .join()
                    .map_err(|_| "thread panicked in block_on_avss".to_string())?,
                    _ => Err("unsupported tokio runtime flavor".to_string()),
                }
            }
            Err(_) => {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .map_err(|e| format!("failed to build tokio runtime: {}", e))?;
                rt.block_on(fut)
            }
        }
    }

    /// C-compatible curve configuration for AVSS.
    /// Variants are constructed by C/SDK callers via integer discriminants.
    #[repr(C)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[allow(dead_code)]
    pub enum CAvssCurveConfig {
        Bls12_381 = 0,
        Bn254 = 1,
        Curve25519 = 2,
        Ed25519 = 3,
        Secp256k1 = 4,
        P256 = 5,
    }

    impl CAvssCurveConfig {
        fn from_ffi(value: u32) -> Option<Self> {
            match value {
                0 => Some(CAvssCurveConfig::Bls12_381),
                1 => Some(CAvssCurveConfig::Bn254),
                2 => Some(CAvssCurveConfig::Curve25519),
                3 => Some(CAvssCurveConfig::Ed25519),
                4 => Some(CAvssCurveConfig::Secp256k1),
                5 => Some(CAvssCurveConfig::P256),
                _ => None,
            }
        }
    }

    /// Internal wrapper that erases the generic (F, G) types behind trait objects.
    /// The opaque pointer stores a `Box<AvssFfiWrapper>`.
    struct AvssFfiWrapper {
        engine: Arc<dyn MpcEngine>,
        avss_ops: Arc<dyn AvssOperations + Send + Sync>,
    }

    /// Opaque pointer type for AvssMpcEngine
    #[repr(C)]
    pub struct AvssEngineOpaque {
        _data: (),
        _marker: core::marker::PhantomData<(*mut u8, PhantomPinned)>,
    }

    /// Error codes for AVSS engine FFI operations.
    /// Variants are matched by C/SDK callers via integer discriminants.
    #[repr(C)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[allow(dead_code)]
    pub enum AvssEngineErrorCode {
        /// Operation succeeded
        Success = 0,
        /// Null pointer provided
        NullPointer = 1,
        /// Engine not ready
        NotReady = 2,
        /// Key generation failed
        KeyGenFailed = 3,
        /// Serialization error
        SerializationError = 4,
        /// Session not found
        SessionNotFound = 5,
        /// Invalid commitment index
        InvalidCommitmentIndex = 6,
        /// Tokio runtime creation failed
        RuntimeError = 7,
        /// Invalid curve configuration
        InvalidCurveConfig = 8,
    }

    /// Generic helper: deserialize keys, create an `AvssMpcEngine<F, G>`, and wrap it.
    fn create_engine_inner<F, G>(
        instance_id: u64,
        party_id: usize,
        n: usize,
        t: usize,
        net: Arc<QuicNetworkManager>,
        sk_bytes: &[u8],
        pk_bytes: &[u8],
    ) -> Result<AvssFfiWrapper, String>
    where
        F: crate::net::curve::SupportedMpcField + ark_std::UniformRand,
        G: ark_ec::CurveGroup<ScalarField = F> + Send + Sync + 'static,
    {
        let sk_i: F = if sk_bytes.is_empty() {
            let mut rng = ark_std::rand::rngs::StdRng::from_entropy();
            F::rand(&mut rng)
        } else {
            CanonicalDeserialize::deserialize_compressed(sk_bytes)
                .map_err(|e| format!("failed to deserialize secret key: {}", e))?
        };

        let pk_map: Vec<G> = Vec::<G>::deserialize_compressed(pk_bytes)
            .map_err(|e| format!("failed to deserialize public key map: {}", e))?;
        if pk_map.len() != n {
            return Err(format!(
                "public key map length {} does not match n={}",
                pk_map.len(),
                n
            ));
        }

        let session = crate::net::MpcSessionConfig::try_new(instance_id, party_id, n, t, net)
            .map_err(|error| error.to_string())?;
        let engine = block_on_avss(AvssMpcEngine::<F, G>::from_config(AvssEngineConfig::new(
            session,
            sk_i,
            Arc::new(pk_map),
        )))?;

        let engine_arc: Arc<AvssMpcEngine<F, G>> = engine;
        Ok(AvssFfiWrapper {
            engine: engine_arc.clone() as Arc<dyn MpcEngine>,
            avss_ops: engine_arc as Arc<dyn AvssOperations + Send + Sync>,
        })
    }

    fn create_bls12381_engine(
        instance_id: u64,
        party_id: usize,
        n: usize,
        t: usize,
        net: Arc<QuicNetworkManager>,
        sk_bytes: &[u8],
        pk_bytes: &[u8],
    ) -> Result<AvssFfiWrapper, String> {
        create_engine_inner::<ark_bls12_381::Fr, ark_bls12_381::G1Projective>(
            instance_id,
            party_id,
            n,
            t,
            net,
            sk_bytes,
            pk_bytes,
        )
    }

    fn create_bn254_engine(
        instance_id: u64,
        party_id: usize,
        n: usize,
        t: usize,
        net: Arc<QuicNetworkManager>,
        sk_bytes: &[u8],
        pk_bytes: &[u8],
    ) -> Result<AvssFfiWrapper, String> {
        create_engine_inner::<ark_bn254::Fr, ark_bn254::G1Projective>(
            instance_id,
            party_id,
            n,
            t,
            net,
            sk_bytes,
            pk_bytes,
        )
    }

    fn create_curve25519_engine(
        instance_id: u64,
        party_id: usize,
        n: usize,
        t: usize,
        net: Arc<QuicNetworkManager>,
        sk_bytes: &[u8],
        pk_bytes: &[u8],
    ) -> Result<AvssFfiWrapper, String> {
        create_engine_inner::<ark_curve25519::Fr, ark_curve25519::EdwardsProjective>(
            instance_id,
            party_id,
            n,
            t,
            net,
            sk_bytes,
            pk_bytes,
        )
    }

    fn create_ed25519_engine(
        instance_id: u64,
        party_id: usize,
        n: usize,
        t: usize,
        net: Arc<QuicNetworkManager>,
        sk_bytes: &[u8],
        pk_bytes: &[u8],
    ) -> Result<AvssFfiWrapper, String> {
        create_engine_inner::<ark_ed25519::Fr, ark_ed25519::EdwardsProjective>(
            instance_id,
            party_id,
            n,
            t,
            net,
            sk_bytes,
            pk_bytes,
        )
    }

    fn create_secp256k1_engine(
        instance_id: u64,
        party_id: usize,
        n: usize,
        t: usize,
        net: Arc<QuicNetworkManager>,
        sk_bytes: &[u8],
        pk_bytes: &[u8],
    ) -> Result<AvssFfiWrapper, String> {
        create_engine_inner::<ark_secp256k1::Fr, ark_secp256k1::Projective>(
            instance_id,
            party_id,
            n,
            t,
            net,
            sk_bytes,
            pk_bytes,
        )
    }

    fn create_p256_engine(
        instance_id: u64,
        party_id: usize,
        n: usize,
        t: usize,
        net: Arc<QuicNetworkManager>,
        sk_bytes: &[u8],
        pk_bytes: &[u8],
    ) -> Result<AvssFfiWrapper, String> {
        create_engine_inner::<ark_secp256r1::Fr, ark_secp256r1::Projective>(
            instance_id,
            party_id,
            n,
            t,
            net,
            sk_bytes,
            pk_bytes,
        )
    }

    /// Creates a new AVSS engine
    ///
    /// # Arguments
    /// * `instance_id` - Unique instance identifier
    /// * `party_id` - This party's ID (0 to n-1)
    /// * `n` - Total number of parties
    /// * `t` - Threshold
    /// * `network_ptr` - Pointer to a QuicNetworkManager (same opaque type as HB)
    /// * `curve_config` - Curve configuration (0 = BLS12-381, 1 = BN254, 2 = Curve25519, 3 = Ed25519, 4 = secp256k1, 5 = P-256)
    /// * `sk_bytes` - Secret key bytes (serialized Fr element), or null for random key
    /// * `sk_len` - Length of secret key bytes
    /// * `pk_map_ptr` - Pointer to serialized public key map (required, must not be null)
    /// * `pk_map_len` - Length of public key map bytes (must be > 0)
    ///
    /// # Returns
    /// Pointer to opaque engine handle, or null on failure
    ///
    /// # Safety
    /// `network_ptr` must be a valid, live pointer to an
    /// `Arc<QuicNetworkManager>` allocated by this FFI layer. When non-null,
    /// `sk_bytes` must point to `sk_len` bytes. `pk_map_ptr` must point to
    /// `pk_map_len` bytes.
    #[no_mangle]
    pub unsafe extern "C" fn adkg_engine_new(
        instance_id: u64,
        party_id: usize,
        n: usize,
        t: usize,
        network_ptr: *mut c_void,
        curve_config: u32,
        sk_bytes: *const u8,
        sk_len: usize,
        pk_map_ptr: *const u8,
        pk_map_len: usize,
    ) -> *mut AvssEngineOpaque {
        if network_ptr.is_null() {
            return std::ptr::null_mut();
        }
        if pk_map_ptr.is_null() || pk_map_len == 0 {
            return std::ptr::null_mut();
        }

        // Extract network from opaque pointer
        let net: Arc<QuicNetworkManager> = unsafe {
            let boxed = &*(network_ptr as *const Arc<QuicNetworkManager>);
            Arc::clone(boxed)
        };

        let sk_slice = if sk_bytes.is_null() || sk_len == 0 {
            &[]
        } else {
            unsafe { std::slice::from_raw_parts(sk_bytes, sk_len) }
        };

        let pk_slice = unsafe { std::slice::from_raw_parts(pk_map_ptr, pk_map_len) };

        let curve_config = match CAvssCurveConfig::from_ffi(curve_config) {
            Some(config) => config,
            None => return std::ptr::null_mut(),
        };

        let wrapper = match curve_config {
            CAvssCurveConfig::Bls12_381 => {
                create_bls12381_engine(instance_id, party_id, n, t, net, sk_slice, pk_slice)
            }
            CAvssCurveConfig::Bn254 => {
                create_bn254_engine(instance_id, party_id, n, t, net, sk_slice, pk_slice)
            }
            CAvssCurveConfig::Curve25519 => {
                create_curve25519_engine(instance_id, party_id, n, t, net, sk_slice, pk_slice)
            }
            CAvssCurveConfig::Ed25519 => {
                create_ed25519_engine(instance_id, party_id, n, t, net, sk_slice, pk_slice)
            }
            CAvssCurveConfig::Secp256k1 => {
                create_secp256k1_engine(instance_id, party_id, n, t, net, sk_slice, pk_slice)
            }
            CAvssCurveConfig::P256 => {
                create_p256_engine(instance_id, party_id, n, t, net, sk_slice, pk_slice)
            }
        };

        match wrapper {
            Ok(w) => {
                if let Err(e) = w.engine.start() {
                    eprintln!("adkg_engine_new: engine start failed: {}", e);
                    return std::ptr::null_mut();
                }
                Box::into_raw(Box::new(w)) as *mut AvssEngineOpaque
            }
            Err(e) => {
                eprintln!("adkg_engine_new: {}", e);
                std::ptr::null_mut()
            }
        }
    }

    /// Frees an AVSS engine instance
    ///
    /// # Safety
    /// `engine_ptr` must be null or a live pointer created by `adkg_engine_new`.
    /// It must not be used after this call, and it must not be freed more than
    /// once.
    #[no_mangle]
    pub unsafe extern "C" fn adkg_engine_free(engine_ptr: *mut AvssEngineOpaque) {
        if !engine_ptr.is_null() {
            unsafe {
                let _ = Box::from_raw(engine_ptr as *mut AvssFfiWrapper);
            }
        }
    }

    /// Helper to get the wrapper from an opaque pointer
    unsafe fn get_wrapper<'a>(ptr: *mut AvssEngineOpaque) -> &'a AvssFfiWrapper {
        &*(ptr as *const AvssFfiWrapper)
    }

    /// Generates a new distributed share under the given key name
    ///
    /// Returns serialized share bytes via out parameters on success.
    /// Caller must free result bytes with adkg_free_bytes.
    ///
    /// # Safety
    /// `engine_ptr` must be a live pointer created by `adkg_engine_new`.
    /// `key_name` must be a valid null-terminated C string. `result_ptr` and
    /// `result_len_ptr` must be valid output pointers; successful results must
    /// be released with `adkg_free_bytes`.
    #[no_mangle]
    pub unsafe extern "C" fn adkg_engine_generate_share(
        engine_ptr: *mut AvssEngineOpaque,
        key_name: *const c_char,
        result_ptr: *mut *mut u8,
        result_len_ptr: *mut usize,
    ) -> AvssEngineErrorCode {
        if engine_ptr.is_null()
            || key_name.is_null()
            || result_ptr.is_null()
            || result_len_ptr.is_null()
        {
            return AvssEngineErrorCode::NullPointer;
        }

        let wrapper = unsafe { get_wrapper(engine_ptr) };

        let c_str = unsafe { CStr::from_ptr(key_name) };
        let key_name_str = match c_str.to_str() {
            Ok(s) => s.to_string(),
            Err(_) => return AvssEngineErrorCode::SerializationError,
        };

        let avss_ops = Arc::clone(&wrapper.avss_ops);
        match block_on_avss(async move { avss_ops.avss_generate_share(key_name_str).await }) {
            Ok(share_bytes) => {
                unsafe {
                    write_ffi_result_bytes(share_bytes, result_ptr, result_len_ptr);
                }
                AvssEngineErrorCode::Success
            }
            Err(_) => AvssEngineErrorCode::KeyGenFailed,
        }
    }

    /// Get the public key for a stored share by key name
    ///
    /// Caller must free result bytes with adkg_free_bytes.
    ///
    /// # Safety
    /// `engine_ptr` must be a live pointer created by `adkg_engine_new`.
    /// `key_name` must be a valid null-terminated C string. `result_ptr` and
    /// `result_len_ptr` must be valid output pointers; successful results must
    /// be released with `adkg_free_bytes`.
    #[no_mangle]
    pub unsafe extern "C" fn adkg_engine_get_public_key(
        engine_ptr: *mut AvssEngineOpaque,
        key_name: *const c_char,
        result_ptr: *mut *mut u8,
        result_len_ptr: *mut usize,
    ) -> AvssEngineErrorCode {
        if engine_ptr.is_null()
            || key_name.is_null()
            || result_ptr.is_null()
            || result_len_ptr.is_null()
        {
            return AvssEngineErrorCode::NullPointer;
        }

        let wrapper = unsafe { get_wrapper(engine_ptr) };

        let c_str = unsafe { CStr::from_ptr(key_name) };
        let key_name_str = match c_str.to_str() {
            Ok(s) => s,
            Err(_) => return AvssEngineErrorCode::SerializationError,
        };

        match wrapper.avss_ops.avss_get_commitment(key_name_str, 0) {
            Ok(bytes) => {
                unsafe {
                    write_ffi_result_bytes(bytes, result_ptr, result_len_ptr);
                }
                AvssEngineErrorCode::Success
            }
            Err(_) => AvssEngineErrorCode::SessionNotFound,
        }
    }

    /// Get a commitment at a specific index for a stored share by key name
    ///
    /// Caller must free result bytes with adkg_free_bytes.
    ///
    /// # Safety
    /// `engine_ptr` must be a live pointer created by `adkg_engine_new`.
    /// `key_name` must be a valid null-terminated C string. `result_ptr` and
    /// `result_len_ptr` must be valid output pointers; successful results must
    /// be released with `adkg_free_bytes`.
    #[no_mangle]
    pub unsafe extern "C" fn adkg_engine_get_commitment(
        engine_ptr: *mut AvssEngineOpaque,
        key_name: *const c_char,
        index: usize,
        result_ptr: *mut *mut u8,
        result_len_ptr: *mut usize,
    ) -> AvssEngineErrorCode {
        if engine_ptr.is_null()
            || key_name.is_null()
            || result_ptr.is_null()
            || result_len_ptr.is_null()
        {
            return AvssEngineErrorCode::NullPointer;
        }

        let wrapper = unsafe { get_wrapper(engine_ptr) };

        let c_str = unsafe { CStr::from_ptr(key_name) };
        let key_name_str = match c_str.to_str() {
            Ok(s) => s,
            Err(_) => return AvssEngineErrorCode::SerializationError,
        };

        match wrapper.avss_ops.avss_get_commitment(key_name_str, index) {
            Ok(bytes) => {
                unsafe {
                    write_ffi_result_bytes(bytes, result_ptr, result_len_ptr);
                }
                AvssEngineErrorCode::Success
            }
            Err(_) => AvssEngineErrorCode::InvalidCommitmentIndex,
        }
    }

    /// Check if the engine is ready
    ///
    /// # Safety
    /// `engine_ptr` must be null or a live pointer created by `adkg_engine_new`.
    #[no_mangle]
    pub unsafe extern "C" fn adkg_engine_is_ready(engine_ptr: *mut AvssEngineOpaque) -> c_int {
        if engine_ptr.is_null() {
            return 0;
        }
        let wrapper = unsafe { get_wrapper(engine_ptr) };
        if wrapper.engine.is_ready() {
            1
        } else {
            0
        }
    }

    /// Get the party ID
    ///
    /// # Safety
    /// `engine_ptr` must be null or a live pointer created by `adkg_engine_new`.
    #[no_mangle]
    pub unsafe extern "C" fn adkg_engine_party_id(engine_ptr: *mut AvssEngineOpaque) -> usize {
        if engine_ptr.is_null() {
            return 0;
        }
        let wrapper = unsafe { get_wrapper(engine_ptr) };
        wrapper.engine.party().id()
    }

    /// Get the protocol name (returns static string, do not free)
    ///
    /// # Safety
    /// `engine_ptr` must be null or a live pointer created by `adkg_engine_new`.
    #[no_mangle]
    pub unsafe extern "C" fn adkg_engine_protocol_name(
        engine_ptr: *mut AvssEngineOpaque,
    ) -> *const c_char {
        static PROTOCOL_NAME: &[u8] = b"avss\0";
        if engine_ptr.is_null() {
            return std::ptr::null();
        }
        PROTOCOL_NAME.as_ptr() as *const c_char
    }

    /// Free bytes allocated by AVSS engine functions
    ///
    /// # Safety
    /// `ptr` must be null or a pointer returned by an AVSS FFI function with
    /// exactly the same `len`.
    #[no_mangle]
    pub unsafe extern "C" fn adkg_free_bytes(ptr: *mut u8, len: usize) {
        unsafe {
            free_ffi_result_bytes(ptr, len);
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use ark_bls12_381::G1Projective;
        use ark_ec::PrimeGroup;
        use ark_serialize::CanonicalSerialize;
        use std::sync::Arc;
        use stoffelnet::transports::quic::QuicNetworkManager;

        #[test]
        fn test_adkg_engine_new_null_network() {
            let engine = unsafe {
                adkg_engine_new(
                    1,
                    0,
                    5,
                    1,
                    std::ptr::null_mut(),
                    CAvssCurveConfig::Bls12_381 as u32,
                    std::ptr::null(),
                    0,
                    std::ptr::null(),
                    0,
                )
            };
            assert!(engine.is_null());
        }

        #[test]
        fn test_adkg_engine_new_invalid_curve_config_rejected() {
            let n = 4usize;
            let net = Arc::new(QuicNetworkManager::new());
            let mut pk_map_bytes = Vec::new();
            vec![G1Projective::generator(); n]
                .serialize_compressed(&mut pk_map_bytes)
                .expect("serialize pk map");
            let net_ptr = &net as *const Arc<QuicNetworkManager> as *mut c_void;

            let engine = unsafe {
                adkg_engine_new(
                    1,
                    0,
                    n,
                    1,
                    net_ptr,
                    99,
                    std::ptr::null(),
                    0,
                    pk_map_bytes.as_ptr(),
                    pk_map_bytes.len(),
                )
            };
            assert!(engine.is_null(), "invalid curve config must be rejected");
        }

        #[test]
        fn test_adkg_engine_new_null_pk_map_rejected() {
            let net = Arc::new(QuicNetworkManager::new());
            let net_ptr = &net as *const Arc<QuicNetworkManager> as *mut c_void;

            let engine = unsafe {
                adkg_engine_new(
                    1,
                    0,
                    4,
                    1,
                    net_ptr,
                    CAvssCurveConfig::Bls12_381 as u32,
                    std::ptr::null(),
                    0,
                    std::ptr::null(),
                    0,
                )
            };
            assert!(
                engine.is_null(),
                "constructor must reject null/empty public key map"
            );
        }

        #[test]
        fn test_adkg_engine_new_without_tokio_runtime() {
            let n = 4usize;
            let net = Arc::new(QuicNetworkManager::new());
            let mut pk_map_bytes = Vec::new();
            vec![G1Projective::generator(); n]
                .serialize_compressed(&mut pk_map_bytes)
                .expect("serialize pk map");
            let net_ptr = &net as *const Arc<QuicNetworkManager> as *mut c_void;

            let engine = unsafe {
                adkg_engine_new(
                    1,
                    0,
                    n,
                    1,
                    net_ptr,
                    CAvssCurveConfig::Bls12_381 as u32,
                    std::ptr::null(),
                    0,
                    pk_map_bytes.as_ptr(),
                    pk_map_bytes.len(),
                )
            };
            assert!(
                !engine.is_null(),
                "constructor should succeed without an ambient Tokio runtime"
            );
            unsafe { adkg_engine_free(engine) };
        }

        #[test]
        fn test_adkg_engine_free_null() {
            unsafe { adkg_engine_free(std::ptr::null_mut()) };
        }

        #[test]
        fn test_adkg_engine_is_ready_null() {
            assert_eq!(unsafe { adkg_engine_is_ready(std::ptr::null_mut()) }, 0);
        }

        #[test]
        fn test_adkg_engine_party_id_null() {
            assert_eq!(unsafe { adkg_engine_party_id(std::ptr::null_mut()) }, 0);
        }

        #[test]
        fn test_adkg_engine_protocol_name_null() {
            assert!(unsafe { adkg_engine_protocol_name(std::ptr::null_mut()) }.is_null());
        }

        #[test]
        fn test_adkg_free_bytes_null() {
            unsafe {
                adkg_free_bytes(std::ptr::null_mut(), 0);
                adkg_free_bytes(std::ptr::null_mut(), 10);
            }
        }
    }
}