derec-library 0.0.1

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
// 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 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 crate::transport::TransportProtocolExt as _;
use crate::utils::ContactMessageExt as _;
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_transport_protocol: 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,
}

/// 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_protocol_ptr: *const u8,
    transport_protocol_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 transport_protocol =
        match decode_transport_protocol(transport_protocol_ptr, transport_protocol_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,
        transport_protocol,
        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)),
    }
}

/// Structurally validate a proto-encoded `ContactMessage`. Returns a
/// successful [`DeRecError`] iff the contact's `(contact_mode, inline keys,
/// binding hash)` tuple satisfies the per-mode invariants enforced by the
/// pairing primitives. Intended for bindings to call at their parse
/// boundary (e.g. `FromProtoBytes`) so that the decoded value handed to
/// application code is guaranteed well-formed.
///
/// Failure codes:
/// - [`DEREC_CODE_FFI_BAD_PROTO`] if the bytes do not decode as a
///   `ContactMessage`.
/// - The library's `InvalidContactMessage` error code on any structural
///   violation (unknown `contact_mode`, mode/field mismatch, wrong
///   binding-hash length).
///
/// # Safety
///
/// `contact_message_ptr` must point to a readable range of
/// `contact_message_len` bytes (or be null with `len == 0`).
#[unsafe(no_mangle)]
pub extern "C" fn validate_contact_message(
    contact_message_ptr: *const u8,
    contact_message_len: usize,
) -> DeRecError {
    let contact_message_bytes = match parse_buffer(
        contact_message_ptr,
        contact_message_len,
        "contact_message_ptr",
    ) {
        Ok(b) => b,
        Err(e) => return e,
    };
    let contact_message = match ContactMessage::decode(contact_message_bytes) {
        Ok(c) => c,
        Err(_) => {
            return ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                "contact_message_bytes is not a valid ContactMessage",
            );
        }
    };
    match contact_message.validate() {
        Ok(()) => success(),
        Err(e) => from_lib_error(e),
    }
}

/// Encodes a JSON [`ContactMessageDto`] to `ContactMessage` proto wire bytes.
/// Structurally validates the input first so a locally-constructed contact
/// that violates the mode/field invariant is rejected at the boundary rather
/// than silently serialized.
///
/// 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();
    if let Err(e) = contact_message.validate() {
        return with_err(from_lib_error(e));
    }
    EncodeContactMessageResult {
        error: success(),
        wire_bytes: vec_into_buffer(contact_message.encode_to_vec()),
    }
}

/// Decodes proto-encoded `ContactMessage` wire bytes into the JSON
/// [`ContactMessageDto`] shape described on [`encode_contact_message`].
/// Structurally validates the decoded value before returning it to
/// application code so consumers can trust the mode/field invariants
/// documented on the wire format.
///
/// # 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 ContactMessage::decode(wire_bytes) {
        Ok(c) => c,
        Err(e) => {
            return with_err(ffi_error(
                DEREC_CODE_FFI_BAD_PROTO,
                format!("contact_wire_bytes is not a valid ContactMessage: {e}"),
            ));
        }
    };
    if let Err(e) = contact_message.validate() {
        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"];

/// 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(())
}

/// `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_protocol_ptr: *const u8,
    transport_protocol_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 transport_protocol =
        match decode_transport_protocol(transport_protocol_ptr, transport_protocol_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,
        transport_protocol,
        &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)),
    }
}

/// # 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,
) -> 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 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(),
    ) {
        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,
) -> ProducePairResponseMessageResult {
    let with_err = |error| ProducePairResponseMessageResult {
        error,
        response_wire_bytes: empty_buffer(),
        peer_transport_protocol: 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,
    ) {
        Ok(r) => ProducePairResponseMessageResult {
            error: success(),
            response_wire_bytes: vec_into_buffer(r.envelope),
            peer_transport_protocol: vec_into_buffer(r.peer_transport_protocol.encode_to_vec()),
            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`].
///
/// # Safety
///
/// Non-null input pointers must point to the corresponding readable byte ranges.
#[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,
) -> 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),
        };

    match crate::primitives::pairing::response::process(
        &contact_message,
        &response,
        &pairing_secret_key_material,
    ) {
        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_protocol_ptr: *const u8,
    transport_protocol_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_protocol =
        match decode_transport_protocol(transport_protocol_ptr, transport_protocol_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_protocol,
        &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)),
    }
}

/// 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)),
    }
}

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) })
    }
}

fn decode_transport_protocol(ptr: *const u8, len: usize) -> Result<TransportProtocol, DeRecError> {
    let bytes = parse_buffer(ptr, len, "transport_protocol_ptr")?;
    let tp = TransportProtocol::decode(bytes).map_err(|_| {
        ffi_error(
            DEREC_CODE_FFI_BAD_PROTO,
            "transport_protocol_bytes is not a valid TransportProtocol",
        )
    })?;
    // Reject mismatched-scheme / malformed transport at the FFI seam.
    // Same gate runs at every primitive `extract`; running it here
    // means application-supplied transport bytes are validated even
    // before the primitive sees them.
    tp.validate()
        .map_err(|e| from_lib_error(crate::Error::Transport(e)))?;
    Ok(tp)
}

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 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",
        "transport_protocol": { "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["transport_protocol"]["uri"],
            "https://owner.example.com"
        );
        assert_eq!(value["transport_protocol"]["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",
            "transport_protocol": { "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,
            transport_protocol: Some(TransportProtocol {
                uri: "https://owner.example.com".to_owned(),
                protocol: 0,
            }),
            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,
        }
        .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.
    #[test]
    fn library_produced_contact_decodes() {
        let transport = TransportProtocol {
            uri: "https://owner.example.com".to_owned(),
            protocol: 0,
        }
        .encode_to_vec();
        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);
    }
}