torrent-core 0.1.5

Low-level core abstractions for the BitTorrent protocol — bencode, metainfo parsing, peer wire protocol types, DHT/Kademlia, piece management, and storage traits. Zero async dependencies.
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
//! KRPC message encoding/decoding — BEP 5.
//!
//! Provides the [`KrpcMessage`] enum, builder helpers for queries
//! and responses, response parsers, and compact node I/O.

use std::net::{IpAddr, Ipv4Addr, SocketAddr};

use crate::bencode::{self, Bencode, Bytes};
use crate::error::{Error, ErrorKind};

/// Transaction ID type (2-byte random value).
pub type TransactionId = [u8; 2];

/// KRPC message types (BEP 5).
///
/// Each message is a bencoded dictionary with the following structure:
///
/// ```text
/// Query:  {"t": "<2-byte id>", "y": "q", "q": "<method>", "a": <args>}
/// Response: {"t": "<2-byte id>", "y": "r", "r": <result>}
/// Error:  {"t": "<2-byte id>", "y": "e", "e": [<code>, <msg>]}
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KrpcMessage {
    Query {
        transaction_id: TransactionId,
        method: String,
        args: Bencode,
    },
    Response {
        transaction_id: TransactionId,
        result: Bencode,
    },
    Error {
        transaction_id: TransactionId,
        code: i64,
        message: String,
    },
}

impl KrpcMessage {
    /// Encode a KRPC message to bencoded bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        tracing::trace!("encoding KRPC message: {:?}", self);
        let dict = match self {
            KrpcMessage::Query {
                transaction_id,
                method,
                args,
            } => Bencode::Dict(vec![
                (
                    t_key(),
                    Bencode::Bytes(Bytes::copy_from_slice(transaction_id)),
                ),
                (y_key(), Bencode::Bytes(Bytes::copy_from_slice(b"q"))),
                (
                    q_key(),
                    Bencode::Bytes(Bytes::copy_from_slice(method.as_bytes())),
                ),
                (a_key(), args.clone()),
            ]),
            KrpcMessage::Response {
                transaction_id,
                result,
            } => Bencode::Dict(vec![
                (
                    t_key(),
                    Bencode::Bytes(Bytes::copy_from_slice(transaction_id)),
                ),
                (y_key(), Bencode::Bytes(Bytes::copy_from_slice(b"r"))),
                (r_key(), result.clone()),
            ]),
            KrpcMessage::Error {
                transaction_id,
                code,
                message,
            } => Bencode::Dict(vec![
                (
                    t_key(),
                    Bencode::Bytes(Bytes::copy_from_slice(transaction_id)),
                ),
                (y_key(), Bencode::Bytes(Bytes::copy_from_slice(b"e"))),
                (
                    e_key(),
                    Bencode::List(vec![
                        Bencode::Integer(*code),
                        Bencode::Bytes(Bytes::copy_from_slice(message.as_bytes())),
                    ]),
                ),
            ]),
        };
        bencode::encode(&dict)
    }

    /// Decode a KRPC message from bencoded bytes.
    pub fn from_bytes(data: &[u8]) -> Result<Self, Error> {
        tracing::trace!("decoding KRPC message ({} bytes)", data.len());
        let (val, _rest) = bencode::decode(data)?;
        Self::from_bencode(&val)
    }

    /// Decode a KRPC message from a bencoded value.
    pub fn from_bencode(val: &Bencode) -> Result<Self, Error> {
        let t = dict_get_bytes(val, b"t").ok_or(Error::new(ErrorKind::Protocol))?;
        let mut transaction_id = [0u8; 2];
        let len = std::cmp::min(t.len(), 2);
        transaction_id[..len].copy_from_slice(&t[..len]);

        let y = dict_get_bytes(val, b"y").ok_or(Error::new(ErrorKind::Protocol))?;
        let y_byte = if !y.is_empty() { y[0] } else { 0 };

        match y_byte {
            b'q' => {
                let method = dict_get_bytes(val, b"q")
                    .and_then(|b| String::from_utf8(b.to_vec()).ok())
                    .ok_or(Error::new(ErrorKind::Protocol))?;
                let args = dict_get(val, b"a")
                    .cloned()
                    .unwrap_or(Bencode::Dict(vec![]));
                Ok(KrpcMessage::Query {
                    transaction_id,
                    method,
                    args,
                })
            }
            b'r' => {
                let result = dict_get(val, b"r")
                    .cloned()
                    .unwrap_or(Bencode::Dict(vec![]));
                Ok(KrpcMessage::Response {
                    transaction_id,
                    result,
                })
            }
            b'e' => {
                let err_val = dict_get(val, b"e").ok_or(Error::new(ErrorKind::Protocol))?;
                match err_val {
                    Bencode::List(items) if items.len() >= 2 => {
                        let code = match &items[0] {
                            Bencode::Integer(c) => *c,
                            _ => return Err(Error::new(ErrorKind::Protocol)),
                        };
                        let message = match &items[1] {
                            Bencode::Bytes(b) => String::from_utf8(b.to_vec()).unwrap_or_default(),
                            _ => return Err(Error::new(ErrorKind::Protocol)),
                        };
                        Ok(KrpcMessage::Error {
                            transaction_id,
                            code,
                            message,
                        })
                    }
                    _ => Err(Error::new(ErrorKind::Protocol)),
                }
            }
            _ => Err(Error::new(ErrorKind::Protocol)),
        }
    }
}

// ── Build helpers ────────────────────────────────────────────────────

/// Build a ping query (BEP 5).
///
/// Creates a KRPC `ping` query message with the given transaction ID
/// and node ID. The result is bencoded bytes ready to send over UDP.
pub fn build_ping(tid: TransactionId, node_id: &[u8; 20]) -> Vec<u8> {
    KrpcMessage::Query {
        transaction_id: tid,
        method: "ping".into(),
        args: Bencode::Dict(vec![(
            id_key(),
            Bencode::Bytes(Bytes::copy_from_slice(node_id)),
        )]),
    }
    .to_bytes()
}

/// Build a find_node query (BEP 5).
///
/// Creates a KRPC `find_node` query for discovering nodes close to
/// a target ID. Used during the DHT bootstrap and recursive lookup process.
pub fn build_find_node(tid: TransactionId, node_id: &[u8; 20], target: &[u8; 20]) -> Vec<u8> {
    KrpcMessage::Query {
        transaction_id: tid,
        method: "find_node".into(),
        args: Bencode::Dict(vec![
            (id_key(), Bencode::Bytes(Bytes::copy_from_slice(node_id))),
            (target_key(), Bencode::Bytes(Bytes::copy_from_slice(target))),
        ]),
    }
    .to_bytes()
}

/// Build a get_peers query (BEP 5).
///
/// Creates a KRPC `get_peers` query to discover peers sharing a torrent
/// identified by `info_hash`. The response may contain peer addresses
/// or closer DHT nodes.
pub fn build_get_peers(tid: TransactionId, node_id: &[u8; 20], info_hash: &[u8; 20]) -> Vec<u8> {
    KrpcMessage::Query {
        transaction_id: tid,
        method: "get_peers".into(),
        args: Bencode::Dict(vec![
            (id_key(), Bencode::Bytes(Bytes::copy_from_slice(node_id))),
            (
                info_hash_key(),
                Bencode::Bytes(Bytes::copy_from_slice(info_hash)),
            ),
        ]),
    }
    .to_bytes()
}

/// Build an announce_peer query (BEP 5).
///
/// Creates a KRPC `announce_peer` query that tells a DHT node we are
/// downloading the torrent identified by `info_hash` on the given `port`.
/// Requires a `token` obtained from a previous `get_peers` response.
pub fn build_announce_peer(
    tid: TransactionId, node_id: &[u8; 20], info_hash: &[u8; 20], port: u16, token: &[u8],
) -> Vec<u8> {
    KrpcMessage::Query {
        transaction_id: tid,
        method: "announce_peer".into(),
        args: Bencode::Dict(vec![
            (id_key(), Bencode::Bytes(Bytes::copy_from_slice(node_id))),
            (
                info_hash_key(),
                Bencode::Bytes(Bytes::copy_from_slice(info_hash)),
            ),
            (Bytes::from("port"), Bencode::Integer(port as i64)),
            (token_key(), Bencode::Bytes(Bytes::copy_from_slice(token))),
        ]),
    }
    .to_bytes()
}

// ── Response parsing helpers ─────────────────────────────────────────

/// Parse a ping response.
///
/// Expects a response dict containing `{"id": <20-byte node ID>}`.
///
/// # Errors
///
/// Returns an error if the message is not a response or is missing the `id` field.
pub fn parse_ping_response(msg: &KrpcMessage) -> Result<[u8; 20], Error> {
    match msg {
        KrpcMessage::Response { result, .. } => {
            let node_id = dict_get_bytes(result, b"id").ok_or(Error::new(ErrorKind::Protocol))?;
            let mut id = [0u8; 20];
            let len = std::cmp::min(node_id.len(), 20);
            id[..len].copy_from_slice(&node_id[..len]);
            Ok(id)
        }
        _ => Err(Error::new(ErrorKind::Protocol)),
    }
}

/// Result of a get_peers DHT query (BEP 5).
///
/// Two outcomes are possible:
/// - [`Values`](GetPeersResult::Values): the node returned peer addresses
///   and a token for later `announce_peer` calls
/// - [`Nodes`](GetPeersResult::Nodes): the node returned closer DHT nodes
///   for continued recursive lookup
#[derive(Debug, Clone)]
pub enum GetPeersResult {
    /// Token + list of SocketAddr.
    Values {
        token: Vec<u8>,
        peers: Vec<SocketAddr>,
    },
    /// Closer nodes in compact format.
    Nodes(Vec<super::Node>),
}

/// Parse a get_peers response (BEP 5).
///
/// Handles both possible responses:
/// - `values` key present → returns [`GetPeersResult::Values`] with token and peers
/// - `nodes` key present → returns [`GetPeersResult::Nodes`] with closer nodes
///
/// # Errors
///
/// Returns an error if the message is not a response or contains neither
/// `values` nor `nodes`.
pub fn parse_get_peers_response(msg: &KrpcMessage) -> Result<GetPeersResult, Error> {
    match msg {
        KrpcMessage::Response { result, .. } => {
            let token = dict_get_bytes(result, b"token")
                .map(|b| b.to_vec())
                .ok_or(Error::new(ErrorKind::Protocol))?;

            // Check for "values" field (list of compact peers)
            if let Some(Bencode::List(values)) = dict_get(result, b"values") {
                let mut peers = Vec::new();
                for v in values {
                    if let Bencode::Bytes(b) = v
                        && b.len() == 6
                    {
                        let ip = Ipv4Addr::new(b[0], b[1], b[2], b[3]);
                        let port = u16::from_be_bytes([b[4], b[5]]);
                        peers.push(SocketAddr::new(IpAddr::V4(ip), port));
                    }
                }
                return Ok(GetPeersResult::Values { token, peers });
            }

            // Check for "nodes" field (compact node info)
            if let Some(nodes_bytes) = dict_get_bytes(result, b"nodes") {
                let nodes = parse_compact_nodes(nodes_bytes);
                return Ok(GetPeersResult::Nodes(nodes));
            }

            Err(Error::new(ErrorKind::Protocol))
        }
        _ => Err(Error::new(ErrorKind::Protocol)),
    }
}

/// Parse compact node info (BEP 5).
///
/// Each node is 26 bytes: 20-byte node ID + 4-byte IPv4 address + 2-byte port.
/// Incomplete trailing bytes are silently ignored.
pub fn parse_compact_nodes(data: &[u8]) -> Vec<super::Node> {
    data.chunks_exact(26)
        .map(|chunk| {
            let mut id = [0u8; 20];
            id.copy_from_slice(&chunk[..20]);
            let ip = Ipv4Addr::new(chunk[20], chunk[21], chunk[22], chunk[23]);
            let port = u16::from_be_bytes([chunk[24], chunk[25]]);
            super::Node {
                id,
                addr: SocketAddr::new(IpAddr::V4(ip), port),
            }
        })
        .collect()
}

/// Encode nodes into compact format (BEP 5).
///
/// Each node is 26 bytes: 20-byte node ID + 4-byte IPv4 address + 2-byte port.
/// Returns the concatenated bytes for all nodes.
pub fn encode_compact_nodes(nodes: &[super::Node]) -> Vec<u8> {
    let mut data = Vec::with_capacity(nodes.len() * 26);
    for node in nodes {
        data.extend_from_slice(&node.id);
        let ip = match node.addr.ip() {
            IpAddr::V4(v4) => v4.octets(),
            _ => continue, // skip IPv6 for now
        };
        data.extend_from_slice(&ip);
        data.extend_from_slice(&node.addr.port().to_be_bytes());
    }
    data
}

// ── Response builders ─────────────────────────────────────────────────

/// Build a `ping` response (BEP 5).
pub fn build_ping_response(tid: TransactionId, node_id: &[u8; 20]) -> Vec<u8> {
    KrpcMessage::Response {
        transaction_id: tid,
        result: Bencode::Dict(vec![(
            id_key(),
            Bencode::Bytes(Bytes::copy_from_slice(node_id)),
        )]),
    }
    .to_bytes()
}

/// Build a `find_node` response (BEP 5).
pub fn build_find_node_response(
    tid: TransactionId, node_id: &[u8; 20], nodes: &[super::Node],
) -> Vec<u8> {
    let compact = encode_compact_nodes(nodes);
    KrpcMessage::Response {
        transaction_id: tid,
        result: Bencode::Dict(vec![
            (id_key(), Bencode::Bytes(Bytes::copy_from_slice(node_id))),
            (Bytes::from("nodes"), Bencode::Bytes(Bytes::from(compact))),
        ]),
    }
    .to_bytes()
}

/// Build a `get_peers` response with peer values (BEP 5).
pub fn build_get_peers_response_values(
    tid: TransactionId, node_id: &[u8; 20], token: &[u8], peers: &[SocketAddr],
) -> Vec<u8> {
    let peer_list: Vec<Bencode> = peers
        .iter()
        .filter_map(|addr| match addr.ip() {
            IpAddr::V4(v4) => {
                let mut data = Vec::new();
                data.extend_from_slice(&v4.octets());
                data.extend_from_slice(&addr.port().to_be_bytes());
                Some(Bencode::Bytes(Bytes::from(data)))
            }
            _ => None,
        })
        .collect();
    KrpcMessage::Response {
        transaction_id: tid,
        result: Bencode::Dict(vec![
            (id_key(), Bencode::Bytes(Bytes::copy_from_slice(node_id))),
            (
                Bytes::from("token"),
                Bencode::Bytes(Bytes::copy_from_slice(token)),
            ),
            (Bytes::from("values"), Bencode::List(peer_list)),
        ]),
    }
    .to_bytes()
}

/// Build a `get_peers` response with closer nodes (BEP 5).
pub fn build_get_peers_response_nodes(
    tid: TransactionId, node_id: &[u8; 20], token: &[u8], nodes: &[super::Node],
) -> Vec<u8> {
    let compact = encode_compact_nodes(nodes);
    KrpcMessage::Response {
        transaction_id: tid,
        result: Bencode::Dict(vec![
            (id_key(), Bencode::Bytes(Bytes::copy_from_slice(node_id))),
            (
                Bytes::from("token"),
                Bencode::Bytes(Bytes::copy_from_slice(token)),
            ),
            (Bytes::from("nodes"), Bencode::Bytes(Bytes::from(compact))),
        ]),
    }
    .to_bytes()
}

/// Build a KRPC error response (BEP 5).
pub fn build_error_response(tid: TransactionId, code: i64, message: &str) -> Vec<u8> {
    KrpcMessage::Error {
        transaction_id: tid,
        code,
        message: message.into(),
    }
    .to_bytes()
}

// ── Helpers ──────────────────────────────────────────────────────────

fn t_key() -> Bytes {
    Bytes::from("t")
}
fn y_key() -> Bytes {
    Bytes::from("y")
}
fn q_key() -> Bytes {
    Bytes::from("q")
}
fn a_key() -> Bytes {
    Bytes::from("a")
}
fn r_key() -> Bytes {
    Bytes::from("r")
}
fn e_key() -> Bytes {
    Bytes::from("e")
}
fn id_key() -> Bytes {
    Bytes::from("id")
}
fn target_key() -> Bytes {
    Bytes::from("target")
}
fn info_hash_key() -> Bytes {
    Bytes::from("info_hash")
}
fn token_key() -> Bytes {
    Bytes::from("token")
}

fn dict_get<'a>(val: &'a Bencode, key: &[u8]) -> Option<&'a Bencode> {
    match val {
        Bencode::Dict(entries) => entries
            .iter()
            .find(|(k, _)| k.as_ref() == key)
            .map(|(_, v)| v),
        _ => None,
    }
}

/// Extract a byte-string value from a bencode dictionary by key.
///
/// Returns `None` if the key is not present or the value is not bytes.
pub fn dict_get_bytes<'a>(val: &'a Bencode, key: &[u8]) -> Option<&'a [u8]> {
    match dict_get(val, key)? {
        Bencode::Bytes(b) => Some(b),
        _ => None,
    }
}

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

    #[test]
    fn krpc_ping_roundtrip() {
        let tid = [0xAB, 0xCD];
        let node_id = [0x42u8; 20];
        let bytes = build_ping(tid, &node_id);

        let msg = KrpcMessage::from_bytes(&bytes).unwrap();
        match &msg {
            KrpcMessage::Query {
                transaction_id,
                method,
                ..
            } => {
                assert_eq!(*transaction_id, tid);
                assert_eq!(method, "ping");
            }
            _ => panic!("expected query"),
        }
    }

    #[test]
    fn krpc_find_node_roundtrip() {
        let tid = [0x12, 0x34];
        let node_id = [0x11u8; 20];
        let target = [0x22u8; 20];
        let bytes = build_find_node(tid, &node_id, &target);

        let msg = KrpcMessage::from_bytes(&bytes).unwrap();
        match &msg {
            KrpcMessage::Query { method, .. } => {
                assert_eq!(method, "find_node");
            }
            _ => panic!("expected query"),
        }
    }

    #[test]
    fn krpc_response_roundtrip() {
        let tid = [0xFF, 0xEE];
        let msg = KrpcMessage::Response {
            transaction_id: tid,
            result: Bencode::Dict(vec![(
                Bytes::from("id"),
                Bencode::Bytes(Bytes::copy_from_slice(&[0x55u8; 20])),
            )]),
        };
        let bytes = msg.to_bytes();
        let decoded = KrpcMessage::from_bytes(&bytes).unwrap();
        match decoded {
            KrpcMessage::Response {
                transaction_id,
                result,
            } => {
                assert_eq!(transaction_id, tid);
                let id = dict_get_bytes(&result, b"id").unwrap();
                assert_eq!(id, &[0x55u8; 20]);
            }
            _ => panic!("expected response"),
        }
    }

    #[test]
    fn krpc_error_roundtrip() {
        let msg = KrpcMessage::Error {
            transaction_id: [0x01, 0x02],
            code: 203,
            message: "Server Error".into(),
        };
        let bytes = msg.to_bytes();
        let decoded = KrpcMessage::from_bytes(&bytes).unwrap();
        match decoded {
            KrpcMessage::Error { code, message, .. } => {
                assert_eq!(code, 203);
                assert_eq!(message, "Server Error");
            }
            _ => panic!("expected error"),
        }
    }

    #[test]
    fn test_parse_compact_nodes() {
        let mut data = Vec::new();
        // Node 1: id + 127.0.0.1:6881
        data.extend_from_slice(&[0x01u8; 20]);
        data.extend_from_slice(&[127, 0, 0, 1]);
        data.extend_from_slice(&6881u16.to_be_bytes());
        // Node 2: id + 192.168.1.1:51413
        data.extend_from_slice(&[0x02u8; 20]);
        data.extend_from_slice(&[192, 168, 1, 1]);
        data.extend_from_slice(&51413u16.to_be_bytes());

        let nodes = parse_compact_nodes(&data);
        assert_eq!(nodes.len(), 2);
        assert_eq!(nodes[0].id, [0x01u8; 20]);
        assert_eq!(nodes[0].addr.to_string(), "127.0.0.1:6881");
        assert_eq!(nodes[1].addr.to_string(), "192.168.1.1:51413");
    }

    #[test]
    fn parse_ping_response_valid() {
        let msg = KrpcMessage::Response {
            transaction_id: [0xAB, 0xCD],
            result: Bencode::Dict(vec![(
                Bytes::from("id"),
                Bencode::Bytes(Bytes::copy_from_slice(&[0x42u8; 20])),
            )]),
        };
        let id = parse_ping_response(&msg).unwrap();
        assert_eq!(id, [0x42u8; 20]);
    }

    #[test]
    fn parse_ping_response_not_a_response() {
        let msg = KrpcMessage::Query {
            transaction_id: [0; 2],
            method: "ping".into(),
            args: Bencode::Dict(vec![]),
        };
        assert!(parse_ping_response(&msg).is_err());
    }

    #[test]
    fn parse_get_peers_values() {
        let msg = KrpcMessage::Response {
            transaction_id: [0; 2],
            result: Bencode::Dict(vec![
                (Bytes::from("token"), Bencode::Bytes(Bytes::from("tok"))),
                (
                    Bytes::from("values"),
                    Bencode::List(vec![
                        // compact peer: 6 bytes (127.0.0.1:6881)
                        Bencode::Bytes(Bytes::from(vec![127, 0, 0, 1, 0x1A, 0xE1])),
                    ]),
                ),
            ]),
        };
        match parse_get_peers_response(&msg).unwrap() {
            GetPeersResult::Values { token, peers } => {
                assert_eq!(token, b"tok");
                assert_eq!(peers.len(), 1);
            }
            _ => panic!("expected Values"),
        }
    }

    #[test]
    fn parse_get_peers_nodes() {
        let mut compact = Vec::new();
        compact.extend_from_slice(&[0x01u8; 20]); // node ID
        compact.extend_from_slice(&[10, 0, 0, 1]); // IP
        compact.extend_from_slice(&6881u16.to_be_bytes());

        let msg = KrpcMessage::Response {
            transaction_id: [0; 2],
            result: Bencode::Dict(vec![
                (Bytes::from("token"), Bencode::Bytes(Bytes::from("tok"))),
                (Bytes::from("nodes"), Bencode::Bytes(Bytes::from(compact))),
            ]),
        };
        match parse_get_peers_response(&msg).unwrap() {
            GetPeersResult::Nodes(nodes) => {
                assert_eq!(nodes.len(), 1);
                assert_eq!(nodes[0].addr.to_string(), "10.0.0.1:6881");
            }
            _ => panic!("expected Nodes"),
        }
    }

    #[test]
    fn parse_get_peers_neither_values_nor_nodes() {
        let msg = KrpcMessage::Response {
            transaction_id: [0; 2],
            result: Bencode::Dict(vec![]),
        };
        assert!(parse_get_peers_response(&msg).is_err());
    }

    #[test]
    fn parse_get_peers_non_response() {
        let msg = KrpcMessage::Query {
            transaction_id: [0; 2],
            method: "get_peers".into(),
            args: Bencode::Dict(vec![]),
        };
        assert!(parse_get_peers_response(&msg).is_err());
    }

    #[test]
    fn decode_truncated_krpc() {
        let data = b"d1:t2:ab1:y1:q"; // truncated dict
        assert!(KrpcMessage::from_bytes(data).is_err());
    }

    #[test]
    fn decode_unknown_y_type() {
        // y = 'x' is not valid
        let _ = KrpcMessage::Error {
            transaction_id: [0; 2],
            code: 0,
            message: String::new(),
        };
        // Instead build a valid message and test internal from_bencode directly
        let dict = Bencode::Dict(vec![
            (Bytes::from("t"), Bencode::Bytes(Bytes::from(vec![0, 0]))),
            (Bytes::from("y"), Bencode::Bytes(Bytes::from(&b"x"[..]))),
            (
                Bytes::from("e"),
                Bencode::List(vec![Bencode::Integer(0), Bencode::Bytes(Bytes::from(""))]),
            ),
        ]);
        assert!(KrpcMessage::from_bencode(&dict).is_err());
    }

    #[test]
    fn decode_missing_t_field() {
        let dict = Bencode::Dict(vec![
            (Bytes::from("y"), Bencode::Bytes(Bytes::from(&b"q"[..]))),
            (Bytes::from("q"), Bencode::Bytes(Bytes::from(&b"ping"[..]))),
            (Bytes::from("a"), Bencode::Dict(vec![])),
        ]);
        assert!(KrpcMessage::from_bencode(&dict).is_err());
    }

    #[test]
    fn decode_error_missing_list() {
        let dict = Bencode::Dict(vec![
            (Bytes::from("t"), Bencode::Bytes(Bytes::from(vec![0, 0]))),
            (Bytes::from("y"), Bencode::Bytes(Bytes::from(&b"e"[..]))),
            (Bytes::from("e"), Bencode::Integer(203)), // not a list
        ]);
        assert!(KrpcMessage::from_bencode(&dict).is_err());
    }
}