derec-library 0.0.1-alpha.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
// 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::ffi::common::{DeRecBuffer, empty_buffer, vec_into_buffer};
use crate::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 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::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),
    }
}

/// `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
}