rns-core 0.7.0

Wire protocol, transport routing, and link/resource engine for the Reticulum Network Stack
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;

use crate::constants;
use crate::transport::types::PacketBytes;

/// Storage for a packet's wire bytes that can hand them over as shared
/// [`PacketBytes`]: shared bytes are cloned, anything else is copied.
pub trait PacketStorage: AsRef<[u8]> {
    fn to_shared(&self) -> PacketBytes;
}

impl PacketStorage for Vec<u8> {
    fn to_shared(&self) -> PacketBytes {
        PacketBytes::from(self.as_slice())
    }
}

impl PacketStorage for &[u8] {
    fn to_shared(&self) -> PacketBytes {
        PacketBytes::from(*self)
    }
}

impl PacketStorage for Arc<[u8]> {
    fn to_shared(&self) -> PacketBytes {
        self.clone()
    }
}

#[derive(Debug)]
pub enum PacketError {
    TooShort,
    ExceedsMtu,
    MissingTransportId,
    InvalidHeaderType,
    ZeroLengthData,
    /// Hop counts at or above `PATHFINDER_M` are malformed, as upstream
    /// `Packet.unpack` (Packet.py:250) rejects them before the transport
    /// hop limiter is consulted; the receiving interface counts a protocol
    /// violation (Transport.py:2008).
    InvalidHopCount(u8),
}

impl fmt::Display for PacketError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PacketError::TooShort => write!(f, "Packet too short"),
            PacketError::ExceedsMtu => write!(f, "Packet exceeds MTU"),
            PacketError::MissingTransportId => write!(f, "HEADER_2 requires transport_id"),
            PacketError::InvalidHeaderType => write!(f, "Invalid header type"),
            PacketError::ZeroLengthData => write!(f, "Zero-length data field"),
            PacketError::InvalidHopCount(hops) => write!(f, "Invalid hop count: {}", hops),
        }
    }
}

// =============================================================================
// PacketFlags: packs 5 fields into one byte
// =============================================================================

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PacketFlags {
    pub header_type: u8,
    pub context_flag: u8,
    pub transport_type: u8,
    pub destination_type: u8,
    pub packet_type: u8,
}

impl PacketFlags {
    /// Pack fields into a single flags byte.
    ///
    /// Bit layout:
    /// ```text
    /// Bit 6:     header_type (1 bit)
    /// Bit 5:     context_flag (1 bit)
    /// Bit 4:     transport_type (1 bit)
    /// Bits 3-2:  destination_type (2 bits)
    /// Bits 1-0:  packet_type (2 bits)
    /// ```
    pub fn pack(&self) -> u8 {
        (self.header_type << 6)
            | (self.context_flag << 5)
            | (self.transport_type << 4)
            | (self.destination_type << 2)
            | self.packet_type
    }

    /// Unpack a flags byte into fields.
    pub fn unpack(byte: u8) -> Self {
        PacketFlags {
            header_type: (byte & 0b01000000) >> 6,
            context_flag: (byte & 0b00100000) >> 5,
            transport_type: (byte & 0b00010000) >> 4,
            destination_type: (byte & 0b00001100) >> 2,
            packet_type: byte & 0b00000011,
        }
    }
}

// =============================================================================
// RawPacket: wire-level packet representation
// =============================================================================

/// A packet's header fields and its wire bytes `raw`, owned (`Vec<u8>`, the
/// default) or in other storage: a borrowed view (`&[u8]`) reads a packet
/// without copying it, and shared bytes (`PacketBytes`) are cloned, not copied.
#[derive(Debug, Clone)]
pub struct RawPacket<B = Vec<u8>> {
    pub flags: PacketFlags,
    pub hops: u8,
    pub transport_id: Option<[u8; 16]>,
    pub destination_hash: [u8; 16],
    pub context: u8,
    pub raw: B,
    pub packet_hash: [u8; 32],
    pub rssi: Option<i16>,
    pub snr: Option<f32>,
}

impl RawPacket {
    /// Offset of the payload in the wire bytes of a packet with this header type.
    #[inline]
    pub const fn data_offset(header_type: u8) -> usize {
        if header_type == constants::HEADER_2 {
            2 + 2 * (constants::TRUNCATED_HASHLENGTH / 8) + 1
        } else {
            2 + constants::TRUNCATED_HASHLENGTH / 8 + 1
        }
    }

    /// [`RawPacket::is_unhashed_link_resource`] for wire bytes that are not
    /// unpacked; `false` when they are too short to carry a context byte.
    pub fn is_unhashed_link_resource_wire(raw: &[u8]) -> bool {
        let Some(&flags) = raw.first() else {
            return false;
        };
        let flags = PacketFlags::unpack(flags);
        raw.get(Self::data_offset(flags.header_type) - 1)
            .is_some_and(|&context| Self::is_unhashed_link_resource_header(&flags, context))
    }

    #[inline]
    fn is_unhashed_link_resource_header(flags: &PacketFlags, context: u8) -> bool {
        flags.destination_type == constants::DESTINATION_LINK
            && match context {
                constants::CONTEXT_RESOURCE | constants::CONTEXT_RESOURCE_REQ => {
                    flags.packet_type == constants::PACKET_TYPE_DATA
                }
                constants::CONTEXT_RESOURCE_PRF => {
                    flags.packet_type == constants::PACKET_TYPE_PROOF
                }
                _ => false,
            }
    }

    /// Pack fields into raw bytes.
    pub fn pack(
        flags: PacketFlags,
        hops: u8,
        destination_hash: &[u8; 16],
        transport_id: Option<&[u8; 16]>,
        context: u8,
        data: &[u8],
    ) -> Result<Self, PacketError> {
        Self::pack_with_max_mtu(
            flags,
            hops,
            destination_hash,
            transport_id,
            context,
            data,
            constants::MTU,
        )
    }

    /// Pack fields into raw bytes and packet hash without constructing a full RawPacket.
    pub fn pack_raw_with_hash(
        flags: PacketFlags,
        hops: u8,
        destination_hash: &[u8; 16],
        transport_id: Option<&[u8; 16]>,
        context: u8,
        data: &[u8],
    ) -> Result<(Vec<u8>, [u8; 32]), PacketError> {
        Self::pack_raw_with_hash_with_max_mtu(
            flags,
            hops,
            destination_hash,
            transport_id,
            context,
            data,
            constants::MTU,
        )
    }

    /// Pack fields into raw bytes with a caller-provided MTU limit.
    pub fn pack_with_max_mtu(
        flags: PacketFlags,
        hops: u8,
        destination_hash: &[u8; 16],
        transport_id: Option<&[u8; 16]>,
        context: u8,
        data: &[u8],
        max_mtu: usize,
    ) -> Result<Self, PacketError> {
        let (raw, packet_hash) = Self::pack_raw_with_hash_with_max_mtu(
            flags,
            hops,
            destination_hash,
            transport_id,
            context,
            data,
            max_mtu,
        )?;

        Ok(RawPacket {
            flags,
            hops,
            transport_id: transport_id.copied(),
            destination_hash: *destination_hash,
            context,
            raw,
            packet_hash,
            rssi: None,
            snr: None,
        })
    }

    /// Pack fields into raw bytes and packet hash with a caller-provided MTU limit.
    pub fn pack_raw_with_hash_with_max_mtu(
        flags: PacketFlags,
        hops: u8,
        destination_hash: &[u8; 16],
        transport_id: Option<&[u8; 16]>,
        context: u8,
        data: &[u8],
        max_mtu: usize,
    ) -> Result<(Vec<u8>, [u8; 32]), PacketError> {
        let raw = Self::pack_raw_with_max_mtu(
            flags,
            hops,
            destination_hash,
            transport_id,
            context,
            data,
            max_mtu,
        )?;
        let packet_hash = Self::compute_packet_hash(flags.header_type, &raw);
        Ok((raw, packet_hash))
    }

    /// Pack only wire bytes when the caller does not need a packet hash.
    /// Validation and encoding match the hash-producing packing methods.
    /// [`RawPacket::pack_raw_with_hash_with_max_mtu`] into shared bytes.
    #[allow(clippy::too_many_arguments)]
    pub fn pack_raw_shared_with_hash_with_max_mtu(
        flags: PacketFlags,
        hops: u8,
        destination_hash: &[u8; 16],
        transport_id: Option<&[u8; 16]>,
        context: u8,
        data: &[u8],
        max_mtu: usize,
    ) -> Result<(PacketBytes, [u8; 32]), PacketError> {
        let raw = Self::pack_raw_shared_with_max_mtu(
            flags,
            hops,
            destination_hash,
            transport_id,
            context,
            data,
            max_mtu,
        )?;
        let packet_hash = Self::compute_packet_hash(flags.header_type, &raw);
        Ok((raw, packet_hash))
    }

    /// The packet hash of packed wire bytes with the given header type.
    pub fn packet_hash_of(header_type: u8, raw: &[u8]) -> [u8; 32] {
        Self::compute_packet_hash(header_type, raw)
    }

    /// [`RawPacket::pack_raw_shared_with_max_mtu`] with a payload of
    /// `payload_len` bytes that `fill` writes in place, so a payload produced
    /// for this packet (a ciphertext, say) needs no buffer of its own. `fill`
    /// receives the payload zeroed.
    #[allow(clippy::too_many_arguments)]
    pub fn pack_raw_shared_filled_with_max_mtu(
        flags: PacketFlags,
        hops: u8,
        destination_hash: &[u8; 16],
        transport_id: Option<&[u8; 16]>,
        context: u8,
        payload_len: usize,
        max_mtu: usize,
        fill: impl FnOnce(&mut [u8]),
    ) -> Result<PacketBytes, PacketError> {
        if flags.header_type == constants::HEADER_2 && transport_id.is_none() {
            return Err(PacketError::MissingTransportId);
        }
        let transport_id = transport_id.filter(|_| flags.header_type == constants::HEADER_2);
        let header_len = 2 + transport_id.map_or(0, |id| id.len()) + destination_hash.len() + 1;
        let len = header_len + payload_len;
        if len > max_mtu {
            return Err(PacketError::ExceedsMtu);
        }
        let mut shared = Arc::<[u8]>::new_uninit_slice(len);
        let out = Arc::get_mut(&mut shared).expect("a new Arc is unique");
        // SAFETY: `out` is `len` writable bytes; zeroing initialises them all,
        // and u8 and MaybeUninit<u8> share a layout.
        let out: &mut [u8] = unsafe {
            core::ptr::write_bytes(out.as_mut_ptr(), 0, len);
            core::slice::from_raw_parts_mut(out.as_mut_ptr().cast::<u8>(), len)
        };
        out[0] = flags.pack();
        out[1] = hops;
        let mut at = 2;
        if let Some(transport_id) = transport_id {
            out[at..at + 16].copy_from_slice(transport_id);
            at += 16;
        }
        out[at..at + 16].copy_from_slice(destination_hash);
        at += 16;
        out[at] = context;
        fill(&mut out[header_len..]);
        // SAFETY: every byte was initialised by the zeroing above.
        Ok(unsafe { shared.assume_init() })
    }

    /// [`RawPacket::pack_raw_with_max_mtu`] into shared bytes, allocated once
    /// at their final size, for packets that are routed and sent as they are.
    pub fn pack_raw_shared_with_max_mtu(
        flags: PacketFlags,
        hops: u8,
        destination_hash: &[u8; 16],
        transport_id: Option<&[u8; 16]>,
        context: u8,
        data: &[u8],
        max_mtu: usize,
    ) -> Result<PacketBytes, PacketError> {
        if flags.header_type == constants::HEADER_2 && transport_id.is_none() {
            return Err(PacketError::MissingTransportId);
        }
        let transport_id = transport_id.filter(|_| flags.header_type == constants::HEADER_2);
        let len =
            2 + transport_id.map_or(0, |id| id.len()) + destination_hash.len() + 1 + data.len();
        if len > max_mtu {
            return Err(PacketError::ExceedsMtu);
        }
        let mut shared = Arc::<[u8]>::new_uninit_slice(len);
        let out = Arc::get_mut(&mut shared).expect("a new Arc is unique");
        let mut at = 0;
        let mut put = |bytes: &[u8]| {
            let slots = &mut out[at..at + bytes.len()];
            // SAFETY: `slots` is in bounds and exactly `bytes.len()` long; u8
            // and MaybeUninit<u8> share a layout.
            unsafe {
                core::ptr::copy_nonoverlapping(
                    bytes.as_ptr(),
                    slots.as_mut_ptr().cast::<u8>(),
                    bytes.len(),
                )
            };
            at += bytes.len();
        };
        put(&[flags.pack(), hops]);
        if let Some(transport_id) = transport_id {
            put(transport_id);
        }
        put(destination_hash);
        put(&[context]);
        put(data);
        assert_eq!(at, len);
        // SAFETY: every one of the `len` bytes was written above.
        Ok(unsafe { shared.assume_init() })
    }

    pub fn pack_raw_with_max_mtu(
        flags: PacketFlags,
        hops: u8,
        destination_hash: &[u8; 16],
        transport_id: Option<&[u8; 16]>,
        context: u8,
        data: &[u8],
        max_mtu: usize,
    ) -> Result<Vec<u8>, PacketError> {
        if flags.header_type == constants::HEADER_2 && transport_id.is_none() {
            return Err(PacketError::MissingTransportId);
        }

        let transport_id = transport_id.filter(|_| flags.header_type == constants::HEADER_2);
        // flags, hops, [transport id], destination hash, context, data
        let len =
            2 + transport_id.map_or(0, |id| id.len()) + destination_hash.len() + 1 + data.len();
        if len > max_mtu {
            return Err(PacketError::ExceedsMtu);
        }

        // Sized once: growing from empty cost an allocation and several
        // reallocations per packet.
        let mut raw = Vec::with_capacity(len);
        raw.push(flags.pack());
        raw.push(hops);
        if let Some(transport_id) = transport_id {
            raw.extend_from_slice(transport_id);
        }
        raw.extend_from_slice(destination_hash);
        raw.push(context);
        raw.extend_from_slice(data);
        debug_assert_eq!(raw.len(), len);

        Ok(raw)
    }

    /// Unpack raw bytes into fields.
    pub fn unpack(raw: &[u8]) -> Result<Self, PacketError> {
        RawPacket::<&[u8]>::parse::<true>(raw).map(|packet| packet.map_raw(<[u8]>::to_vec))
    }

    /// Unpack wire bytes the caller owns, keeping them as `raw` instead of
    /// copying them.
    pub fn unpack_owned(raw: Vec<u8>) -> Result<Self, PacketError> {
        Self::parse::<true>(raw)
    }

    /// Unpack owned wire bytes into fields, leaving `packet_hash` zeroed.
    /// Callers must hash the packet with [`RawPacket::hash_in_place`] before
    /// anything reads `packet_hash`.
    pub(crate) fn unpack_unhashed(raw: Vec<u8>) -> Result<Self, PacketError> {
        Self::parse::<false>(raw)
    }

    /// Unpack owned wire bytes of a packet this node sends. A link resource
    /// part, part request or proof is left unhashed, its `packet_hash`
    /// zeroed, because nothing reads it (see
    /// [`RawPacket::is_unhashed_link_resource`]).
    pub fn unpack_outbound(raw: Vec<u8>) -> Result<Self, PacketError> {
        let mut packet = Self::unpack_unhashed(raw)?;
        if !packet.is_unhashed_link_resource() {
            packet.hash_in_place();
        }
        Ok(packet)
    }

    /// [`RawPacket::unpack_owned`] for shared bytes, kept as they are.
    pub fn unpack_shared(raw: PacketBytes) -> Result<RawPacket<PacketBytes>, PacketError> {
        RawPacket::<PacketBytes>::parse::<true>(raw)
    }

    /// [`RawPacket::unpack`] for shared bytes, leaving `packet_hash` zeroed
    /// (see [`RawPacket::unpack_unhashed`]).
    pub(crate) fn unpack_shared_unhashed(
        raw: PacketBytes,
    ) -> Result<RawPacket<PacketBytes>, PacketError> {
        RawPacket::<PacketBytes>::parse::<false>(raw)
    }

    /// [`RawPacket::unpack_outbound`] for shared bytes, kept as they are.
    pub fn unpack_outbound_shared(raw: PacketBytes) -> Result<RawPacket<PacketBytes>, PacketError> {
        let mut packet = RawPacket::<PacketBytes>::parse::<false>(raw)?;
        if !packet.is_unhashed_link_resource() {
            packet.hash_in_place();
        }
        Ok(packet)
    }

    /// Unpack wire bytes whose packet hash the caller already computed from
    /// these exact bytes (for example a delivered packet's hash), instead of
    /// hashing them again. The hash is trusted, not checked.
    pub fn unpack_prehashed(raw: &[u8], packet_hash: [u8; 32]) -> Result<Self, PacketError> {
        RawPacket::view_prehashed(raw, packet_hash).map(|packet| packet.map_raw(<[u8]>::to_vec))
    }

    fn hashable_tail(header_type: u8, raw: &[u8]) -> &[u8] {
        if header_type == constants::HEADER_2 {
            // Skip transport_id: raw[2..18] is transport_id (16 bytes)
            &raw[(constants::TRUNCATED_HASHLENGTH / 8 + 2)..]
        } else {
            &raw[2..]
        }
    }

    fn compute_hashable_part(header_type: u8, raw: &[u8]) -> Vec<u8> {
        let tail = Self::hashable_tail(header_type, raw);
        let mut hashable = Vec::with_capacity(1 + tail.len());
        hashable.push(raw[0] & 0b00001111);
        hashable.extend_from_slice(tail);
        hashable
    }

    /// SHA-256 of the hashable part, fed from the wire bytes without building
    /// the concatenated buffer that [`RawPacket::get_hashable_part`] returns.
    fn compute_packet_hash(header_type: u8, raw: &[u8]) -> [u8; 32] {
        let mut hasher = rns_crypto::sha256::Sha256::new();
        hasher.update(&[raw[0] & 0b00001111]);
        hasher.update(Self::hashable_tail(header_type, raw));
        hasher.digest()
    }
}

impl<B: AsRef<[u8]>> RawPacket<B> {
    /// The payload: the wire bytes after the header.
    #[inline]
    pub fn data(&self) -> &[u8] {
        &self.raw.as_ref()[<RawPacket>::data_offset(self.flags.header_type)..]
    }

    /// Whether this packet is link resource traffic whose hash nothing
    /// reads: a part, a part request, or a resource proof. The packet filter
    /// admits these contexts before deduplication (`Transport.packet_filter`),
    /// no proof or receipt covers them, and their handlers read only the
    /// payload (the receiver locates a part by its map hash). Their hashes
    /// cannot mark any other packet as a duplicate either, since the context
    /// byte is hashed, so they are neither computed nor remembered.
    #[inline]
    pub fn is_unhashed_link_resource(&self) -> bool {
        <RawPacket>::is_unhashed_link_resource_header(&self.flags, self.context)
    }

    /// Whether a link peer never proves this packet: link data in a context
    /// with its own protocol handling (requests and responses, resource
    /// control and parts, keepalives, identification, RTT and close). Only
    /// plain link data and channel messages are proven, so a sent packet in
    /// one of these contexts has no receipt to wait for.
    pub fn is_unproven_link_data(&self) -> bool {
        self.flags.packet_type == constants::PACKET_TYPE_DATA
            && self.flags.destination_type == constants::DESTINATION_LINK
            && matches!(
                self.context,
                constants::CONTEXT_REQUEST
                    | constants::CONTEXT_RESPONSE
                    | constants::CONTEXT_RESOURCE
                    | constants::CONTEXT_RESOURCE_ADV
                    | constants::CONTEXT_RESOURCE_REQ
                    | constants::CONTEXT_RESOURCE_HMU
                    | constants::CONTEXT_RESOURCE_ICL
                    | constants::CONTEXT_RESOURCE_RCL
                    | constants::CONTEXT_KEEPALIVE
                    | constants::CONTEXT_LINKIDENTIFY
                    | constants::CONTEXT_LRRTT
                    | constants::CONTEXT_LINKCLOSE
            )
    }

    /// Get the hashable part of the packet.
    ///
    /// From Python Packet.py:354-361:
    /// - Take raw[0] & 0x0F (mask out upper 4 bits of flags)
    /// - For HEADER_1: append raw[2:]
    /// - For HEADER_2: skip transport_id: append raw[18:]
    pub fn get_hashable_part(&self) -> Vec<u8> {
        <RawPacket>::compute_hashable_part(self.flags.header_type, self.raw.as_ref())
    }

    /// Compute `packet_hash` from the packet's wire bytes.
    pub(crate) fn hash_in_place(&mut self) {
        self.packet_hash =
            <RawPacket>::compute_packet_hash(self.flags.header_type, self.raw.as_ref());
    }

    /// Full SHA-256 hash of the hashable part.
    pub fn get_hash(&self) -> [u8; 32] {
        self.packet_hash
    }

    /// Truncated hash (first 16 bytes) of the cached packet hash.
    ///
    /// Packet construction and unpacking compute `packet_hash` once; routing
    /// paths use this prefix instead of hashing the raw packet again.
    pub fn get_truncated_hash(&self) -> [u8; 16] {
        let mut result = [0u8; 16];
        result.copy_from_slice(&self.packet_hash[..16]);
        result
    }
    /// A view of this packet borrowing its bytes.
    pub fn as_view(&self) -> RawPacket<&[u8]> {
        RawPacket {
            flags: self.flags,
            hops: self.hops,
            transport_id: self.transport_id,
            destination_hash: self.destination_hash,
            context: self.context,
            raw: self.raw.as_ref(),
            packet_hash: self.packet_hash,
            rssi: self.rssi,
            snr: self.snr,
        }
    }

    /// This packet with its bytes copied into an owned buffer.
    pub fn to_owned_packet(&self) -> RawPacket {
        self.as_view().map_raw(<[u8]>::to_vec)
    }

    /// This packet with its bytes converted by `f`, fields unchanged.
    pub fn map_raw<C>(self, f: impl FnOnce(B) -> C) -> RawPacket<C> {
        RawPacket {
            flags: self.flags,
            hops: self.hops,
            transport_id: self.transport_id,
            destination_hash: self.destination_hash,
            context: self.context,
            raw: f(self.raw),
            packet_hash: self.packet_hash,
            rssi: self.rssi,
            snr: self.snr,
        }
    }

    /// Parse `input`, keeping it as `raw`.
    fn parse<const HASH: bool>(input: B) -> Result<Self, PacketError> {
        let raw = input.as_ref();
        if raw.len() < constants::HEADER_MINSIZE {
            return Err(PacketError::TooShort);
        }

        let flags = PacketFlags::unpack(raw[0]);
        let hops = raw[1];
        if hops >= constants::PATHFINDER_M {
            return Err(PacketError::InvalidHopCount(hops));
        }

        let dst_len = constants::TRUNCATED_HASHLENGTH / 8; // 16

        if flags.header_type == constants::HEADER_2 {
            // HEADER_2: [flags:1][hops:1][transport_id:16][dest_hash:16][context:1][data:*]
            let min_len = 2 + dst_len * 2 + 1;
            if raw.len() < min_len {
                return Err(PacketError::TooShort);
            }

            let mut transport_id = [0u8; 16];
            transport_id.copy_from_slice(&raw[2..2 + dst_len]);

            let mut destination_hash = [0u8; 16];
            destination_hash.copy_from_slice(&raw[2 + dst_len..2 + 2 * dst_len]);

            let context = raw[2 + 2 * dst_len];
            if raw.len() == 2 + 2 * dst_len + 1 {
                return Err(PacketError::ZeroLengthData);
            }

            let packet_hash = if HASH {
                <RawPacket>::compute_packet_hash(flags.header_type, raw)
            } else {
                [0; 32]
            };

            Ok(RawPacket {
                flags,
                hops,
                transport_id: Some(transport_id),
                destination_hash,
                context,
                raw: input,
                packet_hash,
                rssi: None,
                snr: None,
            })
        } else if flags.header_type == constants::HEADER_1 {
            // HEADER_1: [flags:1][hops:1][dest_hash:16][context:1][data:*]
            let min_len = 2 + dst_len + 1;
            if raw.len() < min_len {
                return Err(PacketError::TooShort);
            }

            let mut destination_hash = [0u8; 16];
            destination_hash.copy_from_slice(&raw[2..2 + dst_len]);

            let context = raw[2 + dst_len];
            if raw.len() == 2 + dst_len + 1 {
                return Err(PacketError::ZeroLengthData);
            }

            let packet_hash = if HASH {
                <RawPacket>::compute_packet_hash(flags.header_type, raw)
            } else {
                [0; 32]
            };

            Ok(RawPacket {
                flags,
                hops,
                transport_id: None,
                destination_hash,
                context,
                raw: input,
                packet_hash,
                rssi: None,
                snr: None,
            })
        } else {
            Err(PacketError::InvalidHeaderType)
        }
    }
}

impl<'a> RawPacket<&'a [u8]> {
    /// [`RawPacket::unpack_prehashed`] as a view of `raw`, without copying it.
    pub fn view_prehashed(raw: &'a [u8], packet_hash: [u8; 32]) -> Result<Self, PacketError> {
        let mut packet = Self::parse::<false>(raw)?;
        packet.packet_hash = packet_hash;
        Ok(packet)
    }
}

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

    #[test]
    fn unpack_prehashed_matches_unpack_but_keeps_the_given_hash() {
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_LINK,
            packet_type: constants::PACKET_TYPE_DATA,
        };
        let packet = RawPacket::pack(
            flags,
            3,
            &[0x42; 16],
            None,
            constants::CONTEXT_RESOURCE,
            &[9; 300],
        )
        .unwrap();
        let full = RawPacket::unpack(&packet.raw).unwrap();
        let known = RawPacket::unpack_prehashed(&packet.raw, full.packet_hash).unwrap();
        assert_eq!(known.raw, full.raw);
        assert_eq!(known.packet_hash, full.packet_hash);
        assert_eq!(known.destination_hash, full.destination_hash);
        assert_eq!((known.hops, known.context), (full.hops, full.context));
        assert_eq!(known.data(), full.data());
        // The hash is trusted, not recomputed.
        let other = RawPacket::unpack_prehashed(&packet.raw, [7; 32]).unwrap();
        assert_eq!(other.packet_hash, [7; 32]);
        // Structural errors are the same.
        assert_eq!(
            format!(
                "{:?}",
                RawPacket::unpack_prehashed(&packet.raw[..10], [0; 32]).unwrap_err()
            ),
            format!("{:?}", RawPacket::unpack(&packet.raw[..10]).unwrap_err())
        );
    }

    #[test]
    fn only_link_resource_transfers_are_sent_unhashed() {
        let cases = [
            (
                constants::DESTINATION_LINK,
                constants::PACKET_TYPE_DATA,
                constants::CONTEXT_RESOURCE,
                true,
            ),
            (
                constants::DESTINATION_LINK,
                constants::PACKET_TYPE_DATA,
                constants::CONTEXT_CHANNEL,
                false,
            ),
            (
                constants::DESTINATION_LINK,
                constants::PACKET_TYPE_DATA,
                constants::CONTEXT_RESOURCE_REQ,
                true,
            ),
            (
                constants::DESTINATION_LINK,
                constants::PACKET_TYPE_PROOF,
                constants::CONTEXT_RESOURCE_PRF,
                true,
            ),
            (
                constants::DESTINATION_LINK,
                constants::PACKET_TYPE_DATA,
                constants::CONTEXT_RESOURCE_PRF,
                false,
            ),
            (
                constants::DESTINATION_LINK,
                constants::PACKET_TYPE_DATA,
                constants::CONTEXT_RESOURCE_HMU,
                false,
            ),
            (
                constants::DESTINATION_LINK,
                constants::PACKET_TYPE_PROOF,
                constants::CONTEXT_RESOURCE,
                false,
            ),
            (
                constants::DESTINATION_LINK,
                constants::PACKET_TYPE_PROOF,
                constants::CONTEXT_NONE,
                false,
            ),
            (
                constants::DESTINATION_SINGLE,
                constants::PACKET_TYPE_DATA,
                constants::CONTEXT_RESOURCE,
                false,
            ),
        ];
        for header_type in [constants::HEADER_1, constants::HEADER_2] {
            for (destination_type, packet_type, context, part) in cases {
                let flags = PacketFlags {
                    header_type,
                    context_flag: constants::FLAG_UNSET,
                    transport_type: constants::TRANSPORT_BROADCAST,
                    destination_type,
                    packet_type,
                };
                let transport_id = (header_type == constants::HEADER_2).then_some([0x11; 16]);
                let packet = RawPacket::pack(
                    flags,
                    0,
                    &[0x42; 16],
                    transport_id.as_ref(),
                    context,
                    &[9; 300],
                )
                .unwrap();
                assert_eq!(packet.is_unhashed_link_resource(), part);
                assert_eq!(RawPacket::is_unhashed_link_resource_wire(&packet.raw), part);
                let sent = RawPacket::unpack_outbound(packet.raw.clone()).unwrap();
                assert_eq!(sent.raw, packet.raw);
                let expected = if part { [0; 32] } else { packet.packet_hash };
                assert_eq!(sent.packet_hash, expected);
            }
        }
        // Bytes too short to carry a context byte are not a part.
        let part = RawPacket::pack(
            PacketFlags {
                header_type: constants::HEADER_1,
                context_flag: constants::FLAG_UNSET,
                transport_type: constants::TRANSPORT_BROADCAST,
                destination_type: constants::DESTINATION_LINK,
                packet_type: constants::PACKET_TYPE_DATA,
            },
            0,
            &[0x42; 16],
            None,
            constants::CONTEXT_RESOURCE,
            &[9; 4],
        )
        .unwrap();
        let context_at = RawPacket::data_offset(constants::HEADER_1) - 1;
        assert!(RawPacket::is_unhashed_link_resource_wire(
            &part.raw[..=context_at]
        ));
        assert!(!RawPacket::is_unhashed_link_resource_wire(
            &part.raw[..context_at]
        ));
        assert!(!RawPacket::is_unhashed_link_resource_wire(&[]));
    }

    #[test]
    fn only_plain_link_data_and_channel_messages_await_proofs() {
        let packet = |destination_type, packet_type, context| {
            RawPacket::pack(
                PacketFlags {
                    header_type: constants::HEADER_1,
                    context_flag: constants::FLAG_UNSET,
                    transport_type: constants::TRANSPORT_BROADCAST,
                    destination_type,
                    packet_type,
                },
                0,
                &[0x42; 16],
                None,
                context,
                b"payload",
            )
            .unwrap()
        };
        let link_data = |context| {
            packet(
                constants::DESTINATION_LINK,
                constants::PACKET_TYPE_DATA,
                context,
            )
        };
        for context in [constants::CONTEXT_NONE, constants::CONTEXT_CHANNEL] {
            assert!(
                !link_data(context).is_unproven_link_data(),
                "context {context}"
            );
        }
        for context in [
            constants::CONTEXT_REQUEST,
            constants::CONTEXT_RESPONSE,
            constants::CONTEXT_RESOURCE,
            constants::CONTEXT_RESOURCE_ADV,
            constants::CONTEXT_RESOURCE_REQ,
            constants::CONTEXT_RESOURCE_HMU,
            constants::CONTEXT_RESOURCE_ICL,
            constants::CONTEXT_RESOURCE_RCL,
            constants::CONTEXT_KEEPALIVE,
            constants::CONTEXT_LINKIDENTIFY,
            constants::CONTEXT_LRRTT,
            constants::CONTEXT_LINKCLOSE,
        ] {
            assert!(
                link_data(context).is_unproven_link_data(),
                "context {context}"
            );
        }
        // Only link data qualifies.
        let request = constants::CONTEXT_REQUEST;
        assert!(!packet(
            constants::DESTINATION_SINGLE,
            constants::PACKET_TYPE_DATA,
            request
        )
        .is_unproven_link_data());
        assert!(!packet(
            constants::DESTINATION_LINK,
            constants::PACKET_TYPE_PROOF,
            request
        )
        .is_unproven_link_data());
    }

    #[test]
    fn shared_packing_matches_owned_packing_and_unpacks_alike() {
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_LINK,
            packet_type: constants::PACKET_TYPE_DATA,
        };
        let header2 = PacketFlags {
            header_type: constants::HEADER_2,
            ..flags
        };
        let dest = [0x11; 16];
        let tid = [0x22; 16];
        for (flags, tid) in [(flags, None), (flags, Some(&tid)), (header2, Some(&tid))] {
            for len in [1usize, 2, 15, 16, 400, 465] {
                let data: Vec<u8> = (0..len).map(|i| i as u8).collect();
                for mtu in [len + 18, len + 35, 500] {
                    let owned =
                        RawPacket::pack_raw_with_max_mtu(flags, 3, &dest, tid, 0x07, &data, mtu);
                    let shared = RawPacket::pack_raw_shared_with_max_mtu(
                        flags, 3, &dest, tid, 0x07, &data, mtu,
                    );
                    let filled = RawPacket::pack_raw_shared_filled_with_max_mtu(
                        flags,
                        3,
                        &dest,
                        tid,
                        0x07,
                        data.len(),
                        mtu,
                        |payload| payload.copy_from_slice(&data),
                    );
                    assert_eq!(format!("{shared:?}"), format!("{filled:?}"));
                    match (owned, shared) {
                        (Ok(owned), Ok(shared)) => {
                            assert_eq!(&owned[..], &shared[..]);
                            let a = RawPacket::unpack_outbound(owned).unwrap();
                            let b = RawPacket::unpack_outbound_shared(shared).unwrap();
                            assert_eq!(a.packet_hash, b.packet_hash);
                            assert_eq!(a.data(), b.data());
                        }
                        (Err(PacketError::ExceedsMtu), Err(PacketError::ExceedsMtu)) => {}
                        other => panic!("diverged: {other:?}"),
                    }
                }
            }
        }
        assert!(matches!(
            RawPacket::pack_raw_shared_with_max_mtu(header2, 0, &dest, None, 0, &[1], 500),
            Err(PacketError::MissingTransportId)
        ));
        assert!(matches!(
            RawPacket::pack_raw_shared_filled_with_max_mtu(
                header2,
                0,
                &dest,
                None,
                0,
                1,
                500,
                |_| {}
            ),
            Err(PacketError::MissingTransportId)
        ));
    }

    #[test]
    fn raw_only_packing_preserves_wire_layout_and_limits() {
        for header in [constants::HEADER_1, constants::HEADER_2] {
            for transport in [None, Some([0xBB; 16])] {
                for len in [0, 1, 464, 16348] {
                    let flags = PacketFlags {
                        header_type: header,
                        context_flag: constants::FLAG_UNSET,
                        transport_type: constants::TRANSPORT_BROADCAST,
                        destination_type: constants::DESTINATION_LINK,
                        packet_type: constants::PACKET_TYPE_DATA,
                    };
                    let data = vec![0xCC; len];
                    let mut expected = vec![flags.pack(), 7];
                    if header == constants::HEADER_2 {
                        expected.extend_from_slice(&[0xBB; 16]);
                    }
                    expected.extend_from_slice(&[0xAA; 16]);
                    expected.push(constants::CONTEXT_RESOURCE);
                    expected.extend_from_slice(&data);
                    for limit in [0, expected.len() - 1, expected.len(), expected.len() + 1] {
                        let result = RawPacket::pack_raw_with_max_mtu(
                            flags,
                            7,
                            &[0xAA; 16],
                            transport.as_ref(),
                            constants::CONTEXT_RESOURCE,
                            &data,
                            limit,
                        );
                        if header == constants::HEADER_2 && transport.is_none() {
                            assert!(matches!(result, Err(PacketError::MissingTransportId)));
                        } else if limit < expected.len() {
                            assert!(matches!(result, Err(PacketError::ExceedsMtu)));
                        } else {
                            assert_eq!(result.unwrap(), expected);
                            let (raw, hash) = RawPacket::pack_raw_with_hash_with_max_mtu(
                                flags,
                                7,
                                &[0xAA; 16],
                                transport.as_ref(),
                                constants::CONTEXT_RESOURCE,
                                &data,
                                limit,
                            )
                            .unwrap();
                            assert_eq!(raw, expected);
                            if len == 0 {
                                assert!(matches!(
                                    RawPacket::unpack(&raw),
                                    Err(PacketError::ZeroLengthData)
                                ));
                            } else {
                                assert_eq!(RawPacket::unpack(&raw).unwrap().packet_hash, hash);
                            }
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn test_flags_pack_header1_data_single_broadcast() {
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_DATA,
        };
        assert_eq!(flags.pack(), 0x00);
    }

    #[test]
    fn test_flags_pack_header2_announce_single_transport() {
        let flags = PacketFlags {
            header_type: constants::HEADER_2,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_TRANSPORT,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_ANNOUNCE,
        };
        // 0b01010001 = 0x51
        assert_eq!(flags.pack(), 0x51);
    }

    #[test]
    fn test_flags_roundtrip() {
        for byte in 0..=0x7Fu8 {
            let flags = PacketFlags::unpack(byte);
            assert_eq!(flags.pack(), byte);
        }
    }

    #[test]
    fn test_pack_header1() {
        let dest_hash = [0xAA; 16];
        let data = b"hello";
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_DATA,
        };

        let pkt =
            RawPacket::pack(flags, 0, &dest_hash, None, constants::CONTEXT_NONE, data).unwrap();

        // Verify layout: [flags:1][hops:1][dest:16][context:1][data:5] = 24 bytes
        assert_eq!(pkt.raw.len(), 24);
        assert_eq!(pkt.raw[0], 0x00); // flags
        assert_eq!(pkt.raw[1], 0x00); // hops
        assert_eq!(&pkt.raw[2..18], &dest_hash); // dest hash
        assert_eq!(pkt.raw[18], 0x00); // context
        assert_eq!(&pkt.raw[19..], b"hello"); // data
    }

    #[test]
    fn test_pack_header2() {
        let dest_hash = [0xAA; 16];
        let transport_id = [0xBB; 16];
        let data = b"world";
        let flags = PacketFlags {
            header_type: constants::HEADER_2,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_TRANSPORT,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_ANNOUNCE,
        };

        let pkt = RawPacket::pack(
            flags,
            3,
            &dest_hash,
            Some(&transport_id),
            constants::CONTEXT_NONE,
            data,
        )
        .unwrap();

        // Layout: [flags:1][hops:1][transport:16][dest:16][context:1][data:5] = 40 bytes
        assert_eq!(pkt.raw.len(), 40);
        assert_eq!(pkt.raw[0], flags.pack());
        assert_eq!(pkt.raw[1], 3);
        assert_eq!(&pkt.raw[2..18], &transport_id);
        assert_eq!(&pkt.raw[18..34], &dest_hash);
        assert_eq!(pkt.raw[34], 0x00);
        assert_eq!(&pkt.raw[35..], b"world");
    }

    #[test]
    fn test_unpack_roundtrip_header1() {
        let dest_hash = [0x11; 16];
        let data = b"test data";
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_DATA,
        };

        let pkt = RawPacket::pack(
            flags,
            5,
            &dest_hash,
            None,
            constants::CONTEXT_RESOURCE,
            data,
        )
        .unwrap();
        let unpacked = RawPacket::unpack(&pkt.raw).unwrap();

        assert_eq!(unpacked.flags, flags);
        assert_eq!(unpacked.hops, 5);
        assert!(unpacked.transport_id.is_none());
        assert_eq!(unpacked.destination_hash, dest_hash);
        assert_eq!(unpacked.context, constants::CONTEXT_RESOURCE);
        assert_eq!(unpacked.data(), data);
        assert_eq!(unpacked.packet_hash, pkt.packet_hash);
    }

    #[test]
    fn test_unpack_roundtrip_header2() {
        let dest_hash = [0x22; 16];
        let transport_id = [0x33; 16];
        let data = b"transported";
        let flags = PacketFlags {
            header_type: constants::HEADER_2,
            context_flag: constants::FLAG_SET,
            transport_type: constants::TRANSPORT_TRANSPORT,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_ANNOUNCE,
        };

        let pkt = RawPacket::pack(
            flags,
            2,
            &dest_hash,
            Some(&transport_id),
            constants::CONTEXT_NONE,
            data,
        )
        .unwrap();
        let unpacked = RawPacket::unpack(&pkt.raw).unwrap();

        assert_eq!(unpacked.flags, flags);
        assert_eq!(unpacked.hops, 2);
        assert_eq!(unpacked.transport_id.unwrap(), transport_id);
        assert_eq!(unpacked.destination_hash, dest_hash);
        assert_eq!(unpacked.context, constants::CONTEXT_NONE);
        assert_eq!(unpacked.data(), data);
        assert_eq!(unpacked.packet_hash, pkt.packet_hash);
    }

    #[test]
    fn truncated_hash_is_derived_from_cached_packet_hash() {
        let mut packet = RawPacket::pack(
            PacketFlags {
                header_type: constants::HEADER_1,
                context_flag: constants::FLAG_UNSET,
                transport_type: constants::TRANSPORT_BROADCAST,
                destination_type: constants::DESTINATION_SINGLE,
                packet_type: constants::PACKET_TYPE_DATA,
            },
            1,
            &[0x42; 16],
            None,
            constants::CONTEXT_NONE,
            b"cached hash",
        )
        .unwrap();
        let expected: [u8; 16] = packet.packet_hash[..16].try_into().unwrap();

        // Changing the retained wire buffer demonstrates that this accessor is
        // a prefix operation, not a second hash computation.
        let last = packet.raw.len() - 1;
        packet.raw[last] ^= 0xff;

        assert_eq!(packet.get_truncated_hash(), expected);
    }

    #[test]
    fn test_unpack_too_short() {
        assert!(RawPacket::unpack(&[0x00; 5]).is_err());
    }

    #[test]
    fn unpack_rejects_zero_length_data_for_both_header_types() {
        for header_type in [constants::HEADER_1, constants::HEADER_2] {
            let packet = RawPacket::pack(
                PacketFlags {
                    header_type,
                    context_flag: constants::FLAG_UNSET,
                    transport_type: constants::TRANSPORT_BROADCAST,
                    destination_type: constants::DESTINATION_SINGLE,
                    packet_type: constants::PACKET_TYPE_DATA,
                },
                0,
                &[0x42; 16],
                (header_type == constants::HEADER_2).then_some(&[0x24; 16]),
                constants::CONTEXT_NONE,
                b"",
            )
            .unwrap();
            assert!(matches!(
                RawPacket::unpack(&packet.raw),
                Err(PacketError::ZeroLengthData)
            ));
        }
    }

    #[test]
    fn unpack_enforces_pathfinder_hop_boundary_but_pack_remains_permissive() {
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_DATA,
        };
        let accepted = RawPacket::pack(flags, 127, &[1; 16], None, 0, b"x").unwrap();
        assert_eq!(RawPacket::unpack(&accepted.raw).unwrap().hops, 127);

        for hops in [128, 255] {
            let packed = RawPacket::pack(flags, hops, &[1; 16], None, 0, b"x").unwrap();
            assert!(matches!(
                RawPacket::unpack(&packed.raw),
                Err(PacketError::InvalidHopCount(value)) if value == hops
            ));
        }
    }

    #[test]
    fn test_pack_exceeds_mtu() {
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_DATA,
        };
        let data = [0u8; 500]; // way too much data
        let result = RawPacket::pack(flags, 0, &[0; 16], None, 0, &data);
        assert!(result.is_err());
    }

    #[test]
    fn test_header2_missing_transport_id() {
        let flags = PacketFlags {
            header_type: constants::HEADER_2,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_TRANSPORT,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_ANNOUNCE,
        };
        let result = RawPacket::pack(flags, 0, &[0; 16], None, 0, b"data");
        assert!(result.is_err());
    }

    #[test]
    fn test_hashable_part_header1_masks_upper_flags() {
        let dest_hash = [0xCC; 16];
        let flags = PacketFlags {
            header_type: constants::HEADER_1,
            context_flag: constants::FLAG_SET,
            transport_type: constants::TRANSPORT_BROADCAST,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_DATA,
        };

        let pkt =
            RawPacket::pack(flags, 0, &dest_hash, None, constants::CONTEXT_NONE, b"test").unwrap();
        let hashable = pkt.get_hashable_part();

        // First byte should have upper 4 bits masked out
        assert_eq!(hashable[0], pkt.raw[0] & 0x0F);
        // Rest should be raw[2:]
        assert_eq!(&hashable[1..], &pkt.raw[2..]);
    }

    #[test]
    fn test_hashable_part_header2_strips_transport_id() {
        let dest_hash = [0xDD; 16];
        let transport_id = [0xEE; 16];
        let flags = PacketFlags {
            header_type: constants::HEADER_2,
            context_flag: constants::FLAG_UNSET,
            transport_type: constants::TRANSPORT_TRANSPORT,
            destination_type: constants::DESTINATION_SINGLE,
            packet_type: constants::PACKET_TYPE_ANNOUNCE,
        };

        let pkt = RawPacket::pack(
            flags,
            0,
            &dest_hash,
            Some(&transport_id),
            constants::CONTEXT_NONE,
            b"data",
        )
        .unwrap();
        let hashable = pkt.get_hashable_part();

        // First byte: flags masked
        assert_eq!(hashable[0], pkt.raw[0] & 0x0F);
        // Should skip transport_id: raw[18:] = dest_hash + context + data
        assert_eq!(&hashable[1..], &pkt.raw[18..]);
    }
}