irontide-wire 1.0.1

BitTorrent peer wire protocol: messages, handshake, extensions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    reason = "M175: BitTorrent wire format — message field widths fixed by BEP 3/6/10 spec (u32 piece indices, u32 chunk lengths)"
)]

use bytes::{BufMut, Bytes, BytesMut};

use crate::error::{Error, Result};

/// Standard `BitTorrent` peer wire messages (BEP 3).
///
/// Generic over buffer type `B` to support both owned (`Bytes`) and borrowed
/// (`&[u8]`) payloads.  Data-carrying variants (`Piece`, `Bitfield`,
/// `Extended`) use `B`; fixed-field variants are buffer-agnostic.
///
/// The `Piece` variant carries two buffer fields (`data_0`, `data_1`) to
/// support ring-buffer wrap-around: when a block spans the ring boundary the
/// two non-contiguous slices are stored separately. In the common (no-wrap)
/// case `data_1` is empty.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Message<B = Bytes> {
    /// Keep connection alive (no payload, length=0).
    KeepAlive,
    /// Peer is choking us.
    Choke,
    /// Peer is unchoking us.
    Unchoke,
    /// We're interested in the peer's data.
    Interested,
    /// We're not interested.
    NotInterested,
    /// Peer has piece `index`.
    Have {
        /// Piece index.
        index: u32,
    },
    /// Peer's complete bitfield.
    Bitfield(B),
    /// Request a block: piece index, byte offset within piece, length.
    Request {
        /// Piece index.
        index: u32,
        /// Byte offset within the piece.
        begin: u32,
        /// Requested block length in bytes.
        length: u32,
    },
    /// A data block: piece index, byte offset, data.
    ///
    /// Two buffer fields support ring-buffer wrap-around.  When the block does
    /// not straddle the ring boundary, `data_1` is empty.
    Piece {
        /// Piece index.
        index: u32,
        /// Byte offset within the piece.
        begin: u32,
        /// First (or only) contiguous slice of block payload.
        data_0: B,
        /// Second contiguous slice when the ring buffer wraps; empty otherwise.
        data_1: B,
    },
    /// Cancel a previously sent request.
    Cancel {
        /// Piece index.
        index: u32,
        /// Byte offset within the piece.
        begin: u32,
        /// Block length in bytes.
        length: u32,
    },
    /// DHT port (BEP 5).
    Port(u16),
    /// Extension message (BEP 10). `ext_id=0` is handshake.
    Extended {
        /// Extension message ID (0 = handshake).
        ext_id: u8,
        /// Bencoded extension payload.
        payload: B,
    },
    /// BEP 6: Suggest a piece for the peer to download.
    SuggestPiece(u32),
    /// BEP 6: We have all pieces.
    HaveAll,
    /// BEP 6: We have no pieces.
    HaveNone,
    /// BEP 6: Reject a request from the peer.
    RejectRequest {
        /// Piece index.
        index: u32,
        /// Byte offset within the piece.
        begin: u32,
        /// Block length in bytes.
        length: u32,
    },
    /// BEP 6: Piece index the peer is allowed to request while choked.
    AllowedFast(u32),
    /// BEP 52: Request hashes from a file's Merkle tree.
    HashRequest {
        /// File root hash identifying the Merkle tree.
        pieces_root: irontide_core::Id32,
        /// Tree layer (0 = leaf/block layer).
        base: u32,
        /// Starting node index within the layer.
        index: u32,
        /// Number of consecutive hashes requested.
        count: u32,
        /// Number of uncle proof layers to include.
        proof_layers: u32,
    },
    /// BEP 52: Response with hashes and uncle proof.
    Hashes {
        /// File root hash identifying the Merkle tree.
        pieces_root: irontide_core::Id32,
        /// Tree layer (0 = leaf/block layer).
        base: u32,
        /// Starting node index within the layer.
        index: u32,
        /// Number of consecutive hashes in the response.
        count: u32,
        /// Number of uncle proof layers included.
        proof_layers: u32,
        /// Hash values followed by uncle proof hashes.
        hashes: Vec<irontide_core::Id32>,
    },
    /// BEP 52: Reject a hash request.
    HashReject {
        /// File root hash identifying the Merkle tree.
        pieces_root: irontide_core::Id32,
        /// Tree layer that was requested.
        base: u32,
        /// Starting node index that was requested.
        index: u32,
        /// Number of hashes that was requested.
        count: u32,
        /// Number of proof layers that was requested.
        proof_layers: u32,
    },
}

// Message IDs per BEP 3
const ID_CHOKE: u8 = 0;
const ID_UNCHOKE: u8 = 1;
const ID_INTERESTED: u8 = 2;
const ID_NOT_INTERESTED: u8 = 3;
const ID_HAVE: u8 = 4;
const ID_BITFIELD: u8 = 5;
const ID_REQUEST: u8 = 6;
const ID_PIECE: u8 = 7;
const ID_CANCEL: u8 = 8;
const ID_PORT: u8 = 9;
const ID_EXTENDED: u8 = 20;

// BEP 6 Fast Extension
const ID_SUGGEST_PIECE: u8 = 0x0D;
const ID_HAVE_ALL: u8 = 0x0E;
const ID_HAVE_NONE: u8 = 0x0F;
const ID_REJECT_REQUEST: u8 = 0x10;
const ID_ALLOWED_FAST: u8 = 0x11;

// BEP 52 Hash Messages
const ID_HASH_REQUEST: u8 = 21;
const ID_HASHES: u8 = 22;
const ID_HASH_REJECT: u8 = 23;

impl<B: AsRef<[u8]>> Message<B> {
    /// Serialize a message to bytes (length-prefix + id + payload).
    ///
    /// The returned bytes include the 4-byte length prefix.
    pub fn to_bytes(&self) -> Bytes {
        match self {
            Self::KeepAlive => {
                let mut buf = BytesMut::with_capacity(4);
                buf.put_u32(0);
                buf.freeze()
            }
            Self::Choke => fixed_msg(ID_CHOKE),
            Self::Unchoke => fixed_msg(ID_UNCHOKE),
            Self::Interested => fixed_msg(ID_INTERESTED),
            Self::NotInterested => fixed_msg(ID_NOT_INTERESTED),
            Self::Have { index } => {
                let mut buf = BytesMut::with_capacity(9);
                buf.put_u32(5);
                buf.put_u8(ID_HAVE);
                buf.put_u32(*index);
                buf.freeze()
            }
            Self::Bitfield(bits) => {
                let bits = bits.as_ref();
                let mut buf = BytesMut::with_capacity(5 + bits.len());
                buf.put_u32(1 + bits.len() as u32);
                buf.put_u8(ID_BITFIELD);
                buf.put_slice(bits);
                buf.freeze()
            }
            Self::Request {
                index,
                begin,
                length,
            } => triple_msg(ID_REQUEST, *index, *begin, *length),
            Self::Piece {
                index,
                begin,
                data_0,
                data_1,
            } => {
                let d0 = data_0.as_ref();
                let d1 = data_1.as_ref();
                let data_len = d0.len() + d1.len();
                let mut buf = BytesMut::with_capacity(13 + data_len);
                buf.put_u32(9 + data_len as u32);
                buf.put_u8(ID_PIECE);
                buf.put_u32(*index);
                buf.put_u32(*begin);
                buf.put_slice(d0);
                buf.put_slice(d1);
                buf.freeze()
            }
            Self::Cancel {
                index,
                begin,
                length,
            } => triple_msg(ID_CANCEL, *index, *begin, *length),
            Self::Port(port) => {
                let mut buf = BytesMut::with_capacity(7);
                buf.put_u32(3);
                buf.put_u8(ID_PORT);
                buf.put_u16(*port);
                buf.freeze()
            }
            Self::Extended { ext_id, payload } => {
                let payload = payload.as_ref();
                let mut buf = BytesMut::with_capacity(6 + payload.len());
                buf.put_u32(2 + payload.len() as u32);
                buf.put_u8(ID_EXTENDED);
                buf.put_u8(*ext_id);
                buf.put_slice(payload);
                buf.freeze()
            }
            Self::SuggestPiece(index) => {
                let mut buf = BytesMut::with_capacity(9);
                buf.put_u32(5);
                buf.put_u8(ID_SUGGEST_PIECE);
                buf.put_u32(*index);
                buf.freeze()
            }
            Self::HaveAll => fixed_msg(ID_HAVE_ALL),
            Self::HaveNone => fixed_msg(ID_HAVE_NONE),
            Self::RejectRequest {
                index,
                begin,
                length,
            } => triple_msg(ID_REJECT_REQUEST, *index, *begin, *length),
            Self::AllowedFast(index) => {
                let mut buf = BytesMut::with_capacity(9);
                buf.put_u32(5);
                buf.put_u8(ID_ALLOWED_FAST);
                buf.put_u32(*index);
                buf.freeze()
            }
            Self::HashRequest {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
            }
            | Self::HashReject {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
            } => {
                let id = match self {
                    Self::HashRequest { .. } => ID_HASH_REQUEST,
                    _ => ID_HASH_REJECT,
                };
                let mut buf = BytesMut::with_capacity(53);
                buf.put_u32(49); // 1 + 32 + 4*4
                buf.put_u8(id);
                buf.put_slice(&pieces_root.0);
                buf.put_u32(*base);
                buf.put_u32(*index);
                buf.put_u32(*count);
                buf.put_u32(*proof_layers);
                buf.freeze()
            }
            Self::Hashes {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
                hashes,
            } => {
                let hash_bytes = hashes.len() * 32;
                let payload_len = 1 + 32 + 16 + hash_bytes;
                let mut buf = BytesMut::with_capacity(4 + payload_len);
                buf.put_u32(payload_len as u32);
                buf.put_u8(ID_HASHES);
                buf.put_slice(&pieces_root.0);
                buf.put_u32(*base);
                buf.put_u32(*index);
                buf.put_u32(*count);
                buf.put_u32(*proof_layers);
                for h in hashes {
                    buf.put_slice(&h.0);
                }
                buf.freeze()
            }
        }
    }

    /// Encode this message (with length prefix) directly into a buffer.
    ///
    /// Unlike [`to_bytes`](Self::to_bytes), this writes directly into `dst`
    /// without allocating an intermediate `Bytes`, avoiding a double-copy
    /// when used with `tokio_util::codec::Encoder`.
    pub fn encode_into(&self, dst: &mut BytesMut) {
        match self {
            Self::KeepAlive => {
                dst.put_u32(0);
            }
            Self::Choke => encode_fixed_into(dst, ID_CHOKE),
            Self::Unchoke => encode_fixed_into(dst, ID_UNCHOKE),
            Self::Interested => encode_fixed_into(dst, ID_INTERESTED),
            Self::NotInterested => encode_fixed_into(dst, ID_NOT_INTERESTED),
            Self::Have { index } => {
                dst.put_u32(5);
                dst.put_u8(ID_HAVE);
                dst.put_u32(*index);
            }
            Self::Bitfield(bits) => {
                let bits = bits.as_ref();
                dst.reserve(5 + bits.len());
                dst.put_u32(1 + bits.len() as u32);
                dst.put_u8(ID_BITFIELD);
                dst.put_slice(bits);
            }
            Self::Request {
                index,
                begin,
                length,
            } => encode_triple_into(dst, ID_REQUEST, *index, *begin, *length),
            Self::Piece {
                index,
                begin,
                data_0,
                data_1,
            } => {
                let d0 = data_0.as_ref();
                let d1 = data_1.as_ref();
                let data_len = d0.len() + d1.len();
                dst.reserve(13 + data_len);
                dst.put_u32(9 + data_len as u32);
                dst.put_u8(ID_PIECE);
                dst.put_u32(*index);
                dst.put_u32(*begin);
                dst.put_slice(d0);
                dst.put_slice(d1);
            }
            Self::Cancel {
                index,
                begin,
                length,
            } => encode_triple_into(dst, ID_CANCEL, *index, *begin, *length),
            Self::Port(port) => {
                dst.put_u32(3);
                dst.put_u8(ID_PORT);
                dst.put_u16(*port);
            }
            Self::Extended { ext_id, payload } => {
                let payload = payload.as_ref();
                dst.reserve(6 + payload.len());
                dst.put_u32(2 + payload.len() as u32);
                dst.put_u8(ID_EXTENDED);
                dst.put_u8(*ext_id);
                dst.put_slice(payload);
            }
            Self::SuggestPiece(index) => {
                dst.put_u32(5);
                dst.put_u8(ID_SUGGEST_PIECE);
                dst.put_u32(*index);
            }
            Self::HaveAll => encode_fixed_into(dst, ID_HAVE_ALL),
            Self::HaveNone => encode_fixed_into(dst, ID_HAVE_NONE),
            Self::RejectRequest {
                index,
                begin,
                length,
            } => encode_triple_into(dst, ID_REJECT_REQUEST, *index, *begin, *length),
            Self::AllowedFast(index) => {
                dst.put_u32(5);
                dst.put_u8(ID_ALLOWED_FAST);
                dst.put_u32(*index);
            }
            Self::HashRequest {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
            }
            | Self::HashReject {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
            } => {
                let id = match self {
                    Self::HashRequest { .. } => ID_HASH_REQUEST,
                    _ => ID_HASH_REJECT,
                };
                dst.put_u32(49); // 1 + 32 + 4*4
                dst.put_u8(id);
                dst.put_slice(&pieces_root.0);
                dst.put_u32(*base);
                dst.put_u32(*index);
                dst.put_u32(*count);
                dst.put_u32(*proof_layers);
            }
            Self::Hashes {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
                hashes,
            } => {
                let hash_bytes = hashes.len() * 32;
                let payload_len = 1 + 32 + 16 + hash_bytes;
                dst.reserve(4 + payload_len);
                dst.put_u32(payload_len as u32);
                dst.put_u8(ID_HASHES);
                dst.put_slice(&pieces_root.0);
                dst.put_u32(*base);
                dst.put_u32(*index);
                dst.put_u32(*count);
                dst.put_u32(*proof_layers);
                for h in hashes {
                    dst.put_slice(&h.0);
                }
            }
        }
    }

    /// Return the exact encoded wire length in bytes, including the 4-byte
    /// length prefix.
    ///
    /// This is a pure computation — no allocation, no encoding.  Use it to
    /// check whether a message fits in a fixed-size buffer before calling
    /// [`encode_to_slice`](Self::encode_to_slice).
    #[must_use]
    pub fn wire_len(&self) -> usize {
        match self {
            Self::KeepAlive => 4,
            Self::Choke
            | Self::Unchoke
            | Self::Interested
            | Self::NotInterested
            | Self::HaveAll
            | Self::HaveNone => 5,
            Self::Have { .. } | Self::SuggestPiece(_) | Self::AllowedFast(_) => 9,
            Self::Port(_) => 7,
            Self::Request { .. } | Self::Cancel { .. } | Self::RejectRequest { .. } => 17,
            Self::Bitfield(bits) => 5 + bits.as_ref().len(),
            Self::Piece { data_0, data_1, .. } => {
                13 + data_0.as_ref().len() + data_1.as_ref().len()
            }
            Self::Extended { payload, .. } => 6 + payload.as_ref().len(),
            Self::HashRequest { .. } | Self::HashReject { .. } => 53,
            Self::Hashes { hashes, .. } => 53 + hashes.len() * 32,
        }
    }

    /// Encode this message (with length prefix) into a raw byte slice.
    ///
    /// Returns the number of bytes written. The caller must ensure `dst` is
    /// large enough to hold the encoded message. For peer wire messages,
    /// `MAX_MSG_LEN` (16397) is always sufficient.
    ///
    /// Uses `std::io::Cursor<&mut [u8]>` + `std::io::Write` instead of
    /// `BufMut`, producing identical bytes to [`encode_into`](Self::encode_into).
    #[must_use]
    pub fn encode_to_slice(&self, dst: &mut [u8]) -> usize {
        use std::io::{Cursor, Write};

        let mut cursor = Cursor::new(dst);

        match self {
            Self::KeepAlive => {
                cursor.write_all(&0u32.to_be_bytes()).unwrap();
            }
            Self::Choke => {
                cursor.write_all(&1u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_CHOKE]).unwrap();
            }
            Self::Unchoke => {
                cursor.write_all(&1u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_UNCHOKE]).unwrap();
            }
            Self::Interested => {
                cursor.write_all(&1u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_INTERESTED]).unwrap();
            }
            Self::NotInterested => {
                cursor.write_all(&1u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_NOT_INTERESTED]).unwrap();
            }
            Self::Have { index } => {
                cursor.write_all(&5u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_HAVE]).unwrap();
                cursor.write_all(&index.to_be_bytes()).unwrap();
            }
            Self::Bitfield(bits) => {
                let bits = bits.as_ref();
                cursor
                    .write_all(&(1 + bits.len() as u32).to_be_bytes())
                    .unwrap();
                cursor.write_all(&[ID_BITFIELD]).unwrap();
                cursor.write_all(bits).unwrap();
            }
            Self::Request {
                index,
                begin,
                length,
            } => {
                cursor.write_all(&13u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_REQUEST]).unwrap();
                cursor.write_all(&index.to_be_bytes()).unwrap();
                cursor.write_all(&begin.to_be_bytes()).unwrap();
                cursor.write_all(&length.to_be_bytes()).unwrap();
            }
            Self::Piece {
                index,
                begin,
                data_0,
                data_1,
            } => {
                let d0 = data_0.as_ref();
                let d1 = data_1.as_ref();
                let data_len = d0.len() + d1.len();
                cursor
                    .write_all(&(9 + data_len as u32).to_be_bytes())
                    .unwrap();
                cursor.write_all(&[ID_PIECE]).unwrap();
                cursor.write_all(&index.to_be_bytes()).unwrap();
                cursor.write_all(&begin.to_be_bytes()).unwrap();
                cursor.write_all(d0).unwrap();
                cursor.write_all(d1).unwrap();
            }
            Self::Cancel {
                index,
                begin,
                length,
            } => {
                cursor.write_all(&13u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_CANCEL]).unwrap();
                cursor.write_all(&index.to_be_bytes()).unwrap();
                cursor.write_all(&begin.to_be_bytes()).unwrap();
                cursor.write_all(&length.to_be_bytes()).unwrap();
            }
            Self::Port(port) => {
                cursor.write_all(&3u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_PORT]).unwrap();
                cursor.write_all(&port.to_be_bytes()).unwrap();
            }
            Self::Extended { ext_id, payload } => {
                let payload = payload.as_ref();
                cursor
                    .write_all(&(2 + payload.len() as u32).to_be_bytes())
                    .unwrap();
                cursor.write_all(&[ID_EXTENDED]).unwrap();
                cursor.write_all(&[*ext_id]).unwrap();
                cursor.write_all(payload).unwrap();
            }
            Self::SuggestPiece(index) => {
                cursor.write_all(&5u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_SUGGEST_PIECE]).unwrap();
                cursor.write_all(&index.to_be_bytes()).unwrap();
            }
            Self::HaveAll => {
                cursor.write_all(&1u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_HAVE_ALL]).unwrap();
            }
            Self::HaveNone => {
                cursor.write_all(&1u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_HAVE_NONE]).unwrap();
            }
            Self::RejectRequest {
                index,
                begin,
                length,
            } => {
                cursor.write_all(&13u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_REJECT_REQUEST]).unwrap();
                cursor.write_all(&index.to_be_bytes()).unwrap();
                cursor.write_all(&begin.to_be_bytes()).unwrap();
                cursor.write_all(&length.to_be_bytes()).unwrap();
            }
            Self::AllowedFast(index) => {
                cursor.write_all(&5u32.to_be_bytes()).unwrap();
                cursor.write_all(&[ID_ALLOWED_FAST]).unwrap();
                cursor.write_all(&index.to_be_bytes()).unwrap();
            }
            Self::HashRequest {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
            }
            | Self::HashReject {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
            } => {
                let id = match self {
                    Self::HashRequest { .. } => ID_HASH_REQUEST,
                    _ => ID_HASH_REJECT,
                };
                cursor.write_all(&49u32.to_be_bytes()).unwrap();
                cursor.write_all(&[id]).unwrap();
                cursor.write_all(&pieces_root.0).unwrap();
                cursor.write_all(&base.to_be_bytes()).unwrap();
                cursor.write_all(&index.to_be_bytes()).unwrap();
                cursor.write_all(&count.to_be_bytes()).unwrap();
                cursor.write_all(&proof_layers.to_be_bytes()).unwrap();
            }
            Self::Hashes {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
                hashes,
            } => {
                let hash_bytes = hashes.len() * 32;
                let payload_len = 1 + 32 + 16 + hash_bytes;
                cursor
                    .write_all(&(payload_len as u32).to_be_bytes())
                    .unwrap();
                cursor.write_all(&[ID_HASHES]).unwrap();
                cursor.write_all(&pieces_root.0).unwrap();
                cursor.write_all(&base.to_be_bytes()).unwrap();
                cursor.write_all(&index.to_be_bytes()).unwrap();
                cursor.write_all(&count.to_be_bytes()).unwrap();
                cursor.write_all(&proof_layers.to_be_bytes()).unwrap();
                for h in hashes {
                    cursor.write_all(&h.0).unwrap();
                }
            }
        }

        cursor.position() as usize
    }
}

impl Message<&[u8]> {
    /// Convert a borrowed message to an owned `Message<Bytes>`.
    ///
    /// Fixed-field variants are zero-cost (no data to copy).
    /// Data-carrying variants (`Piece`, `Bitfield`, `Extended`) copy their
    /// slices into fresh `Bytes` allocations.
    #[must_use]
    pub fn to_owned_bytes(&self) -> Message<Bytes> {
        match *self {
            Message::KeepAlive => Message::KeepAlive,
            Message::Choke => Message::Choke,
            Message::Unchoke => Message::Unchoke,
            Message::Interested => Message::Interested,
            Message::NotInterested => Message::NotInterested,
            Message::Have { index } => Message::Have { index },
            Message::Bitfield(data) => Message::Bitfield(Bytes::copy_from_slice(data)),
            Message::Request {
                index,
                begin,
                length,
            } => Message::Request {
                index,
                begin,
                length,
            },
            Message::Piece {
                index,
                begin,
                data_0,
                data_1,
            } => Message::Piece {
                index,
                begin,
                data_0: Bytes::copy_from_slice(data_0),
                data_1: Bytes::copy_from_slice(data_1),
            },
            Message::Cancel {
                index,
                begin,
                length,
            } => Message::Cancel {
                index,
                begin,
                length,
            },
            Message::Port(port) => Message::Port(port),
            Message::Extended { ext_id, payload } => Message::Extended {
                ext_id,
                payload: Bytes::copy_from_slice(payload),
            },
            Message::SuggestPiece(index) => Message::SuggestPiece(index),
            Message::HaveAll => Message::HaveAll,
            Message::HaveNone => Message::HaveNone,
            Message::RejectRequest {
                index,
                begin,
                length,
            } => Message::RejectRequest {
                index,
                begin,
                length,
            },
            Message::AllowedFast(index) => Message::AllowedFast(index),
            Message::HashRequest {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
            } => Message::HashRequest {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
            },
            Message::Hashes {
                ref pieces_root,
                base,
                index,
                count,
                proof_layers,
                ref hashes,
            } => Message::Hashes {
                pieces_root: *pieces_root,
                base,
                index,
                count,
                proof_layers,
                hashes: hashes.clone(),
            },
            Message::HashReject {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
            } => Message::HashReject {
                pieces_root,
                base,
                index,
                count,
                proof_layers,
            },
        }
    }
}

impl Message<Bytes> {
    /// Parse a message from its payload (after the 4-byte length prefix has
    /// been consumed). `payload` is everything after the length prefix.
    ///
    /// # Errors
    ///
    /// Returns an error if the message ID is unknown or the payload is malformed.
    #[allow(clippy::needless_pass_by_value, reason = "pub API stability")]
    pub fn from_payload(payload: Bytes) -> Result<Self> {
        if payload.is_empty() {
            return Ok(Self::KeepAlive);
        }

        let id = payload[0];
        let body = &payload[1..];

        match id {
            ID_CHOKE => Ok(Self::Choke),
            ID_UNCHOKE => Ok(Self::Unchoke),
            ID_INTERESTED => Ok(Self::Interested),
            ID_NOT_INTERESTED => Ok(Self::NotInterested),
            ID_HAVE => {
                ensure_len(body, 4, "Have")?;
                Ok(Self::Have {
                    index: read_u32(body),
                })
            }
            ID_BITFIELD => Ok(Self::Bitfield(payload.slice(1..))),
            ID_REQUEST => {
                ensure_len(body, 12, "Request")?;
                Ok(Self::Request {
                    index: read_u32(body),
                    begin: read_u32(&body[4..]),
                    length: read_u32(&body[8..]),
                })
            }
            ID_PIECE => {
                ensure_len(body, 8, "Piece")?;
                let index = read_u32(body);
                let begin = read_u32(&body[4..]);
                Ok(Self::Piece {
                    index,
                    begin,
                    data_0: payload.slice(9..),
                    data_1: Bytes::new(),
                })
            }
            ID_CANCEL => {
                ensure_len(body, 12, "Cancel")?;
                Ok(Self::Cancel {
                    index: read_u32(body),
                    begin: read_u32(&body[4..]),
                    length: read_u32(&body[8..]),
                })
            }
            ID_PORT => {
                ensure_len(body, 2, "Port")?;
                Ok(Self::Port(u16::from_be_bytes([body[0], body[1]])))
            }
            ID_EXTENDED => {
                ensure_len(body, 1, "Extended")?;
                let ext_id = body[0];
                Ok(Self::Extended {
                    ext_id,
                    payload: payload.slice(2..),
                })
            }
            ID_SUGGEST_PIECE => {
                ensure_len(body, 4, "SuggestPiece")?;
                Ok(Self::SuggestPiece(read_u32(body)))
            }
            ID_HAVE_ALL => Ok(Self::HaveAll),
            ID_HAVE_NONE => Ok(Self::HaveNone),
            ID_REJECT_REQUEST => {
                ensure_len(body, 12, "RejectRequest")?;
                Ok(Self::RejectRequest {
                    index: read_u32(body),
                    begin: read_u32(&body[4..]),
                    length: read_u32(&body[8..]),
                })
            }
            ID_ALLOWED_FAST => {
                ensure_len(body, 4, "AllowedFast")?;
                Ok(Self::AllowedFast(read_u32(body)))
            }
            ID_HASH_REQUEST | ID_HASH_REJECT => {
                ensure_len(body, 48, "HashRequest/Reject")?;
                let mut root = [0u8; 32];
                root.copy_from_slice(&body[..32]);
                let pieces_root = irontide_core::Id32(root);
                let base = read_u32(&body[32..]);
                let index = read_u32(&body[36..]);
                let count = read_u32(&body[40..]);
                let proof_layers = read_u32(&body[44..]);
                if id == ID_HASH_REQUEST {
                    Ok(Self::HashRequest {
                        pieces_root,
                        base,
                        index,
                        count,
                        proof_layers,
                    })
                } else {
                    Ok(Self::HashReject {
                        pieces_root,
                        base,
                        index,
                        count,
                        proof_layers,
                    })
                }
            }
            ID_HASHES => {
                ensure_len(body, 48, "Hashes")?;
                let mut root = [0u8; 32];
                root.copy_from_slice(&body[..32]);
                let pieces_root = irontide_core::Id32(root);
                let base = read_u32(&body[32..]);
                let index = read_u32(&body[36..]);
                let count = read_u32(&body[40..]);
                let proof_layers = read_u32(&body[44..]);
                let hash_data = &body[48..];
                if !hash_data.len().is_multiple_of(32) {
                    return Err(Error::MessageTooShort {
                        expected: 48 + 32,
                        got: body.len(),
                    });
                }
                let hashes = hash_data
                    .chunks_exact(32)
                    .map(|chunk| {
                        let mut h = [0u8; 32];
                        h.copy_from_slice(chunk);
                        irontide_core::Id32(h)
                    })
                    .collect();
                Ok(Self::Hashes {
                    pieces_root,
                    base,
                    index,
                    count,
                    proof_layers,
                    hashes,
                })
            }
            _ => Err(Error::InvalidMessageId(id)),
        }
    }
}

fn encode_fixed_into(dst: &mut BytesMut, id: u8) {
    dst.put_u32(1);
    dst.put_u8(id);
}

fn encode_triple_into(dst: &mut BytesMut, id: u8, a: u32, b: u32, c: u32) {
    dst.put_u32(13);
    dst.put_u8(id);
    dst.put_u32(a);
    dst.put_u32(b);
    dst.put_u32(c);
}

fn fixed_msg(id: u8) -> Bytes {
    let mut buf = BytesMut::with_capacity(5);
    buf.put_u32(1);
    buf.put_u8(id);
    buf.freeze()
}

fn triple_msg(id: u8, a: u32, b: u32, c: u32) -> Bytes {
    let mut buf = BytesMut::with_capacity(17);
    buf.put_u32(13);
    buf.put_u8(id);
    buf.put_u32(a);
    buf.put_u32(b);
    buf.put_u32(c);
    buf.freeze()
}

fn read_u32(buf: &[u8]) -> u32 {
    let mut b = [0u8; 4];
    b.copy_from_slice(&buf[..4]);
    u32::from_be_bytes(b)
}

fn ensure_len(body: &[u8], min: usize, _name: &str) -> Result<()> {
    if body.len() < min {
        Err(Error::MessageTooShort {
            expected: min,
            got: body.len(),
        })
    } else {
        Ok(())
    }
}

/// BEP 6 Allowed-Fast set generation.
///
/// Generates a deterministic set of piece indices that a peer is allowed
/// to request even while choked. Uses IP masking + `info_hash` + SHA1.
///
/// For IPv4: masks to /24 (matching BEP 6 spec).
/// For IPv6: masks to /48 (matching libtorrent convention).
#[must_use]
pub fn allowed_fast_set(
    info_hash: &irontide_core::Id20,
    peer_ip: std::net::Ipv4Addr,
    num_pieces: u32,
    count: usize,
) -> Vec<u32> {
    allowed_fast_set_for_ip(info_hash, std::net::IpAddr::V4(peer_ip), num_pieces, count)
}

/// BEP 6 Allowed-Fast set generation for any IP address family.
///
/// IPv4: /24 prefix mask. IPv6: /48 prefix mask (libtorrent convention).
#[must_use]
pub fn allowed_fast_set_for_ip(
    info_hash: &irontide_core::Id20,
    peer_ip: std::net::IpAddr,
    num_pieces: u32,
    count: usize,
) -> Vec<u32> {
    use irontide_core::sha1;

    if num_pieces == 0 {
        return Vec::new();
    }

    let count = count.min(num_pieces as usize);
    let mut result = Vec::with_capacity(count);

    // Build masked IP bytes based on address family
    let masked: Vec<u8> = match peer_ip {
        std::net::IpAddr::V4(ipv4) => {
            // Mask to /24
            let o = ipv4.octets();
            vec![o[0], o[1], o[2], 0]
        }
        std::net::IpAddr::V6(ipv6) => {
            // Mask to /48: keep first 6 bytes, zero the rest
            let o = ipv6.octets();
            let mut masked = [0u8; 16];
            masked[..6].copy_from_slice(&o[..6]);
            masked.to_vec()
        }
    };

    // Initial hash: SHA1(masked_ip + info_hash)
    let mut input = Vec::with_capacity(masked.len() + 20);
    input.extend_from_slice(&masked);
    input.extend_from_slice(info_hash.as_bytes());
    let mut hash = sha1(&input);

    while result.len() < count {
        let hash_bytes = hash.as_bytes();
        // Each 20-byte hash gives us 5 candidate indices (4 bytes each)
        for i in (0..20).step_by(4) {
            if result.len() >= count {
                break;
            }
            let index = u32::from_be_bytes([
                hash_bytes[i],
                hash_bytes[i + 1],
                hash_bytes[i + 2],
                hash_bytes[i + 3],
            ]) % num_pieces;
            if !result.contains(&index) {
                result.push(index);
            }
        }
        // Re-hash for more candidates
        hash = sha1(hash.as_bytes());
    }

    result
}

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

    #[allow(clippy::needless_pass_by_value, reason = "test helper convenience")]
    fn round_trip(msg: Message) {
        let bytes = msg.to_bytes();
        // Skip the 4-byte length prefix for parsing
        let parsed = Message::from_payload(Bytes::copy_from_slice(&bytes[4..])).unwrap();
        assert_eq!(msg, parsed);
    }

    #[test]
    fn keepalive() {
        round_trip(Message::KeepAlive);
    }

    #[test]
    fn choke_unchoke() {
        round_trip(Message::Choke);
        round_trip(Message::Unchoke);
    }

    #[test]
    fn interested() {
        round_trip(Message::Interested);
        round_trip(Message::NotInterested);
    }

    #[test]
    fn have() {
        round_trip(Message::Have { index: 42 });
    }

    #[test]
    fn bitfield() {
        round_trip(Message::Bitfield(Bytes::from_static(&[0xFF, 0x80])));
    }

    #[test]
    fn request() {
        round_trip(Message::Request {
            index: 1,
            begin: 0,
            length: 16384,
        });
    }

    #[test]
    fn piece() {
        round_trip(Message::Piece {
            index: 1,
            begin: 0,
            data_0: Bytes::from_static(b"hello world"),
            data_1: Bytes::new(),
        });
    }

    #[test]
    fn cancel() {
        round_trip(Message::Cancel {
            index: 1,
            begin: 0,
            length: 16384,
        });
    }

    #[test]
    fn port() {
        round_trip(Message::Port(6881));
    }

    #[test]
    fn extended() {
        round_trip(Message::Extended {
            ext_id: 1,
            payload: Bytes::from_static(b"test payload"),
        });
    }

    #[test]
    fn invalid_message_id() {
        assert!(Message::from_payload(Bytes::from_static(&[99u8])).is_err());
    }

    #[test]
    fn suggest_piece() {
        round_trip(Message::SuggestPiece(42));
    }

    #[test]
    fn have_all() {
        round_trip(Message::HaveAll);
    }

    #[test]
    fn have_none() {
        round_trip(Message::HaveNone);
    }

    #[test]
    fn reject_request() {
        round_trip(Message::RejectRequest {
            index: 1,
            begin: 0,
            length: 16384,
        });
    }

    #[test]
    fn allowed_fast() {
        round_trip(Message::AllowedFast(7));
    }

    #[test]
    fn allowed_fast_set_deterministic() {
        use irontide_core::Id20;
        let ih = Id20::from_hex("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d").unwrap();
        let ip: std::net::Ipv4Addr = "192.168.1.100".parse().unwrap();
        let set1 = allowed_fast_set(&ih, ip, 1000, 10);
        let set2 = allowed_fast_set(&ih, ip, 1000, 10);
        assert_eq!(set1, set2);
        assert_eq!(set1.len(), 10);
        // All indices in range
        assert!(set1.iter().all(|&i| i < 1000));
    }

    #[test]
    fn allowed_fast_set_unique() {
        use irontide_core::Id20;
        let ih = Id20::from_hex("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d").unwrap();
        let ip: std::net::Ipv4Addr = "10.0.0.1".parse().unwrap();
        let set = allowed_fast_set(&ih, ip, 50, 10);
        let unique: std::collections::HashSet<u32> = set.iter().copied().collect();
        assert_eq!(set.len(), unique.len(), "all indices should be unique");
    }

    #[test]
    fn allowed_fast_set_empty_torrent() {
        use irontide_core::Id20;
        let ih = Id20::ZERO;
        let ip: std::net::Ipv4Addr = "127.0.0.1".parse().unwrap();
        assert!(allowed_fast_set(&ih, ip, 0, 10).is_empty());
    }

    #[test]
    fn allowed_fast_set_ipv6() {
        use irontide_core::Id20;
        let ih = Id20::from_hex("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d").unwrap();
        let ip: std::net::IpAddr = "2001:db8::1".parse().unwrap();
        let set = allowed_fast_set_for_ip(&ih, ip, 1000, 10);
        assert_eq!(set.len(), 10);
        assert!(set.iter().all(|&i| i < 1000));

        // Same /48 prefix should produce same set
        let ip2: std::net::IpAddr = "2001:db8::ffff".parse().unwrap();
        let set2 = allowed_fast_set_for_ip(&ih, ip2, 1000, 10);
        assert_eq!(set, set2);

        // Different /48 prefix should produce different set
        let ip3: std::net::IpAddr = "2001:db9::1".parse().unwrap();
        let set3 = allowed_fast_set_for_ip(&ih, ip3, 1000, 10);
        assert_ne!(set, set3);
    }

    #[test]
    fn hash_request_round_trip() {
        let msg = Message::HashRequest {
            pieces_root: irontide_core::Id32::ZERO,
            base: 7,
            index: 0,
            count: 512,
            proof_layers: 3,
        };
        round_trip(msg);
    }

    #[test]
    fn hash_reject_round_trip() {
        let msg = Message::HashReject {
            pieces_root: irontide_core::Id32::ZERO,
            base: 7,
            index: 0,
            count: 512,
            proof_layers: 3,
        };
        round_trip(msg);
    }

    #[test]
    fn hashes_round_trip() {
        let h1 = irontide_core::sha256(b"block1");
        let h2 = irontide_core::sha256(b"block2");
        let uncle = irontide_core::sha256(b"uncle");
        let msg = Message::Hashes {
            pieces_root: irontide_core::Id32::ZERO,
            base: 0,
            index: 0,
            count: 2,
            proof_layers: 1,
            hashes: vec![h1, h2, uncle],
        };
        round_trip(msg);
    }

    #[test]
    fn hash_request_exact_wire_size() {
        let msg: Message = Message::HashRequest {
            pieces_root: irontide_core::Id32::ZERO,
            base: 0,
            index: 0,
            count: 1,
            proof_layers: 0,
        };
        let bytes = msg.to_bytes();
        // 4 (length prefix) + 1 (msg id) + 32 (root) + 4*4 (fields) = 53
        assert_eq!(bytes.len(), 53);
    }

    #[test]
    fn hashes_variable_length() {
        let h = irontide_core::sha256(b"test");
        let msg: Message = Message::Hashes {
            pieces_root: irontide_core::Id32::ZERO,
            base: 0,
            index: 0,
            count: 1,
            proof_layers: 0,
            hashes: vec![h],
        };
        let bytes = msg.to_bytes();
        // 4 + 1 + 32 + 4*4 + 1*32 = 85
        assert_eq!(bytes.len(), 85);
    }

    #[test]
    fn hash_request_too_short() {
        // msg id 21, but only 10 bytes of body (need 48)
        let mut payload = vec![21u8];
        payload.extend_from_slice(&[0u8; 10]);
        assert!(Message::from_payload(Bytes::from(payload)).is_err());
    }

    #[test]
    fn encode_into_matches_to_bytes() {
        let messages = vec![
            Message::KeepAlive,
            Message::Choke,
            Message::Unchoke,
            Message::Interested,
            Message::NotInterested,
            Message::Have { index: 42 },
            Message::Bitfield(Bytes::from_static(b"\xff\x00")),
            Message::Request {
                index: 1,
                begin: 0,
                length: 16384,
            },
            Message::Piece {
                index: 0,
                begin: 0,
                data_0: Bytes::from_static(b"block data here"),
                data_1: Bytes::new(),
            },
            Message::Cancel {
                index: 1,
                begin: 0,
                length: 16384,
            },
            Message::Port(6881),
            Message::Extended {
                ext_id: 0,
                payload: Bytes::from_static(b"ext payload"),
            },
            Message::SuggestPiece(7),
            Message::HaveAll,
            Message::HaveNone,
            Message::RejectRequest {
                index: 1,
                begin: 0,
                length: 16384,
            },
            Message::AllowedFast(5),
            Message::HashRequest {
                pieces_root: irontide_core::Id32::ZERO,
                base: 7,
                index: 0,
                count: 512,
                proof_layers: 3,
            },
            Message::HashReject {
                pieces_root: irontide_core::Id32::ZERO,
                base: 7,
                index: 0,
                count: 512,
                proof_layers: 3,
            },
            Message::Hashes {
                pieces_root: irontide_core::Id32::ZERO,
                base: 0,
                index: 0,
                count: 2,
                proof_layers: 1,
                hashes: vec![
                    irontide_core::sha256(b"block1"),
                    irontide_core::sha256(b"block2"),
                    irontide_core::sha256(b"uncle"),
                ],
            },
        ];
        for msg in messages {
            let expected = msg.to_bytes();
            let mut buf = BytesMut::new();
            msg.encode_into(&mut buf);
            assert_eq!(&expected[..], &buf[..], "mismatch for {msg:?}");
        }
    }

    #[test]
    fn allowed_fast_set_ipv4_compat() {
        // allowed_fast_set (IPv4-only) and allowed_fast_set_for_ip with V4 should match
        use irontide_core::Id20;
        let ih = Id20::from_hex("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d").unwrap();
        let ipv4: std::net::Ipv4Addr = "192.168.1.100".parse().unwrap();
        let set_v4 = allowed_fast_set(&ih, ipv4, 1000, 10);
        let set_ip = allowed_fast_set_for_ip(&ih, std::net::IpAddr::V4(ipv4), 1000, 10);
        assert_eq!(set_v4, set_ip);
    }

    // ── M158: BEP 6 AllowedFast spec vector conformance ──

    #[test]
    fn allowed_fast_bep6_spec_vector_k7() {
        // BEP 6 exact test vector: IP 80.4.4.200, InfoHash 0xaaaa..aa, 1313 pieces, k=7
        use irontide_core::Id20;
        let ih = Id20([0xaa; 20]);
        let ip: std::net::Ipv4Addr = "80.4.4.200".parse().unwrap();
        let set = allowed_fast_set(&ih, ip, 1313, 7);
        assert_eq!(set, vec![1059, 431, 808, 1217, 287, 376, 1188]);
    }

    #[test]
    fn allowed_fast_bep6_spec_vector_k9() {
        // BEP 6 exact test vector: same inputs, k=9 — extends k=7 with [353, 508]
        use irontide_core::Id20;
        let ih = Id20([0xaa; 20]);
        let ip: std::net::Ipv4Addr = "80.4.4.200".parse().unwrap();
        let set = allowed_fast_set(&ih, ip, 1313, 9);
        assert_eq!(set, vec![1059, 431, 808, 1217, 287, 376, 1188, 353, 508]);
    }

    #[test]
    fn allowed_fast_ip_masking() {
        // BEP 6 spec: peer IP is masked to /24 before hashing.
        // 80.4.4.200 should mask to 80.4.4.0 = [0x50, 0x04, 0x04, 0x00].
        // Verify that any IP in the same /24 produces the same set.
        use irontide_core::Id20;
        let ih = Id20([0xaa; 20]);
        let ip_a: std::net::Ipv4Addr = "80.4.4.200".parse().unwrap();
        let ip_b: std::net::Ipv4Addr = "80.4.4.0".parse().unwrap();
        let ip_c: std::net::Ipv4Addr = "80.4.4.255".parse().unwrap();
        let set_a = allowed_fast_set(&ih, ip_a, 1313, 7);
        let set_b = allowed_fast_set(&ih, ip_b, 1313, 7);
        let set_c = allowed_fast_set(&ih, ip_c, 1313, 7);
        assert_eq!(
            set_a, set_b,
            "80.4.4.200 and 80.4.4.0 must produce same set (same /24)"
        );
        assert_eq!(
            set_a, set_c,
            "80.4.4.200 and 80.4.4.255 must produce same set (same /24)"
        );

        // Verify the masked bytes are correct: 80=0x50, 4=0x04, 4=0x04, 0=0x00
        let octets = ip_a.octets();
        let masked = [octets[0], octets[1], octets[2], 0u8];
        assert_eq!(masked, [0x50, 0x04, 0x04, 0x00]);
    }

    // ── M110: Generic Message<B> tests ──

    #[test]
    fn message_piece_two_fields_round_trip() {
        // Encode a Piece with data_0 only (data_1 empty) — common case.
        let msg = Message::Piece {
            index: 5,
            begin: 16384,
            data_0: Bytes::from_static(b"block payload here"),
            data_1: Bytes::new(),
        };
        let bytes = msg.to_bytes();
        let parsed = Message::from_payload(Bytes::copy_from_slice(&bytes[4..])).unwrap();
        assert_eq!(msg, parsed);
    }

    #[test]
    fn message_piece_split_data_round_trip() {
        // Encode a Piece with both data_0 and data_1 populated (ring-wrap case).
        // The wire format concatenates them, so decoding puts everything into data_0.
        let msg = Message::Piece {
            index: 3,
            begin: 0,
            data_0: Bytes::from_static(b"first half"),
            data_1: Bytes::from_static(b" second half"),
        };
        let bytes = msg.to_bytes();
        let parsed = Message::from_payload(Bytes::copy_from_slice(&bytes[4..])).unwrap();
        // After round-trip through the wire, the data is concatenated into data_0
        // with data_1 empty (the receiver doesn't know about ring-wrap).
        assert_eq!(
            parsed,
            Message::Piece {
                index: 3,
                begin: 0,
                data_0: Bytes::from_static(b"first half second half"),
                data_1: Bytes::new(),
            }
        );
    }

    #[test]
    fn message_generic_encode_borrowed() {
        // Verify that Message<&[u8]> can encode_into just like Message<Bytes>.
        let borrowed: Message<&[u8]> = Message::Piece {
            index: 1,
            begin: 0,
            data_0: b"borrowed data",
            data_1: b"",
        };
        let owned: Message<Bytes> = Message::Piece {
            index: 1,
            begin: 0,
            data_0: Bytes::from_static(b"borrowed data"),
            data_1: Bytes::new(),
        };
        let mut buf_borrowed = BytesMut::new();
        borrowed.encode_into(&mut buf_borrowed);
        let mut buf_owned = BytesMut::new();
        owned.encode_into(&mut buf_owned);
        assert_eq!(
            buf_borrowed, buf_owned,
            "borrowed and owned encode identically"
        );

        // Also test to_bytes
        assert_eq!(borrowed.to_bytes(), owned.to_bytes());

        // Test borrowed Bitfield
        let bf_borrowed: Message<&[u8]> = Message::Bitfield(b"\xff\x80");
        let bf_owned: Message<Bytes> = Message::Bitfield(Bytes::from_static(b"\xff\x80"));
        assert_eq!(bf_borrowed.to_bytes(), bf_owned.to_bytes());

        // Test borrowed Extended
        let ext_borrowed: Message<&[u8]> = Message::Extended {
            ext_id: 1,
            payload: b"payload",
        };
        let ext_owned: Message<Bytes> = Message::Extended {
            ext_id: 1,
            payload: Bytes::from_static(b"payload"),
        };
        assert_eq!(ext_borrowed.to_bytes(), ext_owned.to_bytes());
    }

    // ── M115: encode_to_slice tests ──

    /// Build the complete set of message variants used for `encode_to_slice` tests.
    fn all_message_variants() -> Vec<Message> {
        vec![
            Message::KeepAlive,
            Message::Choke,
            Message::Unchoke,
            Message::Interested,
            Message::NotInterested,
            Message::Have { index: 42 },
            Message::Bitfield(Bytes::from_static(b"\xff\x00")),
            Message::Request {
                index: 1,
                begin: 0,
                length: 16384,
            },
            Message::Piece {
                index: 0,
                begin: 0,
                data_0: Bytes::from_static(b"block data here"),
                data_1: Bytes::new(),
            },
            Message::Piece {
                index: 3,
                begin: 0,
                data_0: Bytes::from_static(b"first half"),
                data_1: Bytes::from_static(b" second half"),
            },
            Message::Cancel {
                index: 1,
                begin: 0,
                length: 16384,
            },
            Message::Port(6881),
            Message::Extended {
                ext_id: 0,
                payload: Bytes::from_static(b"ext payload"),
            },
            Message::SuggestPiece(7),
            Message::HaveAll,
            Message::HaveNone,
            Message::RejectRequest {
                index: 1,
                begin: 0,
                length: 16384,
            },
            Message::AllowedFast(5),
            Message::HashRequest {
                pieces_root: irontide_core::Id32::ZERO,
                base: 7,
                index: 0,
                count: 512,
                proof_layers: 3,
            },
            Message::HashReject {
                pieces_root: irontide_core::Id32::ZERO,
                base: 7,
                index: 0,
                count: 512,
                proof_layers: 3,
            },
            Message::Hashes {
                pieces_root: irontide_core::Id32::ZERO,
                base: 0,
                index: 0,
                count: 2,
                proof_layers: 1,
                hashes: vec![
                    irontide_core::sha256(b"block1"),
                    irontide_core::sha256(b"block2"),
                    irontide_core::sha256(b"uncle"),
                ],
            },
        ]
    }

    #[test]
    fn encode_to_slice_roundtrip() {
        for msg in all_message_variants() {
            let mut buf = [0u8; 4096];
            let n = msg.encode_to_slice(&mut buf);
            // Skip the 4-byte length prefix for parsing
            let parsed = Message::from_payload(Bytes::copy_from_slice(&buf[4..n])).unwrap();
            // For Piece with split data, wire format concatenates into data_0
            match &msg {
                Message::Piece {
                    index,
                    begin,
                    data_0,
                    data_1,
                } if !data_1.is_empty() => {
                    let mut combined = Vec::from(data_0.as_ref());
                    combined.extend_from_slice(data_1.as_ref());
                    let expected = Message::Piece {
                        index: *index,
                        begin: *begin,
                        data_0: Bytes::from(combined),
                        data_1: Bytes::new(),
                    };
                    assert_eq!(parsed, expected, "roundtrip mismatch for split Piece");
                }
                _ => {
                    assert_eq!(msg, parsed, "roundtrip mismatch for {msg:?}");
                }
            }
        }
    }

    #[test]
    fn encode_to_slice_matches_encode_into() {
        for msg in all_message_variants() {
            let mut slice_buf = [0u8; 4096];
            let n = msg.encode_to_slice(&mut slice_buf);

            let mut bytes_buf = BytesMut::new();
            msg.encode_into(&mut bytes_buf);

            assert_eq!(
                &slice_buf[..n],
                &bytes_buf[..],
                "encode_to_slice vs encode_into mismatch for {msg:?}"
            );
        }
    }

    #[test]
    fn wire_len_matches_encoded_size() {
        for msg in all_message_variants() {
            let expected = msg.to_bytes().len();
            assert_eq!(msg.wire_len(), expected, "wire_len mismatch for {msg:?}");
        }
    }

    #[test]
    fn wire_len_large_bitfield() {
        // Bitfield for a torrent with >131K pieces (16,384 bytes of bitfield data).
        let bits = vec![0xFFu8; 20_000];
        let msg = Message::Bitfield(Bytes::from(bits.clone()));
        assert_eq!(msg.wire_len(), 5 + bits.len());
        assert_eq!(msg.wire_len(), msg.to_bytes().len());
    }
}