ant-quic 0.27.24

QUIC transport protocol with advanced NAT traversal for P2P networks
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
use crate::ConnectionCloseReason;

const ACK_CONTROL_MAGIC: &[u8; 8] = b"ANQAckC1";
pub(crate) const ACK_BIDI_REQUEST_MAGIC: &[u8; 8] = b"ANQAckB3";
const ACK_BIDI_RESPONSE_MAGIC: &[u8; 8] = b"ANQAckR2";
const PROBE_REQUEST_MAGIC: &[u8; 8] = b"ANQProR1";

const ACK_REQUEST_ID_LEN: usize = 16;
pub(crate) const ACK_BIDI_RESPONSE_MAX_BYTES: usize = ACK_BIDI_RESPONSE_MAGIC.len() + 2;

/// Reasons the remote receive pipeline rejected an ACK-requested payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ReceiveRejectReason {
    /// The local consumer side of `recv()` is no longer available.
    ConsumerGone,
    /// The payload format was invalid for the ACK request protocol.
    InvalidEnvelope,
    /// The request is not supported on this connection.
    NotSupported,
    /// The local receive queue did not admit the payload within the ACK budget.
    Backpressured,
    /// The payload was rejected for an unspecified reason.
    Unknown,
}

impl std::fmt::Display for ReceiveRejectReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let value = match self {
            Self::ConsumerGone => "ConsumerGone",
            Self::InvalidEnvelope => "InvalidEnvelope",
            Self::NotSupported => "NotSupported",
            Self::Backpressured => "Backpressured",
            Self::Unknown => "Unknown",
        };
        f.write_str(value)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AckControlOutcome {
    Accepted,
    Rejected(ReceiveRejectReason),
    Closed(ConnectionCloseReason),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct AckBidiRequest<'a> {
    pub(crate) request_id: [u8; ACK_REQUEST_ID_LEN],
    pub(crate) payload: &'a [u8],
}

pub(crate) fn encode_ack_bidi_request(
    request_id: [u8; ACK_REQUEST_ID_LEN],
    payload: &[u8],
) -> Vec<u8> {
    let mut bytes =
        Vec::with_capacity(ACK_BIDI_REQUEST_MAGIC.len() + ACK_REQUEST_ID_LEN + payload.len());
    bytes.extend_from_slice(ACK_BIDI_REQUEST_MAGIC);
    bytes.extend_from_slice(&request_id);
    bytes.extend_from_slice(payload);
    bytes
}

pub(crate) fn decode_ack_bidi_request(bytes: &[u8]) -> Option<AckBidiRequest<'_>> {
    if bytes.len() < ACK_BIDI_REQUEST_MAGIC.len() + ACK_REQUEST_ID_LEN
        || !bytes.starts_with(ACK_BIDI_REQUEST_MAGIC)
    {
        return None;
    }

    let mut request_id = [0u8; ACK_REQUEST_ID_LEN];
    request_id.copy_from_slice(
        &bytes[ACK_BIDI_REQUEST_MAGIC.len()..ACK_BIDI_REQUEST_MAGIC.len() + ACK_REQUEST_ID_LEN],
    );
    Some(AckBidiRequest {
        request_id,
        payload: &bytes[ACK_BIDI_REQUEST_MAGIC.len() + ACK_REQUEST_ID_LEN..],
    })
}

pub(crate) fn encode_ack_control(tag: [u8; 16], outcome: AckControlOutcome) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(ACK_CONTROL_MAGIC.len() + 18);
    bytes.extend_from_slice(ACK_CONTROL_MAGIC);
    bytes.extend_from_slice(&tag);
    match outcome {
        AckControlOutcome::Accepted => {
            bytes.push(0);
            bytes.push(0);
        }
        AckControlOutcome::Rejected(reason) => {
            bytes.push(1);
            bytes.push(match reason {
                ReceiveRejectReason::ConsumerGone => 1,
                ReceiveRejectReason::InvalidEnvelope => 2,
                ReceiveRejectReason::NotSupported => 3,
                ReceiveRejectReason::Backpressured => 4,
                ReceiveRejectReason::Unknown => 255,
            });
        }
        AckControlOutcome::Closed(reason) => {
            bytes.push(2);
            bytes.push(match reason {
                ConnectionCloseReason::Superseded => 1,
                ConnectionCloseReason::ReaderExit => 2,
                ConnectionCloseReason::PeerShutdown => 3,
                ConnectionCloseReason::Banned => 4,
                ConnectionCloseReason::LifecycleCleanup => 5,
                ConnectionCloseReason::LivenessTimeout => 14,
                ConnectionCloseReason::ApplicationClosed => 6,
                ConnectionCloseReason::ConnectionClosed => 7,
                ConnectionCloseReason::TimedOut => 8,
                ConnectionCloseReason::Reset => 9,
                ConnectionCloseReason::TransportError => 10,
                ConnectionCloseReason::LocallyClosed => 11,
                ConnectionCloseReason::VersionMismatch => 12,
                ConnectionCloseReason::CidsExhausted => 13,
                ConnectionCloseReason::Unknown => 255,
            });
        }
    }
    bytes
}

pub(crate) fn encode_ack_bidi_response(outcome: AckControlOutcome) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(ACK_BIDI_RESPONSE_MAX_BYTES);
    bytes.extend_from_slice(ACK_BIDI_RESPONSE_MAGIC);
    match outcome {
        AckControlOutcome::Accepted => {
            bytes.push(0);
            bytes.push(0);
        }
        AckControlOutcome::Rejected(reason) => {
            bytes.push(1);
            bytes.push(match reason {
                ReceiveRejectReason::ConsumerGone => 1,
                ReceiveRejectReason::InvalidEnvelope => 2,
                ReceiveRejectReason::NotSupported => 3,
                ReceiveRejectReason::Backpressured => 4,
                ReceiveRejectReason::Unknown => 255,
            });
        }
        AckControlOutcome::Closed(reason) => {
            bytes.push(2);
            bytes.push(match reason {
                ConnectionCloseReason::Superseded => 1,
                ConnectionCloseReason::ReaderExit => 2,
                ConnectionCloseReason::PeerShutdown => 3,
                ConnectionCloseReason::Banned => 4,
                ConnectionCloseReason::LifecycleCleanup => 5,
                ConnectionCloseReason::LivenessTimeout => 14,
                ConnectionCloseReason::ApplicationClosed => 6,
                ConnectionCloseReason::ConnectionClosed => 7,
                ConnectionCloseReason::TimedOut => 8,
                ConnectionCloseReason::Reset => 9,
                ConnectionCloseReason::TransportError => 10,
                ConnectionCloseReason::LocallyClosed => 11,
                ConnectionCloseReason::VersionMismatch => 12,
                ConnectionCloseReason::CidsExhausted => 13,
                ConnectionCloseReason::Unknown => 255,
            });
        }
    }
    bytes
}

pub(crate) fn decode_ack_bidi_response(bytes: &[u8]) -> Option<AckControlOutcome> {
    if bytes.len() != ACK_BIDI_RESPONSE_MAX_BYTES || !bytes.starts_with(ACK_BIDI_RESPONSE_MAGIC) {
        return None;
    }

    let kind = bytes[ACK_BIDI_RESPONSE_MAGIC.len()];
    let value = bytes[ACK_BIDI_RESPONSE_MAGIC.len() + 1];
    match kind {
        0 => Some(AckControlOutcome::Accepted),
        1 => Some(AckControlOutcome::Rejected(match value {
            1 => ReceiveRejectReason::ConsumerGone,
            2 => ReceiveRejectReason::InvalidEnvelope,
            3 => ReceiveRejectReason::NotSupported,
            4 => ReceiveRejectReason::Backpressured,
            _ => ReceiveRejectReason::Unknown,
        })),
        2 => Some(AckControlOutcome::Closed(match value {
            1 => ConnectionCloseReason::Superseded,
            2 => ConnectionCloseReason::ReaderExit,
            3 => ConnectionCloseReason::PeerShutdown,
            4 => ConnectionCloseReason::Banned,
            5 => ConnectionCloseReason::LifecycleCleanup,
            6 => ConnectionCloseReason::ApplicationClosed,
            7 => ConnectionCloseReason::ConnectionClosed,
            8 => ConnectionCloseReason::TimedOut,
            9 => ConnectionCloseReason::Reset,
            10 => ConnectionCloseReason::TransportError,
            11 => ConnectionCloseReason::LocallyClosed,
            12 => ConnectionCloseReason::VersionMismatch,
            13 => ConnectionCloseReason::CidsExhausted,
            14 => ConnectionCloseReason::LivenessTimeout,
            _ => ConnectionCloseReason::Unknown,
        })),
        _ => None,
    }
}

pub(crate) fn decode_ack_control(bytes: &[u8]) -> Option<([u8; 16], AckControlOutcome)> {
    if bytes.len() != ACK_CONTROL_MAGIC.len() + 18 || !bytes.starts_with(ACK_CONTROL_MAGIC) {
        return None;
    }

    let mut tag = [0u8; 16];
    tag.copy_from_slice(&bytes[ACK_CONTROL_MAGIC.len()..ACK_CONTROL_MAGIC.len() + 16]);
    let kind = bytes[ACK_CONTROL_MAGIC.len() + 16];
    let value = bytes[ACK_CONTROL_MAGIC.len() + 17];
    let outcome = match kind {
        0 => AckControlOutcome::Accepted,
        1 => AckControlOutcome::Rejected(match value {
            1 => ReceiveRejectReason::ConsumerGone,
            2 => ReceiveRejectReason::InvalidEnvelope,
            3 => ReceiveRejectReason::NotSupported,
            4 => ReceiveRejectReason::Backpressured,
            _ => ReceiveRejectReason::Unknown,
        }),
        2 => AckControlOutcome::Closed(match value {
            1 => ConnectionCloseReason::Superseded,
            2 => ConnectionCloseReason::ReaderExit,
            3 => ConnectionCloseReason::PeerShutdown,
            4 => ConnectionCloseReason::Banned,
            5 => ConnectionCloseReason::LifecycleCleanup,
            6 => ConnectionCloseReason::ApplicationClosed,
            7 => ConnectionCloseReason::ConnectionClosed,
            8 => ConnectionCloseReason::TimedOut,
            9 => ConnectionCloseReason::Reset,
            10 => ConnectionCloseReason::TransportError,
            11 => ConnectionCloseReason::LocallyClosed,
            12 => ConnectionCloseReason::VersionMismatch,
            13 => ConnectionCloseReason::CidsExhausted,
            14 => ConnectionCloseReason::LivenessTimeout,
            _ => ConnectionCloseReason::Unknown,
        }),
        _ => return None,
    };
    Some((tag, outcome))
}

/// Encode a probe-liveness request envelope.
///
/// Carries only the 16-byte correlation tag — no user payload. Distinct magic
/// from ACK-v2 request envelopes so the reader path can short-circuit probes
/// without forwarding anything to the application receive channel.
pub(crate) fn encode_probe_request(tag: [u8; 16]) -> Vec<u8> {
    let mut bytes = Vec::with_capacity(PROBE_REQUEST_MAGIC.len() + tag.len());
    bytes.extend_from_slice(PROBE_REQUEST_MAGIC);
    bytes.extend_from_slice(&tag);
    bytes
}

/// Decode a probe-liveness request envelope.
///
/// Returns `Some(tag)` when `bytes` is exactly a probe envelope. Probe responses
/// are carried as ordinary [`AckControlOutcome::Accepted`] control frames so the
/// existing waiter machinery resolves them.
pub(crate) fn decode_probe_request(bytes: &[u8]) -> Option<[u8; 16]> {
    if bytes.len() != PROBE_REQUEST_MAGIC.len() + 16 || !bytes.starts_with(PROBE_REQUEST_MAGIC) {
        return None;
    }
    let mut tag = [0u8; 16];
    tag.copy_from_slice(&bytes[PROBE_REQUEST_MAGIC.len()..PROBE_REQUEST_MAGIC.len() + 16]);
    Some(tag)
}

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

    // AckControlOutcome tests

    #[test]
    fn ack_control_accepted_roundtrip() {
        let tag = [0xCD; 16];
        let encoded = encode_ack_control(tag, AckControlOutcome::Accepted);
        let (decoded_tag, outcome) = decode_ack_control(&encoded).unwrap();
        assert_eq!(decoded_tag, tag);
        assert_eq!(outcome, AckControlOutcome::Accepted);
    }

    #[test]
    fn ack_control_all_reject_reasons_roundtrip() {
        let tag = [0xCD; 16];
        let reasons = [
            ReceiveRejectReason::ConsumerGone,
            ReceiveRejectReason::InvalidEnvelope,
            ReceiveRejectReason::NotSupported,
            ReceiveRejectReason::Backpressured,
            ReceiveRejectReason::Unknown,
        ];
        for reason in &reasons {
            let outcome = AckControlOutcome::Rejected(*reason);
            let encoded = encode_ack_control(tag, outcome);
            let (decoded_tag, decoded_outcome) = decode_ack_control(&encoded).unwrap();
            assert_eq!(decoded_tag, tag, "failed for reason {reason:?}");
            assert_eq!(decoded_outcome, outcome, "failed for reason {reason:?}");
        }
    }

    #[test]
    fn ack_control_all_close_reasons_roundtrip() {
        let tag = [0xCD; 16];
        let reasons = [
            ConnectionCloseReason::Superseded,
            ConnectionCloseReason::ReaderExit,
            ConnectionCloseReason::PeerShutdown,
            ConnectionCloseReason::Banned,
            ConnectionCloseReason::LifecycleCleanup,
            ConnectionCloseReason::LivenessTimeout,
            ConnectionCloseReason::ApplicationClosed,
            ConnectionCloseReason::ConnectionClosed,
            ConnectionCloseReason::TimedOut,
            ConnectionCloseReason::Reset,
            ConnectionCloseReason::TransportError,
            ConnectionCloseReason::LocallyClosed,
            ConnectionCloseReason::VersionMismatch,
            ConnectionCloseReason::CidsExhausted,
            ConnectionCloseReason::Unknown,
        ];
        for reason in &reasons {
            let outcome = AckControlOutcome::Closed(*reason);
            let encoded = encode_ack_control(tag, outcome);
            let (decoded_tag, decoded_outcome) = decode_ack_control(&encoded).unwrap();
            assert_eq!(decoded_tag, tag, "failed for reason {reason:?}");
            assert_eq!(decoded_outcome, outcome, "failed for reason {reason:?}");
        }
    }

    #[test]
    fn ack_control_rejects_short_input() {
        assert!(decode_ack_control(&[]).is_none());
        assert!(decode_ack_control(&[0; 18]).is_none());
    }

    #[test]
    fn ack_control_rejects_wrong_magic() {
        let mut encoded = encode_ack_control([0xCD; 16], AckControlOutcome::Accepted);
        encoded[0] ^= 0xFF;
        assert!(decode_ack_control(&encoded).is_none());
    }

    #[test]
    fn ack_control_rejects_invalid_kind() {
        let mut encoded: Vec<u8> = ACK_CONTROL_MAGIC.to_vec();
        encoded.extend_from_slice(&[0u8; 16]);
        encoded.push(3);
        encoded.push(0);
        assert!(decode_ack_control(&encoded).is_none());
    }

    #[test]
    fn ack_control_unknown_reject_value_maps_to_unknown() {
        let mut bytes: Vec<u8> = ACK_CONTROL_MAGIC.to_vec();
        bytes.extend_from_slice(&[0u8; 16]);
        bytes.push(1);
        bytes.push(99);
        let (_, outcome) = decode_ack_control(&bytes).unwrap();
        assert_eq!(
            outcome,
            AckControlOutcome::Rejected(ReceiveRejectReason::Unknown)
        );
    }

    #[test]
    fn ack_control_unknown_close_value_maps_to_unknown() {
        let mut bytes: Vec<u8> = ACK_CONTROL_MAGIC.to_vec();
        bytes.extend_from_slice(&[0u8; 16]);
        bytes.push(2);
        bytes.push(99);
        let (_, outcome) = decode_ack_control(&bytes).unwrap();
        assert_eq!(
            outcome,
            AckControlOutcome::Closed(ConnectionCloseReason::Unknown)
        );
    }

    // AckBidiRequest tests

    #[test]
    fn ack_bidi_request_roundtrip() {
        let request_id = [0xA5; 16];
        let payload = b"hello";
        let encoded = encode_ack_bidi_request(request_id, payload);
        let decoded = decode_ack_bidi_request(&encoded).unwrap();
        assert_eq!(decoded.request_id, request_id);
        assert_eq!(decoded.payload, payload);
        assert_eq!(
            encoded.len(),
            ACK_BIDI_REQUEST_MAGIC.len() + ACK_REQUEST_ID_LEN + payload.len()
        );
    }

    #[test]
    fn ack_bidi_request_empty_payload() {
        let request_id = [0xB0; 16];
        let encoded = encode_ack_bidi_request(request_id, b"");
        let decoded = decode_ack_bidi_request(&encoded).unwrap();
        assert_eq!(decoded.request_id, request_id);
        assert!(decoded.payload.is_empty());
    }

    #[test]
    fn ack_bidi_request_rejects_too_short() {
        assert!(decode_ack_bidi_request(&[]).is_none());
        assert!(decode_ack_bidi_request(&[0u8; 23]).is_none());
        assert!(decode_ack_bidi_request(ACK_BIDI_REQUEST_MAGIC).is_none());
    }

    #[test]
    fn ack_bidi_request_rejects_wrong_magic() {
        let mut corrupted = encode_ack_bidi_request([0xA5; 16], b"test");
        corrupted[0] ^= 0xFF;
        assert!(decode_ack_bidi_request(&corrupted).is_none());
    }

    // AckBidiResponse tests

    #[test]
    fn ack_bidi_response_accepted_roundtrip() {
        let encoded = encode_ack_bidi_response(AckControlOutcome::Accepted);
        let decoded = decode_ack_bidi_response(&encoded).unwrap();
        assert_eq!(decoded, AckControlOutcome::Accepted);
    }

    #[test]
    fn ack_bidi_response_all_reject_reasons_roundtrip() {
        let reasons = [
            ReceiveRejectReason::ConsumerGone,
            ReceiveRejectReason::InvalidEnvelope,
            ReceiveRejectReason::NotSupported,
            ReceiveRejectReason::Backpressured,
            ReceiveRejectReason::Unknown,
        ];
        for reason in &reasons {
            let outcome = AckControlOutcome::Rejected(*reason);
            let encoded = encode_ack_bidi_response(outcome);
            let decoded = decode_ack_bidi_response(&encoded).unwrap();
            assert_eq!(decoded, outcome);
        }
    }

    #[test]
    fn ack_bidi_response_all_close_reasons_roundtrip() {
        let reasons = [
            ConnectionCloseReason::Superseded,
            ConnectionCloseReason::ReaderExit,
            ConnectionCloseReason::PeerShutdown,
            ConnectionCloseReason::Banned,
            ConnectionCloseReason::LifecycleCleanup,
            ConnectionCloseReason::LivenessTimeout,
            ConnectionCloseReason::ApplicationClosed,
            ConnectionCloseReason::ConnectionClosed,
            ConnectionCloseReason::TimedOut,
            ConnectionCloseReason::Reset,
            ConnectionCloseReason::TransportError,
            ConnectionCloseReason::LocallyClosed,
            ConnectionCloseReason::VersionMismatch,
            ConnectionCloseReason::CidsExhausted,
            ConnectionCloseReason::Unknown,
        ];
        for reason in &reasons {
            let outcome = AckControlOutcome::Closed(*reason);
            let encoded = encode_ack_bidi_response(outcome);
            let decoded = decode_ack_bidi_response(&encoded).unwrap();
            assert_eq!(decoded, outcome);
        }
    }

    #[test]
    fn ack_bidi_response_rejects_wrong_length() {
        assert!(decode_ack_bidi_response(&[]).is_none());
        let mut too_short: Vec<u8> = ACK_BIDI_RESPONSE_MAGIC.to_vec();
        too_short.push(0);
        assert!(decode_ack_bidi_response(&too_short).is_none());
    }

    #[test]
    fn ack_bidi_response_rejects_wrong_magic() {
        let encoded = encode_ack_bidi_response(AckControlOutcome::Accepted);
        let mut corrupted = encoded;
        corrupted[0] ^= 0xFF;
        assert!(decode_ack_bidi_response(&corrupted).is_none());
    }

    #[test]
    fn ack_bidi_response_rejects_invalid_kind() {
        let mut bytes: Vec<u8> = ACK_BIDI_RESPONSE_MAGIC.to_vec();
        bytes.push(3);
        bytes.push(0);
        assert!(decode_ack_bidi_response(&bytes).is_none());
    }

    #[test]
    fn ack_bidi_response_unknown_reject_value() {
        let mut bytes: Vec<u8> = ACK_BIDI_RESPONSE_MAGIC.to_vec();
        bytes.push(1);
        bytes.push(99);
        let outcome = decode_ack_bidi_response(&bytes).unwrap();
        assert_eq!(
            outcome,
            AckControlOutcome::Rejected(ReceiveRejectReason::Unknown)
        );
    }

    #[test]
    fn ack_bidi_response_unknown_close_value() {
        let mut bytes: Vec<u8> = ACK_BIDI_RESPONSE_MAGIC.to_vec();
        bytes.push(2);
        bytes.push(99);
        let outcome = decode_ack_bidi_response(&bytes).unwrap();
        assert_eq!(
            outcome,
            AckControlOutcome::Closed(ConnectionCloseReason::Unknown)
        );
    }

    // Probe request tests

    #[test]
    fn probe_request_roundtrip() {
        let tag = [0x5A; 16];
        let encoded = encode_probe_request(tag);
        let decoded = decode_probe_request(&encoded).unwrap();
        assert_eq!(decoded, tag);
    }

    #[test]
    fn probe_request_different_tags_roundtrip() {
        for b in [0x00u8, 0xFF, 0xAA, 0x55] {
            let tag = [b; 16];
            let encoded = encode_probe_request(tag);
            let decoded = decode_probe_request(&encoded).unwrap();
            assert_eq!(decoded, tag, "failed for byte value 0x{b:02x}");
        }
    }

    #[test]
    fn probe_envelope_distinct_from_ack() {
        let tag = [0x77; 16];
        let probe = encode_probe_request(tag);
        assert!(decode_ack_control(&probe).is_none());

        let ack_control = encode_ack_control(tag, AckControlOutcome::Accepted);
        assert!(decode_probe_request(&ack_control).is_none());

        let ack_bidi = encode_ack_bidi_request([0x22; 16], b"hi");
        assert!(decode_probe_request(&ack_bidi).is_none());
        assert!(decode_ack_control(&ack_bidi).is_none());
    }

    #[test]
    fn probe_request_rejects_wrong_length() {
        let mut too_short: Vec<u8> = PROBE_REQUEST_MAGIC.to_vec();
        too_short.extend_from_slice(&[0u8; 15]);
        assert!(decode_probe_request(&too_short).is_none());

        let mut too_long: Vec<u8> = PROBE_REQUEST_MAGIC.to_vec();
        too_long.extend_from_slice(&[0u8; 17]);
        assert!(decode_probe_request(&too_long).is_none());
    }

    #[test]
    fn probe_request_rejects_wrong_magic() {
        let mut corrupted = encode_probe_request([0x5A; 16]);
        corrupted[0] ^= 0xFF;
        assert!(decode_probe_request(&corrupted).is_none());
    }

    // ReceiveRejectReason tests

    #[test]
    fn receive_reject_reason_display_all_variants() {
        assert_eq!(
            ReceiveRejectReason::ConsumerGone.to_string(),
            "ConsumerGone"
        );
        assert_eq!(
            ReceiveRejectReason::InvalidEnvelope.to_string(),
            "InvalidEnvelope"
        );
        assert_eq!(
            ReceiveRejectReason::NotSupported.to_string(),
            "NotSupported"
        );
        assert_eq!(
            ReceiveRejectReason::Backpressured.to_string(),
            "Backpressured"
        );
        assert_eq!(ReceiveRejectReason::Unknown.to_string(), "Unknown");
    }

    #[test]
    fn receive_reject_reason_equality_and_copy() {
        assert_eq!(
            ReceiveRejectReason::ConsumerGone,
            ReceiveRejectReason::ConsumerGone
        );
        assert_ne!(
            ReceiveRejectReason::ConsumerGone,
            ReceiveRejectReason::Unknown
        );
        let a = ReceiveRejectReason::ConsumerGone;
        let b = a;
        assert_eq!(a, b);
    }
}