derec-library 0.0.8

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

//! C FFI for the DeRec pairing flow.
//!
//! Protocol semantics live in `library/src/primitives/pairing/`. Items below
//! describe only the FFI surface.
//!
//! # Pairing secret material
//!
//! [`PairingSecretKeyMaterial`] is serialized into an opaque FFI-specific
//! blob. Persist it and feed it back into [`extract_pair_request`] /
//! [`produce_pair_response_message`] (on the contact-initiator side) or
//! [`extract_pair_response`] / [`process_pair_response_message`] (on the
//! contact-responder side).

use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use std::ffi::c_char;

use crate::extensions::transport_protocol::TransportProtocolExt as _;
use crate::interop::dto::ContactMessage as ContactMessageDto;
use crate::interop::ffi::common::{DeRecBuffer, empty_buffer, vec_into_buffer};
use crate::interop::ffi::error::{
    DEREC_CODE_FFI_BAD_PROTO, DEREC_CODE_FFI_BAD_SHARED_KEY, DEREC_CODE_FFI_INVALID_ENUM,
    DEREC_CODE_FFI_NULL_PTR, DeRecError, ffi_error, from_lib_error, success,
};
use derec_cryptography::pairing::PairingSecretKeyMaterial;
use derec_proto::{
    CommunicationInfo, ContactMessage, ContactMode, DeRecMessage, PairRequestMessage,
    PairResponseMessage, PrePairRequestMessage, PrePairResponseMessage, SenderKind,
    TransportProtocol,
};
use prost::Message as _;

#[repr(C)]
pub struct CreateContactMessageResult {
    pub error: DeRecError,
    pub contact_wire_bytes: DeRecBuffer,
    /// Opaque pairing secret key material. See module docs.
    pub secret_key_material: DeRecBuffer,
}

#[repr(C)]
pub struct EncodeContactMessageResult {
    pub error: DeRecError,
    /// Proto-encoded `ContactMessage`, ready to publish out of band.
    pub wire_bytes: DeRecBuffer,
}

#[repr(C)]
pub struct DecodeContactMessageResult {
    pub error: DeRecError,
    /// UTF-8 JSON object. See [`encode_contact_message`] for the shape.
    pub contact_json: DeRecBuffer,
}

#[repr(C)]
pub struct ProducePairRequestMessageResult {
    pub error: DeRecError,
    pub request_wire_bytes: DeRecBuffer,
    pub initiator_contact_message_wire_bytes: DeRecBuffer,
    /// Opaque pairing secret key material. See module docs.
    pub secret_key_material: DeRecBuffer,
}

#[repr(C)]
pub struct ExtractPairRequestResult {
    pub error: DeRecError,
    pub channel_id: u64,
    /// Inner `PairRequestMessage` proto bytes for chaining into
    /// [`produce_pair_response_message`].
    pub request_proto_bytes: DeRecBuffer,
}

#[repr(C)]
pub struct ProducePairResponseMessageResult {
    pub error: DeRecError,
    pub response_wire_bytes: DeRecBuffer,
    pub peer_transports: DeRecBuffer,
    pub shared_key: DeRecBuffer,
    /// Post-handshake rekey channel id the responder is committing to.
    /// Callers MUST atomically rename their local channel record from the
    /// pre-rekey id (the one passed to `produce_pair_response_message`) to
    /// this value as part of accepting the response. Zero on error.
    pub channel_id: u64,
}

#[repr(C)]
pub struct ExtractPairResponseResult {
    pub error: DeRecError,
    pub channel_id: u64,
    /// Inner `PairResponseMessage` proto bytes for chaining into
    /// [`process_pair_response_message`].
    pub response_proto_bytes: DeRecBuffer,
}

/// `shared_key` is populated only on success; empty on peer rejection (see
/// [`crate::interop::ffi::error`]).
#[repr(C)]
pub struct ProcessPairResponseMessageResult {
    pub error: DeRecError,
    pub shared_key: DeRecBuffer,
    /// Post-handshake rekey channel id — already validated against the
    /// caller's own derivation. Callers MUST atomically rename their local
    /// channel record from the pre-rekey id (the one in the contact) to
    /// this value. Zero on error.
    pub channel_id: u64,
}

#[repr(C)]
pub struct ProducePrePairRequestMessageResult {
    pub error: DeRecError,
    /// Serialized outer plaintext `DeRecMessage` envelope carrying a
    /// `PrePairRequestMessage`. Ready to send over transport.
    pub envelope_wire_bytes: DeRecBuffer,
}

#[repr(C)]
pub struct ExtractPrePairRequestResult {
    pub error: DeRecError,
    /// Channel identifier decoded from the outer envelope's routing field.
    pub channel_id: u64,
    /// Inner `PrePairRequestMessage` proto bytes for chaining into
    /// [`produce_pre_pair_response_message`].
    pub request_proto_bytes: DeRecBuffer,
}

#[repr(C)]
pub struct ProducePrePairResponseMessageResult {
    pub error: DeRecError,
    /// Serialized outer plaintext `DeRecMessage` envelope carrying a
    /// `PrePairResponseMessage`. Ready to send over transport.
    pub envelope_wire_bytes: DeRecBuffer,
}

#[repr(C)]
pub struct ExtractPrePairResponseResult {
    pub error: DeRecError,
    /// Channel identifier decoded from the outer envelope's routing field.
    pub channel_id: u64,
    /// Inner `PrePairResponseMessage` proto bytes for chaining into
    /// [`process_pre_pair_response_message`].
    pub response_proto_bytes: DeRecBuffer,
}

#[repr(C)]
pub struct ProducePrePairNoKeysResponseMessageResult {
    pub error: DeRecError,
    /// Serialized outer plaintext `DeRecMessage` envelope carrying a
    /// `PrePairResponseMessage` with freshly generated public keys.
    pub envelope_wire_bytes: DeRecBuffer,
    /// The secret key material generated for this pairing. The caller MUST
    /// persist it: the `PairRequestMessage` that follows is encrypted to it.
    pub secret_key_material: DeRecBuffer,
}

#[repr(C)]
pub struct PairingFingerprintResult {
    pub error: DeRecError,
    /// NUL-terminated UTF-8 fingerprint. Free with
    /// [`crate::interop::ffi::common::derec_free_string`]. Null on failure.
    pub fingerprint: *mut c_char,
}

/// On success the two key buffers hold the validated public keys republished
/// by the contact creator. On failure (status non-Ok, hash mismatch, etc.)
/// both buffers are empty; consult `error`.
#[repr(C)]
pub struct ProcessPrePairResponseMessageResult {
    pub error: DeRecError,
    pub mlkem_encapsulation_key: DeRecBuffer,
    pub ecies_public_key: DeRecBuffer,
    /// Nonce echoed from the original `ContactMessage`. Zero on failure.
    pub nonce: u64,
}

/// Single entry point for all three modes:
/// - `contact_mode == 0` (`INLINE_KEYS`) — keys inlined in contact.
/// - `contact_mode == 1` (`HASHED_KEYS`) — binding hash inlined; keys via PrePair.
/// - `contact_mode == 2` (`NO_KEYS`) — no key material; keys generated on the
///   fly by the responder when the `PrePairRequest` arrives.
///
/// `has_nonce == 0` lets the library generate a fresh random `u64`.
/// `has_nonce == 1` uses the supplied `nonce` value verbatim; required for
/// `NO_KEYS` where callers typically pick a small human-typable value.
///
/// On success `secret_key_material` is populated for `INLINE_KEYS` and
/// `HASHED_KEYS`; it is empty for `NO_KEYS` (no keys exist at
/// contact-creation time).
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn create_contact_message(
    channel_id: u64,
    contact_mode: i32,
    transport_protocols_ptr: *const u8,
    transport_protocols_len: usize,
    has_nonce: u32,
    nonce: u64,
) -> CreateContactMessageResult {
    let with_err = |error| CreateContactMessageResult {
        error,
        contact_wire_bytes: empty_buffer(),
        secret_key_material: empty_buffer(),
    };

    let contact_mode = match ContactMode::try_from(contact_mode) {
        Ok(m) => m,
        Err(_) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_INVALID_ENUM,
                format!("invalid ContactMode value: {contact_mode}"),
            ));
        }
    };

    let own = match decode_transport_protocol_list(transport_protocols_ptr, transport_protocols_len)
    {
        Ok(t) => t,
        Err(e) => return with_err(e),
    };

    let nonce = if has_nonce != 0 { Some(nonce) } else { None };

    match crate::primitives::pairing::request::create_contact(
        channel_id.into(),
        contact_mode,
        own,
        nonce,
    ) {
        Ok(r) => CreateContactMessageResult {
            error: success(),
            contact_wire_bytes: vec_into_buffer(r.contact_message.encode_to_vec()),
            secret_key_material: match r.secret_key {
                Some(k) => vec_into_buffer(serialize_pairing_secret_key_material(&k)),
                None => empty_buffer(),
            },
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// Encodes a JSON [`ContactMessageDto`] to `ContactMessage` proto wire bytes.
/// See [`crate::primitives::pairing::request::encode_contact`].
///
/// The JSON shape is [`ContactMessageDto`]'s serde representation with one
/// adjustment applied at this seam: `channel_id` and `nonce` are decimal
/// strings, matching the `u64`-as-decimal-string convention every other FFI
/// JSON payload uses (see [`crate::interop::ffi::protocol::flow`]) because a host
/// whose numbers are IEEE-754 doubles cannot round-trip a full-width `u64`.
/// A plain JSON number is also accepted for either field.
///
/// # Safety
///
/// `contact_json_ptr` must point to a readable range of `contact_json_len`
/// bytes (or be null with `len == 0`).
#[unsafe(no_mangle)]
pub extern "C" fn encode_contact_message(
    contact_json_ptr: *const u8,
    contact_json_len: usize,
) -> EncodeContactMessageResult {
    let with_err = |error| EncodeContactMessageResult {
        error,
        wire_bytes: empty_buffer(),
    };

    let json_bytes = match parse_buffer(contact_json_ptr, contact_json_len, "contact_json_ptr") {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let mut json: serde_json::Value = match serde_json::from_slice(json_bytes) {
        Ok(v) => v,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("contact_json is not valid JSON: {e}"),
            ));
        }
    };
    if let Err(e) = u64_id_fields_to_numbers(&mut json) {
        return with_err(ffi_error(DEREC_CODE_FFI_BAD_PROTO, e));
    }
    let dto: ContactMessageDto = match serde_json::from_value(json) {
        Ok(d) => d,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("contact_json is not a valid ContactMessage: {e}"),
            ));
        }
    };

    let contact_message: ContactMessage = dto.into();
    match crate::primitives::pairing::request::encode_contact(&contact_message) {
        Ok(bytes) => EncodeContactMessageResult {
            error: success(),
            wire_bytes: vec_into_buffer(bytes),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// Decodes proto-encoded `ContactMessage` wire bytes into the JSON
/// [`ContactMessageDto`] shape described on [`encode_contact_message`].
/// See [`crate::primitives::pairing::request::decode_contact`].
///
/// # Safety
///
/// `contact_wire_ptr` must point to a readable range of `contact_wire_len`
/// bytes (or be null with `len == 0`).
#[unsafe(no_mangle)]
pub extern "C" fn decode_contact_message(
    contact_wire_ptr: *const u8,
    contact_wire_len: usize,
) -> DecodeContactMessageResult {
    let with_err = |error| DecodeContactMessageResult {
        error,
        contact_json: empty_buffer(),
    };

    let wire_bytes = match parse_buffer(contact_wire_ptr, contact_wire_len, "contact_wire_ptr") {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let contact_message = match crate::primitives::pairing::request::decode_contact(wire_bytes) {
        Ok(c) => c,
        Err(e) => return with_err(from_lib_error(e)),
    };

    let dto: ContactMessageDto = contact_message.into();
    let mut json = match serde_json::to_value(&dto) {
        Ok(v) => v,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to encode ContactMessage as JSON: {e}"),
            ));
        }
    };
    u64_id_fields_to_strings(&mut json);
    match serde_json::to_vec(&json) {
        Ok(bytes) => DecodeContactMessageResult {
            error: success(),
            contact_json: vec_into_buffer(bytes),
        },
        Err(e) => with_err(ffi_error(
            DEREC_CODE_FFI_BAD_PROTO,
            format!("failed to serialize ContactMessage JSON: {e}"),
        )),
    }
}

/// The `ContactMessage` fields that cross this seam as decimal strings.
const CONTACT_U64_ID_FIELDS: [&str; 2] = ["channel_id", "nonce"];

/// `communication_info_ptr` may be null / zero-length to indicate no
/// communication info; otherwise it must be serialized [`CommunicationInfo`]
/// proto bytes. `parameter_range_ptr` follows the same convention and
/// carries serialized [`derec_proto::ParameterRange`] bytes.
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub extern "C" fn produce_pair_request_message(
    sender_kind: i32,
    transport_protocols_ptr: *const u8,
    transport_protocols_len: usize,
    contact_message_ptr: *const u8,
    contact_message_len: usize,
    communication_info_ptr: *const u8,
    communication_info_len: usize,
    parameter_range_ptr: *const u8,
    parameter_range_len: usize,
) -> ProducePairRequestMessageResult {
    let with_err = |error| ProducePairRequestMessageResult {
        error,
        request_wire_bytes: empty_buffer(),
        initiator_contact_message_wire_bytes: empty_buffer(),
        secret_key_material: empty_buffer(),
    };

    let sender_kind = match SenderKind::try_from(sender_kind) {
        Ok(v) => v,
        Err(_) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_INVALID_ENUM,
                format!("invalid SenderKind value: {sender_kind}"),
            ));
        }
    };
    let own = match decode_transport_protocol_list(transport_protocols_ptr, transport_protocols_len)
    {
        Ok(t) => t,
        Err(e) => return with_err(e),
    };
    let contact_message_bytes = match parse_buffer(
        contact_message_ptr,
        contact_message_len,
        "contact_message_ptr",
    ) {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let contact_message = match ContactMessage::decode(contact_message_bytes) {
        Ok(c) => c,
        Err(_) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                "contact_message_bytes is not a valid ContactMessage",
            ));
        }
    };
    let communication_info =
        match decode_optional_communication_info(communication_info_ptr, communication_info_len) {
            Ok(c) => c,
            Err(e) => return with_err(e),
        };
    let parameter_range =
        match decode_optional_parameter_range(parameter_range_ptr, parameter_range_len) {
            Ok(p) => p,
            Err(e) => return with_err(e),
        };

    match crate::primitives::pairing::request::produce(
        sender_kind,
        own,
        &contact_message,
        communication_info,
        parameter_range,
    ) {
        Ok(r) => ProducePairRequestMessageResult {
            error: success(),
            request_wire_bytes: vec_into_buffer(r.envelope),
            initiator_contact_message_wire_bytes: vec_into_buffer(
                r.initiator_contact_message.encode_to_vec(),
            ),
            secret_key_material: vec_into_buffer(serialize_pairing_secret_key_material(
                &r.secret_key,
            )),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// `parameter_range_ptr` may be null / zero-length to declare no parameter
/// range; otherwise it must be serialized [`derec_proto::ParameterRange`]
/// proto bytes. See [`crate::primitives::pairing::request::extract`].
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn extract_pair_request(
    request_ptr: *const u8,
    request_len: usize,
    secret_key_material_ptr: *const u8,
    secret_key_material_len: usize,
    parameter_range_ptr: *const u8,
    parameter_range_len: usize,
) -> ExtractPairRequestResult {
    let with_err = |error| ExtractPairRequestResult {
        error,
        channel_id: 0,
        request_proto_bytes: empty_buffer(),
    };

    let request_bytes = match parse_buffer(request_ptr, request_len, "request_ptr") {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let pairing_secret_key_material =
        match decode_secret_key_material(secret_key_material_ptr, secret_key_material_len) {
            Ok(m) => m,
            Err(e) => return with_err(e),
        };

    let parameter_range =
        match decode_optional_parameter_range(parameter_range_ptr, parameter_range_len) {
            Ok(p) => p,
            Err(e) => return with_err(e),
        };

    let channel_id = match DeRecMessage::decode(request_bytes) {
        Ok(e) => e.channel_id,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode envelope: {e}"),
            ));
        }
    };

    match crate::primitives::pairing::request::extract(
        request_bytes,
        pairing_secret_key_material.ecies_secret_key(),
        parameter_range.as_ref(),
    ) {
        Ok(r) => ExtractPairRequestResult {
            error: success(),
            channel_id,
            request_proto_bytes: vec_into_buffer(r.request.encode_to_vec()),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// `request_proto_ptr` / `request_proto_len` must be the `request_proto_bytes`
/// returned by [`extract_pair_request`]. `communication_info_ptr` may be null /
/// zero-length to indicate no communication info.
///
/// `parameter_range_ptr` may be null / zero-length to indicate no
/// parameter range; otherwise it must be serialized
/// [`derec_proto::ParameterRange`] proto bytes.
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub extern "C" fn produce_pair_response_message(
    channel_id: u64,
    request_proto_ptr: *const u8,
    request_proto_len: usize,
    secret_key_material_ptr: *const u8,
    secret_key_material_len: usize,
    communication_info_ptr: *const u8,
    communication_info_len: usize,
    parameter_range_ptr: *const u8,
    parameter_range_len: usize,
    unsafe_connection: u32,
) -> ProducePairResponseMessageResult {
    let with_err = |error| ProducePairResponseMessageResult {
        error,
        response_wire_bytes: empty_buffer(),
        peer_transports: empty_buffer(),
        shared_key: empty_buffer(),
        channel_id: 0,
    };

    let request_bytes =
        match parse_buffer(request_proto_ptr, request_proto_len, "request_proto_ptr") {
            Ok(b) => b,
            Err(e) => return with_err(e),
        };
    let request = match PairRequestMessage::decode(request_bytes) {
        Ok(r) => r,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode request: {e}"),
            ));
        }
    };
    let pairing_secret_key_material =
        match decode_secret_key_material(secret_key_material_ptr, secret_key_material_len) {
            Ok(m) => m,
            Err(e) => return with_err(e),
        };
    let communication_info =
        match decode_optional_communication_info(communication_info_ptr, communication_info_len) {
            Ok(c) => c,
            Err(e) => return with_err(e),
        };
    let parameter_range =
        match decode_optional_parameter_range(parameter_range_ptr, parameter_range_len) {
            Ok(p) => p,
            Err(e) => return with_err(e),
        };

    match crate::primitives::pairing::response::produce(
        crate::types::ChannelId(channel_id),
        &request,
        &pairing_secret_key_material,
        communication_info,
        parameter_range,
        crate::transport::TransportPolicy::new(unsafe_connection != 0),
    ) {
        Ok(r) => ProducePairResponseMessageResult {
            error: success(),
            response_wire_bytes: vec_into_buffer(r.envelope),
            peer_transports: vec_into_buffer(encode_transport_list(&r.peer_transports)),
            shared_key: vec_into_buffer(r.shared_key.to_vec()),
            channel_id: r.channel_id.into(),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn extract_pair_response(
    response_ptr: *const u8,
    response_len: usize,
    secret_key_material_ptr: *const u8,
    secret_key_material_len: usize,
) -> ExtractPairResponseResult {
    let with_err = |error| ExtractPairResponseResult {
        error,
        channel_id: 0,
        response_proto_bytes: empty_buffer(),
    };

    let response_bytes = match parse_buffer(response_ptr, response_len, "response_ptr") {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let pairing_secret_key_material =
        match decode_secret_key_material(secret_key_material_ptr, secret_key_material_len) {
            Ok(m) => m,
            Err(e) => return with_err(e),
        };

    let channel_id = match DeRecMessage::decode(response_bytes) {
        Ok(e) => e.channel_id,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode envelope: {e}"),
            ));
        }
    };

    match crate::primitives::pairing::response::extract(
        response_bytes,
        pairing_secret_key_material.ecies_secret_key(),
    ) {
        Ok(r) => ExtractPairResponseResult {
            error: success(),
            channel_id,
            response_proto_bytes: vec_into_buffer(r.response.encode_to_vec()),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// `response_proto_ptr` / `response_proto_len` must be the
/// `response_proto_bytes` returned by [`extract_pair_response`].
///
/// `parameter_range_ptr` may be null / zero-length to declare no parameter
/// range; otherwise it must be serialized [`derec_proto::ParameterRange`]
/// proto bytes. See [`crate::primitives::pairing::response::process`].
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[allow(clippy::too_many_arguments)]
#[unsafe(no_mangle)]
pub extern "C" fn process_pair_response_message(
    contact_message_ptr: *const u8,
    contact_message_len: usize,
    response_proto_ptr: *const u8,
    response_proto_len: usize,
    secret_key_material_ptr: *const u8,
    secret_key_material_len: usize,
    parameter_range_ptr: *const u8,
    parameter_range_len: usize,
) -> ProcessPairResponseMessageResult {
    let with_err = |error| ProcessPairResponseMessageResult {
        error,
        shared_key: empty_buffer(),
        channel_id: 0,
    };

    let contact_message_bytes = match parse_buffer(
        contact_message_ptr,
        contact_message_len,
        "contact_message_ptr",
    ) {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let contact_message = match ContactMessage::decode(contact_message_bytes) {
        Ok(c) => c,
        Err(_) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                "contact_message_bytes is not a valid ContactMessage",
            ));
        }
    };
    let response_bytes =
        match parse_buffer(response_proto_ptr, response_proto_len, "response_proto_ptr") {
            Ok(b) => b,
            Err(e) => return with_err(e),
        };
    let response = match PairResponseMessage::decode(response_bytes) {
        Ok(r) => r,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode response: {e}"),
            ));
        }
    };
    let pairing_secret_key_material =
        match decode_secret_key_material(secret_key_material_ptr, secret_key_material_len) {
            Ok(m) => m,
            Err(e) => return with_err(e),
        };

    let parameter_range =
        match decode_optional_parameter_range(parameter_range_ptr, parameter_range_len) {
            Ok(p) => p,
            Err(e) => return with_err(e),
        };

    match crate::primitives::pairing::response::process(
        &contact_message,
        &response,
        &pairing_secret_key_material,
        parameter_range.as_ref(),
    ) {
        Ok(r) => ProcessPairResponseMessageResult {
            error: success(),
            shared_key: vec_into_buffer(r.shared_key.to_vec()),
            channel_id: r.channel_id.into(),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// Builds a plaintext `PrePairRequestMessage` envelope. Used by the scanner
/// when the contact was sent with `contact_mode == HASHED_KEYS`. The envelope
/// is unencrypted — no shared key exists yet — so the caller does not pass
/// secret key material here.
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn produce_pre_pair_request_message(
    transport_protocols_ptr: *const u8,
    transport_protocols_len: usize,
    contact_message_ptr: *const u8,
    contact_message_len: usize,
) -> ProducePrePairRequestMessageResult {
    let with_err = |error| ProducePrePairRequestMessageResult {
        error,
        envelope_wire_bytes: empty_buffer(),
    };

    let transport_protocols =
        match decode_transport_protocol_list(transport_protocols_ptr, transport_protocols_len) {
            Ok(t) => t,
            Err(e) => return with_err(e),
        };
    let contact_message_bytes = match parse_buffer(
        contact_message_ptr,
        contact_message_len,
        "contact_message_ptr",
    ) {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let contact_message = match ContactMessage::decode(contact_message_bytes) {
        Ok(c) => c,
        Err(_) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                "contact_message_bytes is not a valid ContactMessage",
            ));
        }
    };

    match crate::primitives::pairing::request::produce_pre_pair_request(
        transport_protocols,
        &contact_message,
    ) {
        Ok(r) => ProducePrePairRequestMessageResult {
            error: success(),
            envelope_wire_bytes: vec_into_buffer(r.envelope),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// Decodes a plaintext `PrePairRequestMessage` envelope.
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn extract_pre_pair_request(
    envelope_ptr: *const u8,
    envelope_len: usize,
) -> ExtractPrePairRequestResult {
    let with_err = |error| ExtractPrePairRequestResult {
        error,
        channel_id: 0,
        request_proto_bytes: empty_buffer(),
    };

    let envelope_bytes = match parse_buffer(envelope_ptr, envelope_len, "envelope_ptr") {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };

    let channel_id = match DeRecMessage::decode(envelope_bytes) {
        Ok(e) => e.channel_id,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode envelope: {e}"),
            ));
        }
    };

    match crate::primitives::pairing::request::extract_pre_pair(envelope_bytes) {
        Ok(r) => ExtractPrePairRequestResult {
            error: success(),
            channel_id,
            request_proto_bytes: vec_into_buffer(r.request.encode_to_vec()),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// Builds a plaintext `PrePairResponseMessage` envelope republishing the
/// initiator's public keys. The keys come from `secret_key_material` (which
/// retains them alongside the secrets in `HASHED_KEYS` flows).
///
/// `request_proto_ptr` / `request_proto_len` must be the `request_proto_bytes`
/// returned by [`extract_pre_pair_request`].
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn produce_pre_pair_response_message(
    channel_id: u64,
    request_proto_ptr: *const u8,
    request_proto_len: usize,
    secret_key_material_ptr: *const u8,
    secret_key_material_len: usize,
) -> ProducePrePairResponseMessageResult {
    let with_err = |error| ProducePrePairResponseMessageResult {
        error,
        envelope_wire_bytes: empty_buffer(),
    };

    let request_bytes =
        match parse_buffer(request_proto_ptr, request_proto_len, "request_proto_ptr") {
            Ok(b) => b,
            Err(e) => return with_err(e),
        };
    let request = match PrePairRequestMessage::decode(request_bytes) {
        Ok(r) => r,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode PrePairRequestMessage: {e}"),
            ));
        }
    };
    let pairing_secret_key_material =
        match decode_secret_key_material(secret_key_material_ptr, secret_key_material_len) {
            Ok(m) => m,
            Err(e) => return with_err(e),
        };

    match crate::primitives::pairing::response::produce_pre_pair(
        crate::types::ChannelId(channel_id),
        &request,
        &pairing_secret_key_material,
    ) {
        Ok(r) => ProducePrePairResponseMessageResult {
            error: success(),
            envelope_wire_bytes: vec_into_buffer(r.envelope),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// Decodes a plaintext `PrePairResponseMessage` envelope.
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn extract_pre_pair_response(
    envelope_ptr: *const u8,
    envelope_len: usize,
) -> ExtractPrePairResponseResult {
    let with_err = |error| ExtractPrePairResponseResult {
        error,
        channel_id: 0,
        response_proto_bytes: empty_buffer(),
    };

    let envelope_bytes = match parse_buffer(envelope_ptr, envelope_len, "envelope_ptr") {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };

    let channel_id = match DeRecMessage::decode(envelope_bytes) {
        Ok(e) => e.channel_id,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode envelope: {e}"),
            ));
        }
    };

    match crate::primitives::pairing::response::extract_pre_pair(envelope_bytes) {
        Ok(r) => ExtractPrePairResponseResult {
            error: success(),
            channel_id,
            response_proto_bytes: vec_into_buffer(r.response.encode_to_vec()),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// Contact-creator side of a `NO_KEYS` pairing: generates key material and
/// answers the `PrePairRequestMessage` with its public half.
///
/// The caller MUST first match the request's `nonce` against the contact it
/// issued — the only thing that authenticates a `NO_KEYS` request — and MUST
/// keep the resulting channel unusable until both sides confirm
/// [`pairing_fingerprint`] out of band.
///
/// `request_proto_ptr` / `request_proto_len` must be the `request_proto_bytes`
/// returned by [`extract_pre_pair_request`].
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn produce_pre_pair_no_keys_response_message(
    channel_id: u64,
    request_proto_ptr: *const u8,
    request_proto_len: usize,
) -> ProducePrePairNoKeysResponseMessageResult {
    let with_err = |error| ProducePrePairNoKeysResponseMessageResult {
        error,
        envelope_wire_bytes: empty_buffer(),
        secret_key_material: empty_buffer(),
    };

    let request_bytes =
        match parse_buffer(request_proto_ptr, request_proto_len, "request_proto_ptr") {
            Ok(b) => b,
            Err(e) => return with_err(e),
        };
    let request = match PrePairRequestMessage::decode(request_bytes) {
        Ok(r) => r,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode PrePairRequestMessage: {e}"),
            ));
        }
    };

    match crate::primitives::pairing::response::produce_pre_pair_no_keys(
        crate::types::ChannelId(channel_id),
        &request,
    ) {
        Ok(r) => ProducePrePairNoKeysResponseMessageResult {
            error: success(),
            envelope_wire_bytes: vec_into_buffer(r.envelope),
            secret_key_material: vec_into_buffer(serialize_pairing_secret_key_material(
                &r.pairing_secret_key_material,
            )),
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// Scanner side of a `NO_KEYS` pairing: accepts the contact creator's public
/// keys. There is no binding hash to check them against, so the channel this
/// leads to MUST stay unusable until both sides confirm
/// [`pairing_fingerprint`] out of band.
///
/// `response_proto_ptr` / `response_proto_len` must be the
/// `response_proto_bytes` returned by [`extract_pre_pair_response`].
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn process_pre_pair_no_keys_response_message(
    contact_message_ptr: *const u8,
    contact_message_len: usize,
    response_proto_ptr: *const u8,
    response_proto_len: usize,
) -> ProcessPrePairResponseMessageResult {
    let with_err = |error| ProcessPrePairResponseMessageResult {
        error,
        mlkem_encapsulation_key: empty_buffer(),
        ecies_public_key: empty_buffer(),
        nonce: 0,
    };

    let contact_message_bytes = match parse_buffer(
        contact_message_ptr,
        contact_message_len,
        "contact_message_ptr",
    ) {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let contact_message = match ContactMessage::decode(contact_message_bytes) {
        Ok(c) => c,
        Err(_) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                "contact_message_bytes is not a valid ContactMessage",
            ));
        }
    };
    let response_bytes =
        match parse_buffer(response_proto_ptr, response_proto_len, "response_proto_ptr") {
            Ok(b) => b,
            Err(e) => return with_err(e),
        };
    let response = match PrePairResponseMessage::decode(response_bytes) {
        Ok(r) => r,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode PrePairResponseMessage: {e}"),
            ));
        }
    };

    match crate::primitives::pairing::response::process_pre_pair_no_keys(
        &contact_message,
        &response,
    ) {
        Ok(r) => ProcessPrePairResponseMessageResult {
            error: success(),
            mlkem_encapsulation_key: vec_into_buffer(r.mlkem_encapsulation_key),
            ecies_public_key: vec_into_buffer(r.ecies_public_key),
            nonce: r.nonce,
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// The human-readable fingerprint of a pairing's shared key. See
/// [`crate::primitives::pairing::fingerprint`].
///
/// # Safety
///
/// `shared_key_ptr` must point to `shared_key_len` readable bytes.
#[unsafe(no_mangle)]
pub extern "C" fn pairing_fingerprint(
    shared_key_ptr: *const u8,
    shared_key_len: usize,
) -> PairingFingerprintResult {
    let with_err = |error| PairingFingerprintResult {
        error,
        fingerprint: std::ptr::null_mut(),
    };
    let shared_key = match parse_shared_key(shared_key_ptr, shared_key_len) {
        Ok(k) => k,
        Err(e) => return with_err(e),
    };
    match std::ffi::CString::new(crate::primitives::pairing::fingerprint(&shared_key)) {
        Ok(c) => PairingFingerprintResult {
            error: success(),
            fingerprint: c.into_raw(),
        },
        Err(_) => with_err(ffi_error(
            DEREC_CODE_FFI_BAD_PROTO,
            "fingerprint contains NUL byte",
        )),
    }
}

/// Scanner-side: validates a decoded `PrePairResponseMessage` against the
/// original `ContactMessage`'s SHA-384 binding hash. On success returns the
/// validated public keys and echoed nonce. On any failure (non-Ok status,
/// hash mismatch, nonce mismatch, missing fields) returns an error and
/// empty buffers.
///
/// `response_proto_ptr` / `response_proto_len` must be the
/// `response_proto_bytes` returned by [`extract_pre_pair_response`].
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[unsafe(no_mangle)]
pub extern "C" fn process_pre_pair_response_message(
    contact_message_ptr: *const u8,
    contact_message_len: usize,
    response_proto_ptr: *const u8,
    response_proto_len: usize,
) -> ProcessPrePairResponseMessageResult {
    let with_err = |error| ProcessPrePairResponseMessageResult {
        error,
        mlkem_encapsulation_key: empty_buffer(),
        ecies_public_key: empty_buffer(),
        nonce: 0,
    };

    let contact_message_bytes = match parse_buffer(
        contact_message_ptr,
        contact_message_len,
        "contact_message_ptr",
    ) {
        Ok(b) => b,
        Err(e) => return with_err(e),
    };
    let contact_message = match ContactMessage::decode(contact_message_bytes) {
        Ok(c) => c,
        Err(_) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                "contact_message_bytes is not a valid ContactMessage",
            ));
        }
    };
    let response_bytes =
        match parse_buffer(response_proto_ptr, response_proto_len, "response_proto_ptr") {
            Ok(b) => b,
            Err(e) => return with_err(e),
        };
    let response = match PrePairResponseMessage::decode(response_bytes) {
        Ok(r) => r,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("failed to decode PrePairResponseMessage: {e}"),
            ));
        }
    };

    match crate::primitives::pairing::response::process_pre_pair(&contact_message, &response) {
        Ok(r) => ProcessPrePairResponseMessageResult {
            error: success(),
            mlkem_encapsulation_key: vec_into_buffer(r.mlkem_encapsulation_key),
            ecies_public_key: vec_into_buffer(r.ecies_public_key),
            nonce: r.nonce,
        },
        Err(e) => with_err(from_lib_error(e)),
    }
}

/// Rewrites [`CONTACT_U64_ID_FIELDS`] from JSON numbers to decimal strings.
fn u64_id_fields_to_strings(value: &mut serde_json::Value) {
    let Some(object) = value.as_object_mut() else {
        return;
    };
    for field in CONTACT_U64_ID_FIELDS {
        if let Some(n) = object.get(field).and_then(serde_json::Value::as_u64) {
            object.insert(field.to_owned(), serde_json::Value::String(n.to_string()));
        }
    }
}

/// Reverse of [`u64_id_fields_to_strings`]. A field already holding a JSON
/// number is left untouched.
fn u64_id_fields_to_numbers(value: &mut serde_json::Value) -> Result<(), String> {
    let Some(object) = value.as_object_mut() else {
        return Ok(());
    };
    for field in CONTACT_U64_ID_FIELDS {
        let Some(serde_json::Value::String(raw)) = object.get(field) else {
            continue;
        };
        let parsed: u64 = raw
            .parse()
            .map_err(|e| format!("{field} must be a decimal u64 string, got {raw:?}: {e}"))?;
        object.insert(field.to_owned(), serde_json::Value::Number(parsed.into()));
    }
    Ok(())
}

fn parse_buffer<'a>(ptr: *const u8, len: usize, name: &str) -> Result<&'a [u8], DeRecError> {
    if ptr.is_null() && len > 0 {
        return Err(ffi_error(
            DEREC_CODE_FFI_NULL_PTR,
            format!("{name} is null"),
        ));
    }
    if len == 0 {
        Ok(&[])
    } else {
        Ok(unsafe { std::slice::from_raw_parts(ptr, len) })
    }
}

/// Decode a length-delimited sequence of `TransportProtocol` messages.
///
/// Each entry is a protobuf varint byte length followed by that many bytes
/// of an encoded `TransportProtocol` — the same framing protobuf itself
/// uses for a repeated embedded message field, so every binding can build
/// it with the varint writer its protobuf runtime already exposes.
///
/// The list is the caller's served endpoints in its own preference order,
/// and that order is preserved exactly. Every entry is validated at this
/// seam, as the single-endpoint decoder does.
/// Frame a list of endpoints the way `decode_transport_protocol_list` reads
/// one: each entry preceded by its varint byte length.
fn encode_transport_list(endpoints: &[TransportProtocol]) -> Vec<u8> {
    let mut out = Vec::new();
    for endpoint in endpoints {
        let entry = endpoint.encode_to_vec();
        prost::encoding::encode_varint(entry.len() as u64, &mut out);
        out.extend_from_slice(&entry);
    }
    out
}

fn decode_transport_protocol_list(
    ptr: *const u8,
    len: usize,
) -> Result<Vec<TransportProtocol>, DeRecError> {
    let mut bytes = parse_buffer(ptr, len, "transport_protocols_ptr")?;
    let mut out = Vec::new();

    while !bytes.is_empty() {
        let entry_len = prost::encoding::decode_varint(&mut bytes).map_err(|_| {
            ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                "transport_protocols_bytes has a malformed length prefix",
            )
        })? as usize;

        if entry_len > bytes.len() {
            return Err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                "transport_protocols_bytes length prefix overruns the buffer",
            ));
        }

        let (entry, rest) = bytes.split_at(entry_len);
        bytes = rest;

        let tp = TransportProtocol::decode(entry).map_err(|_| {
            ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                "transport_protocols_bytes contains an invalid TransportProtocol",
            )
        })?;
        tp.validate()
            .map_err(|e| from_lib_error(crate::Error::Transport(e)))?;
        out.push(tp);
    }

    if out.is_empty() {
        return Err(ffi_error(
            DEREC_CODE_FFI_BAD_PROTO,
            "transport_protocols_bytes must carry at least one TransportProtocol",
        ));
    }

    Ok(out)
}

fn decode_optional_communication_info(
    ptr: *const u8,
    len: usize,
) -> Result<Option<CommunicationInfo>, DeRecError> {
    if ptr.is_null() || len == 0 {
        return Ok(None);
    }
    let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
    CommunicationInfo::decode(bytes).map(Some).map_err(|_| {
        ffi_error(
            DEREC_CODE_FFI_BAD_PROTO,
            "communication_info_bytes is not a valid CommunicationInfo",
        )
    })
}

fn decode_optional_parameter_range(
    ptr: *const u8,
    len: usize,
) -> Result<Option<derec_proto::ParameterRange>, DeRecError> {
    if ptr.is_null() || len == 0 {
        return Ok(None);
    }
    let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
    derec_proto::ParameterRange::decode(bytes)
        .map(Some)
        .map_err(|_| {
            ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                "parameter_range_bytes is not a valid ParameterRange",
            )
        })
}

fn parse_shared_key(ptr: *const u8, len: usize) -> Result<[u8; 32], DeRecError> {
    let bytes = parse_buffer(ptr, len, "shared_key_ptr")?;
    bytes.try_into().map_err(|_| {
        ffi_error(
            DEREC_CODE_FFI_BAD_SHARED_KEY,
            "shared_key must be exactly 32 bytes",
        )
    })
}

fn decode_secret_key_material(
    ptr: *const u8,
    len: usize,
) -> Result<PairingSecretKeyMaterial, DeRecError> {
    let bytes = parse_buffer(ptr, len, "secret_key_material_ptr")?;
    PairingSecretKeyMaterial::deserialize_uncompressed(&mut &bytes[..]).map_err(|e| {
        ffi_error(
            DEREC_CODE_FFI_BAD_SHARED_KEY,
            format!("invalid secret key material: {e}"),
        )
    })
}

fn serialize_pairing_secret_key_material(sk: &PairingSecretKeyMaterial) -> Vec<u8> {
    let mut out = Vec::new();
    sk.serialize_uncompressed(&mut out)
        .expect("PairingSecretKeyMaterial serialization is infallible");
    out
}

#[cfg(test)]
mod contact_message_json_tests {
    use super::*;
    use crate::interop::ffi::common::derec_free_buffer;
    use crate::interop::ffi::error::{DEREC_CATEGORY_OK, derec_free_error};

    /// Copies a returned buffer out and releases it, matching the ABI
    /// contract foreign callers follow.
    fn take_buffer(buffer: DeRecBuffer) -> Vec<u8> {
        if buffer.ptr.is_null() {
            return Vec::new();
        }
        let bytes = unsafe { std::slice::from_raw_parts(buffer.ptr, buffer.len) }.to_vec();
        derec_free_buffer(buffer.ptr, buffer.len);
        bytes
    }

    fn release(mut error: DeRecError) -> i32 {
        let code = error.code;
        unsafe { derec_free_error(&mut error) };
        code
    }

    fn encode(json: &str) -> EncodeContactMessageResult {
        encode_contact_message(json.as_ptr(), json.len())
    }

    fn decode(wire: &[u8]) -> DecodeContactMessageResult {
        decode_contact_message(wire.as_ptr(), wire.len())
    }

    /// `channel_id` and `nonce` are above 2^53 deliberately: a host whose
    /// numbers are doubles must still see the exact value, which is why
    /// they cross as decimal strings.
    const VALID_INLINE_KEYS_JSON: &str = r#"{
        "channel_id": "18446744073709551615",
        "supported_transports": [{ "uri": "https://owner.example.com", "protocol": 0 }],
        "nonce": "9007199254740993",
        "contact_mode": 0,
        "mlkem_encapsulation_key": [1, 2, 3],
        "ecies_public_key": [4, 5, 6],
        "timestamp": { "seconds": 1700000000, "nanos": 42 }
    }"#;

    #[test]
    fn json_survives_encode_decode_round_trip() {
        let encoded = encode(VALID_INLINE_KEYS_JSON);
        assert_eq!(release(encoded.error), 0);
        let wire = take_buffer(encoded.wire_bytes);
        assert!(!wire.is_empty());

        let decoded = decode(&wire);
        assert_eq!(release(decoded.error), 0);
        let json_bytes = take_buffer(decoded.contact_json);
        let value: serde_json::Value = serde_json::from_slice(&json_bytes).unwrap();

        assert_eq!(value["channel_id"], "18446744073709551615");
        assert_eq!(value["nonce"], "9007199254740993");
        assert_eq!(value["contact_mode"], 0);
        assert_eq!(
            value["supported_transports"][0]["uri"],
            "https://owner.example.com"
        );
        assert_eq!(value["supported_transports"][0]["protocol"], 0);
        assert_eq!(
            value["mlkem_encapsulation_key"],
            serde_json::json!([1, 2, 3])
        );
        assert_eq!(value["ecies_public_key"], serde_json::json!([4, 5, 6]));
        assert!(value.get("contact_binding_hash").is_none());
        assert_eq!(value["timestamp"]["seconds"], 1700000000);
        assert_eq!(value["timestamp"]["nanos"], 42);

        // Re-encoding the decoded JSON reproduces the same wire bytes.
        let json_text = String::from_utf8(json_bytes).unwrap();
        let re_encoded = encode(&json_text);
        assert_eq!(release(re_encoded.error), 0);
        assert_eq!(take_buffer(re_encoded.wire_bytes), wire);
    }

    /// An `INLINE_KEYS` contact that also carries a binding hash violates
    /// the mode/field invariant. Both directions must reject it — encode so
    /// a locally-built contact is never published, decode so application
    /// code can trust what it is handed.
    #[test]
    fn invalid_contact_is_rejected_in_both_directions() {
        let invalid_json = r#"{
            "channel_id": "7",
            "supported_transports": [{ "uri": "https://owner.example.com", "protocol": 0 }],
            "nonce": "9",
            "contact_mode": 0,
            "mlkem_encapsulation_key": [1, 2, 3],
            "ecies_public_key": [4, 5, 6],
            "contact_binding_hash": [7, 7, 7],
            "timestamp": { "seconds": 1700000000, "nanos": 0 }
        }"#;

        let encoded = encode(invalid_json);
        assert_eq!(
            release(encoded.error),
            crate::interop::ffi::error::DEREC_CODE_INVALID_CONTACT_MESSAGE
        );
        assert_eq!(take_buffer(encoded.wire_bytes), Vec::<u8>::new());

        // The same invalid value built as proto bytes without going through
        // the encoder, so the decoder's own gate is what is under test.
        let invalid_wire = ContactMessage {
            channel_id: 7,
            nonce: 9,
            contact_mode: ContactMode::InlineKeys as i32,
            mlkem_encapsulation_key: Some(vec![1, 2, 3]),
            ecies_public_key: Some(vec![4, 5, 6]),
            contact_binding_hash: Some(vec![7, 7, 7]),
            timestamp: None,
            supported_transports: vec![TransportProtocol {
                uri: "https://owner.example.com".to_owned(),
                protocol: 0,
            }],
        }
        .encode_to_vec();

        let decoded = decode(&invalid_wire);
        assert_eq!(
            release(decoded.error),
            crate::interop::ffi::error::DEREC_CODE_INVALID_CONTACT_MESSAGE
        );
        assert_eq!(take_buffer(decoded.contact_json), Vec::<u8>::new());
    }

    /// A contact produced by the library itself decodes without any
    /// hand-written JSON in the loop.
    /// Frame a list of endpoints the way `decode_transport_protocol_list`
    /// expects: each entry preceded by its varint byte length.
    fn encode_transport_list(entries: &[TransportProtocol]) -> Vec<u8> {
        let mut out = Vec::new();
        for tp in entries {
            let bytes = tp.encode_to_vec();
            prost::encoding::encode_varint(bytes.len() as u64, &mut out);
            out.extend_from_slice(&bytes);
        }
        out
    }

    #[test]
    fn library_produced_contact_decodes() {
        let transport = encode_transport_list(&[TransportProtocol {
            uri: "https://owner.example.com".to_owned(),
            protocol: 0,
        }]);
        let created = create_contact_message(
            42,
            ContactMode::InlineKeys as i32,
            transport.as_ptr(),
            transport.len(),
            1,
            99,
        );
        assert_eq!(release(created.error), 0);
        let wire = take_buffer(created.contact_wire_bytes);
        let _ = take_buffer(created.secret_key_material);

        let decoded = decode(&wire);
        assert_eq!(release(decoded.error), DEREC_CATEGORY_OK);
        let value: serde_json::Value =
            serde_json::from_slice(&take_buffer(decoded.contact_json)).unwrap();
        assert_eq!(value["channel_id"], "42");
        assert_eq!(value["nonce"], "99");
        assert_eq!(value["contact_mode"], 0);
    }
}

/// The pairing entry points as a foreign caller sees them: raw pointers,
/// length-delimited endpoint lists, and error codes rather than `Result`.
///
/// These matter because validation deliberately lives in the primitives
/// rather than being repeated per SDK — every binding inherits whatever this
/// seam enforces, so what it enforces is worth pinning.
#[cfg(test)]
mod pairing_entry_point_tests {
    use super::*;
    use crate::interop::ffi::common::derec_free_buffer;
    use crate::interop::ffi::error::{DEREC_CATEGORY_OK, derec_free_error};

    fn take(buffer: DeRecBuffer) -> Vec<u8> {
        if buffer.ptr.is_null() {
            return Vec::new();
        }
        let bytes = unsafe { std::slice::from_raw_parts(buffer.ptr, buffer.len) }.to_vec();
        derec_free_buffer(buffer.ptr, buffer.len);
        bytes
    }

    fn release(mut error: DeRecError) -> i32 {
        let code = error.code;
        unsafe { derec_free_error(&mut error) };
        code
    }

    fn endpoint(uri: &str, protocol: derec_proto::Protocol) -> TransportProtocol {
        TransportProtocol {
            uri: uri.to_owned(),
            protocol: protocol as i32,
        }
    }

    /// The framing every endpoint list crosses this seam in.
    fn framed(entries: &[TransportProtocol]) -> Vec<u8> {
        encode_transport_list(entries)
    }

    fn create_contact(
        mode: derec_proto::ContactMode,
        framed_list: &[u8],
    ) -> CreateContactMessageResult {
        create_contact_message(
            42,
            mode as i32,
            framed_list.as_ptr(),
            framed_list.len(),
            0,
            0,
        )
    }

    /// The happy path, and the shape the other tests deviate from.
    #[test]
    fn create_contact_accepts_a_framed_endpoint_list() {
        let list = framed(&[
            endpoint("grpcs://a.example:443", derec_proto::Protocol::Grpc),
            endpoint("https://a.example/derec", derec_proto::Protocol::Https),
        ]);
        let result = create_contact(derec_proto::ContactMode::InlineKeys, &list);

        assert_eq!(result.error.category, DEREC_CATEGORY_OK, "unexpected error");
        let contact =
            derec_proto::ContactMessage::decode(take(result.contact_wire_bytes).as_slice())
                .expect("the produced contact decodes");
        let _ = take(result.secret_key_material);

        assert_eq!(contact.supported_transports.len(), 2);
        assert_eq!(contact.supported_transports[0].uri, "grpcs://a.example:443");
    }

    /// An empty list names no endpoint, so the contact would be unusable.
    /// Rejected at the seam rather than producing a contact nobody can answer.
    #[test]
    fn create_contact_rejects_an_empty_endpoint_list() {
        let result = create_contact(derec_proto::ContactMode::InlineKeys, &[]);

        assert_ne!(
            release(result.error),
            0,
            "an empty endpoint list must be refused"
        );
        let _ = take(result.contact_wire_bytes);
        let _ = take(result.secret_key_material);
    }

    /// Malformed framing is caught here rather than decoding into garbage: a
    /// length prefix claiming more bytes than the buffer holds.
    #[test]
    fn a_length_prefix_overrunning_the_buffer_is_refused() {
        // Varint 0x7F promises 127 bytes; only two follow.
        let malformed = [0x7Fu8, 0x00, 0x00];
        let result = create_contact(derec_proto::ContactMode::InlineKeys, &malformed);

        assert_ne!(
            release(result.error),
            0,
            "a length prefix past the end must be refused"
        );
        let _ = take(result.contact_wire_bytes);
        let _ = take(result.secret_key_material);
    }

    /// A structurally invalid endpoint inside the list is refused, so an SDK
    /// cannot smuggle a mismatched scheme past the seam.
    #[test]
    fn a_scheme_mismatched_endpoint_in_the_list_is_refused() {
        let list = framed(&[endpoint("ws://a.example", derec_proto::Protocol::Https)]);
        let result = create_contact(derec_proto::ContactMode::InlineKeys, &list);

        assert_ne!(
            release(result.error),
            0,
            "a scheme-mismatched endpoint must be refused"
        );
        let _ = take(result.contact_wire_bytes);
        let _ = take(result.secret_key_material);
    }

    /// The PrePair entry point takes the same framing, and refuses an empty
    /// list for the same reason: the reply would have nowhere to go.
    #[test]
    fn produce_pre_pair_request_requires_at_least_one_endpoint() {
        let list = framed(&[endpoint(
            "https://a.example/derec",
            derec_proto::Protocol::Https,
        )]);
        let contact = create_contact(derec_proto::ContactMode::HashedKeys, &list);
        assert_eq!(contact.error.category, DEREC_CATEGORY_OK);
        let contact_bytes = take(contact.contact_wire_bytes);
        let _ = take(contact.secret_key_material);

        let empty = produce_pre_pair_request_message(
            std::ptr::null(),
            0,
            contact_bytes.as_ptr(),
            contact_bytes.len(),
        );
        assert_ne!(
            release(empty.error),
            0,
            "a PrePair request naming no endpoint must be refused"
        );
        let _ = take(empty.envelope_wire_bytes);

        let ok = produce_pre_pair_request_message(
            list.as_ptr(),
            list.len(),
            contact_bytes.as_ptr(),
            contact_bytes.len(),
        );
        assert_eq!(
            ok.error.category, DEREC_CATEGORY_OK,
            "a framed list must be accepted"
        );
        let _ = take(ok.envelope_wire_bytes);
    }

    /// A `NO_KEYS` pre-pair completes through the C ABI alone: the contact
    /// creator generates and returns its key material, and the scanner
    /// accepts the published keys under the nonce it was given.
    #[test]
    fn a_no_keys_pre_pair_completes_through_the_c_abi() {
        const NONCE: u64 = 4242;
        let list = framed(&[endpoint(
            "https://a.example/derec",
            derec_proto::Protocol::Https,
        )]);
        let contact = create_contact_message(
            42,
            derec_proto::ContactMode::NoKeys as i32,
            list.as_ptr(),
            list.len(),
            1,
            NONCE,
        );
        assert_eq!(contact.error.category, DEREC_CATEGORY_OK);
        let contact_bytes = take(contact.contact_wire_bytes);
        let _ = take(contact.secret_key_material);

        let request = produce_pre_pair_request_message(
            list.as_ptr(),
            list.len(),
            contact_bytes.as_ptr(),
            contact_bytes.len(),
        );
        assert_eq!(request.error.category, DEREC_CATEGORY_OK);
        let request_envelope = take(request.envelope_wire_bytes);

        let extracted = extract_pre_pair_request(request_envelope.as_ptr(), request_envelope.len());
        assert_eq!(extracted.error.category, DEREC_CATEGORY_OK);
        let request_proto = take(extracted.request_proto_bytes);

        let produced = produce_pre_pair_no_keys_response_message(
            42,
            request_proto.as_ptr(),
            request_proto.len(),
        );
        assert_eq!(produced.error.category, DEREC_CATEGORY_OK);
        let response_envelope = take(produced.envelope_wire_bytes);
        let secret_key_material = take(produced.secret_key_material);
        assert!(
            decode_secret_key_material(secret_key_material.as_ptr(), secret_key_material.len())
                .is_ok(),
            "the generated key material must round-trip"
        );

        let response =
            extract_pre_pair_response(response_envelope.as_ptr(), response_envelope.len());
        assert_eq!(response.error.category, DEREC_CATEGORY_OK);
        let response_proto = take(response.response_proto_bytes);

        let processed = process_pre_pair_no_keys_response_message(
            contact_bytes.as_ptr(),
            contact_bytes.len(),
            response_proto.as_ptr(),
            response_proto.len(),
        );
        assert_eq!(processed.error.category, DEREC_CATEGORY_OK);
        assert!(!take(processed.mlkem_encapsulation_key).is_empty());
        assert!(!take(processed.ecies_public_key).is_empty());
        assert_eq!(processed.nonce, NONCE);
    }

    /// The fingerprint is the same derivation the protocol uses, so both
    /// layers show the user the same value.
    #[test]
    fn the_fingerprint_matches_the_protocol_derivation() {
        let key = [0x5A; 32];
        let result = pairing_fingerprint(key.as_ptr(), key.len());
        assert_eq!(result.error.category, DEREC_CATEGORY_OK);
        let text = unsafe { std::ffi::CStr::from_ptr(result.fingerprint) }
            .to_string_lossy()
            .into_owned();
        crate::interop::ffi::common::derec_free_string(result.fingerprint);
        assert_eq!(text, crate::primitives::pairing::fingerprint(&key));

        let short = [0x5A; 31];
        let refused = pairing_fingerprint(short.as_ptr(), short.len());
        assert!(refused.fingerprint.is_null());
        assert_ne!(release(refused.error), 0, "a 31-byte key must be refused");
    }

    /// A null pointer with a non-zero length is a caller bug, not a decode
    /// failure — it must be reported rather than dereferenced.
    #[test]
    fn a_null_pointer_with_a_non_zero_length_is_refused() {
        let result = create_contact_message(42, 0, std::ptr::null(), 8, 0, 0);

        assert_ne!(
            release(result.error),
            0,
            "a null pointer with a non-zero length must be refused"
        );
        let _ = take(result.contact_wire_bytes);
        let _ = take(result.secret_key_material);
    }
}