Skip to main content

enxame_peer/
lib.rs

1//! The BitTorrent peer wire protocol ([BEP-3]) as a typed AST.
2//!
3//! After the TCP/uTP handshake, two peers exchange a stream of
4//! length-prefixed messages. This crate models that stream as the
5//! pleme-io idiom demands — a **typed [`PeerMessage`] AST**
6//! (parse-don't-validate) with a [`PeerMessage::parse`] decoder and a
7//! typed-emission [`PeerMessage::encode`] (the framing is built from
8//! typed integers and byte literals, never a `format!()` of the wire —
9//! the ★★ TYPED EMISSION rule). It is the exact shape proven in mado's
10//! `CsiCommand` dispatch: bytes → typed message → interpret.
11//!
12//! Frame layout: `<u32 length><u8 id><payload>`; a zero-length frame is
13//! the [`PeerMessage::KeepAlive`] (no id byte). The [`Handshake`] that
14//! precedes the stream has its own fixed layout.
15//!
16//! [BEP-3]: https://www.bittorrent.org/beps/bep_0003.html
17
18#![forbid(unsafe_code)]
19
20/// The fixed protocol identifier string in the handshake (`pstr`).
21pub const PROTOCOL: &[u8; 19] = b"BitTorrent protocol";
22
23/// A peer's 20-byte id.
24pub type PeerId = [u8; 20];
25/// A 20-byte info-hash (kept local so this crate has no metainfo dep).
26pub type InfoHash = [u8; 20];
27
28/// The opening handshake: `<19><"BitTorrent protocol"><8 reserved><20
29/// info_hash><20 peer_id>` — 68 bytes total.
30#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct Handshake {
32    /// 8 reserved bytes — extension bits (BEP-10 bit 0x10 in byte 5,
33    /// DHT bit 0x01 in byte 7, Fast bit 0x04 in byte 7).
34    pub reserved: [u8; 8],
35    /// The torrent's info-hash.
36    pub info_hash: InfoHash,
37    /// The remote peer's id.
38    pub peer_id: PeerId,
39}
40
41impl Handshake {
42    /// Total on-wire size of a handshake.
43    pub const LEN: usize = 68;
44
45    /// A handshake with all reserved bits clear.
46    #[must_use]
47    pub fn new(info_hash: InfoHash, peer_id: PeerId) -> Self {
48        Self { reserved: [0; 8], info_hash, peer_id }
49    }
50
51    /// Encode to the 68 wire bytes (typed emission).
52    #[must_use]
53    pub fn encode(&self) -> [u8; Self::LEN] {
54        let mut buf = [0u8; Self::LEN];
55        buf[0] = 19;
56        buf[1..20].copy_from_slice(PROTOCOL);
57        buf[20..28].copy_from_slice(&self.reserved);
58        buf[28..48].copy_from_slice(&self.info_hash);
59        buf[48..68].copy_from_slice(&self.peer_id);
60        buf
61    }
62
63    /// Parse a 68-byte handshake.
64    ///
65    /// # Errors
66    /// [`ProtocolError::ShortHandshake`] if `< 68` bytes;
67    /// [`ProtocolError::BadProtocol`] if the `pstrlen`/`pstr` aren't the
68    /// BEP-3 constants.
69    pub fn parse(input: &[u8]) -> Result<Self, ProtocolError> {
70        if input.len() < Self::LEN {
71            return Err(ProtocolError::ShortHandshake { got: input.len() });
72        }
73        if input[0] != 19 || &input[1..20] != PROTOCOL.as_slice() {
74            return Err(ProtocolError::BadProtocol);
75        }
76        let mut reserved = [0u8; 8];
77        reserved.copy_from_slice(&input[20..28]);
78        let mut info_hash = [0u8; 20];
79        info_hash.copy_from_slice(&input[28..48]);
80        let mut peer_id = [0u8; 20];
81        peer_id.copy_from_slice(&input[48..68]);
82        Ok(Self { reserved, info_hash, peer_id })
83    }
84
85    /// Whether the remote advertised the BEP-10 extension protocol.
86    #[must_use]
87    pub fn supports_extensions(&self) -> bool {
88        self.reserved[5] & 0x10 != 0
89    }
90
91    /// Whether the remote advertised DHT (BEP-5).
92    #[must_use]
93    pub fn supports_dht(&self) -> bool {
94        self.reserved[7] & 0x01 != 0
95    }
96}
97
98/// A request/cancel block region (`index`, `begin`, `length`) — a
99/// sub-range of a piece.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct Block {
102    /// Piece index.
103    pub index: u32,
104    /// Byte offset within the piece.
105    pub begin: u32,
106    /// Block length in bytes.
107    pub length: u32,
108}
109
110/// The typed peer-wire message AST (BEP-3 + the BEP-5 `Port` and BEP-10
111/// `Extended` messages). Unknown ids are kept (not dropped) as
112/// [`PeerMessage::Unknown`] so a forward-compatible peer round-trips.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum PeerMessage {
115    /// Zero-length frame — a liveness ping.
116    KeepAlive,
117    /// id 0 — sender is choking the receiver.
118    Choke,
119    /// id 1 — sender is no longer choking.
120    Unchoke,
121    /// id 2 — sender is interested.
122    Interested,
123    /// id 3 — sender is not interested.
124    NotInterested,
125    /// id 4 — sender has the given piece.
126    Have(u32),
127    /// id 5 — the sender's piece bitfield.
128    Bitfield(Vec<u8>),
129    /// id 6 — request a block.
130    Request(Block),
131    /// id 7 — a block payload (`index`, `begin`, data).
132    Piece { index: u32, begin: u32, data: Vec<u8> },
133    /// id 8 — cancel a previously-requested block.
134    Cancel(Block),
135    /// id 9 — the sender's DHT UDP port (BEP-5).
136    Port(u16),
137    /// id 20 — the BEP-10 extension protocol (`ext_id` + bencoded/raw
138    /// payload). The payload is kept opaque here; `enxame-ext` types it.
139    Extended { ext_id: u8, payload: Vec<u8> },
140    /// An id this crate doesn't model — kept verbatim for round-trip.
141    Unknown { id: u8, payload: Vec<u8> },
142}
143
144/// A typed framing/decoding failure.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub enum ProtocolError {
147    /// Fewer than 68 handshake bytes.
148    ShortHandshake { got: usize },
149    /// Handshake `pstrlen`/`pstr` weren't the BEP-3 constants.
150    BadProtocol,
151    /// A fixed-shape message (`Have`/`Request`/`Piece`/…) had the wrong
152    /// payload length.
153    BadPayloadLength { id: u8, got: usize },
154}
155
156impl std::fmt::Display for ProtocolError {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        match self {
159            ProtocolError::ShortHandshake { got } => {
160                write!(f, "handshake too short: {got} < 68 bytes")
161            }
162            ProtocolError::BadProtocol => write!(f, "handshake pstr is not 'BitTorrent protocol'"),
163            ProtocolError::BadPayloadLength { id, got } => {
164                write!(f, "message id {id} has wrong payload length {got}")
165            }
166        }
167    }
168}
169
170impl std::error::Error for ProtocolError {}
171
172impl PeerMessage {
173    /// Decode one message from its **payload** — the bytes *after* the
174    /// 4-byte length prefix has been read and the frame body collected.
175    /// An empty body is a [`PeerMessage::KeepAlive`]. (Framing — reading
176    /// the length prefix off a stream — is [`decode_frame`].)
177    ///
178    /// # Errors
179    /// [`ProtocolError::BadPayloadLength`] for a fixed-shape message
180    /// whose payload size is wrong.
181    pub fn from_body(body: &[u8]) -> Result<Self, ProtocolError> {
182        let Some((&id, payload)) = body.split_first() else {
183            return Ok(PeerMessage::KeepAlive);
184        };
185        let exact = |want: usize| -> Result<(), ProtocolError> {
186            if payload.len() == want {
187                Ok(())
188            } else {
189                Err(ProtocolError::BadPayloadLength { id, got: payload.len() })
190            }
191        };
192        Ok(match id {
193            0 => {
194                exact(0)?;
195                PeerMessage::Choke
196            }
197            1 => {
198                exact(0)?;
199                PeerMessage::Unchoke
200            }
201            2 => {
202                exact(0)?;
203                PeerMessage::Interested
204            }
205            3 => {
206                exact(0)?;
207                PeerMessage::NotInterested
208            }
209            4 => {
210                exact(4)?;
211                PeerMessage::Have(read_u32(payload, 0))
212            }
213            5 => PeerMessage::Bitfield(payload.to_vec()),
214            6 => {
215                exact(12)?;
216                PeerMessage::Request(read_block(payload))
217            }
218            7 => {
219                if payload.len() < 8 {
220                    return Err(ProtocolError::BadPayloadLength { id, got: payload.len() });
221                }
222                PeerMessage::Piece {
223                    index: read_u32(payload, 0),
224                    begin: read_u32(payload, 4),
225                    data: payload[8..].to_vec(),
226                }
227            }
228            8 => {
229                exact(12)?;
230                PeerMessage::Cancel(read_block(payload))
231            }
232            9 => {
233                exact(2)?;
234                PeerMessage::Port(u16::from(payload[0]) << 8 | u16::from(payload[1]))
235            }
236            20 => {
237                let Some((&ext_id, rest)) = payload.split_first() else {
238                    return Err(ProtocolError::BadPayloadLength { id, got: 0 });
239                };
240                PeerMessage::Extended { ext_id, payload: rest.to_vec() }
241            }
242            other => PeerMessage::Unknown { id: other, payload: payload.to_vec() },
243        })
244    }
245
246    /// Encode to a complete length-prefixed wire frame (typed emission:
247    /// the length prefix and all integers are written as big-endian
248    /// bytes, never a `format!()`).
249    #[must_use]
250    pub fn encode(&self) -> Vec<u8> {
251        let mut body = Vec::new();
252        match self {
253            PeerMessage::KeepAlive => {} // empty body → length 0
254            PeerMessage::Choke => body.push(0),
255            PeerMessage::Unchoke => body.push(1),
256            PeerMessage::Interested => body.push(2),
257            PeerMessage::NotInterested => body.push(3),
258            PeerMessage::Have(idx) => {
259                body.push(4);
260                body.extend_from_slice(&idx.to_be_bytes());
261            }
262            PeerMessage::Bitfield(bits) => {
263                body.push(5);
264                body.extend_from_slice(bits);
265            }
266            PeerMessage::Request(b) => {
267                body.push(6);
268                push_block(&mut body, b);
269            }
270            PeerMessage::Piece { index, begin, data } => {
271                body.push(7);
272                body.extend_from_slice(&index.to_be_bytes());
273                body.extend_from_slice(&begin.to_be_bytes());
274                body.extend_from_slice(data);
275            }
276            PeerMessage::Cancel(b) => {
277                body.push(8);
278                push_block(&mut body, b);
279            }
280            PeerMessage::Port(port) => {
281                body.push(9);
282                body.extend_from_slice(&port.to_be_bytes());
283            }
284            PeerMessage::Extended { ext_id, payload } => {
285                body.push(20);
286                body.push(*ext_id);
287                body.extend_from_slice(payload);
288            }
289            PeerMessage::Unknown { id, payload } => {
290                body.push(*id);
291                body.extend_from_slice(payload);
292            }
293        }
294        let len = u32::try_from(body.len()).expect("a peer message body fits u32");
295        let mut frame = Vec::with_capacity(4 + body.len());
296        frame.extend_from_slice(&len.to_be_bytes());
297        frame.extend_from_slice(&body);
298        frame
299    }
300}
301
302/// Decode one complete frame from the front of a buffer: read the 4-byte
303/// big-endian length prefix, and if that many body bytes are present,
304/// return the parsed [`PeerMessage`] and the number of bytes consumed.
305/// `Ok(None)` means "need more bytes" (the frame isn't complete yet) —
306/// the caller keeps buffering. This is the streaming framing seam.
307///
308/// # Errors
309/// Any [`ProtocolError`] from decoding a complete frame's body.
310pub fn decode_frame(buf: &[u8]) -> Result<Option<(PeerMessage, usize)>, ProtocolError> {
311    if buf.len() < 4 {
312        return Ok(None);
313    }
314    let len = read_u32(buf, 0) as usize;
315    let total = 4 + len;
316    if buf.len() < total {
317        return Ok(None);
318    }
319    let msg = PeerMessage::from_body(&buf[4..total])?;
320    Ok(Some((msg, total)))
321}
322
323fn read_u32(b: &[u8], at: usize) -> u32 {
324    u32::from_be_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]])
325}
326
327fn read_block(p: &[u8]) -> Block {
328    Block { index: read_u32(p, 0), begin: read_u32(p, 4), length: read_u32(p, 8) }
329}
330
331fn push_block(out: &mut Vec<u8>, b: &Block) {
332    out.extend_from_slice(&b.index.to_be_bytes());
333    out.extend_from_slice(&b.begin.to_be_bytes());
334    out.extend_from_slice(&b.length.to_be_bytes());
335}
336
337#[cfg(test)]
338mod tests {
339    use super::*;
340
341    #[test]
342    fn handshake_round_trips() {
343        let hs = Handshake::new([7u8; 20], [9u8; 20]);
344        let bytes = hs.encode();
345        assert_eq!(bytes.len(), Handshake::LEN);
346        assert_eq!(Handshake::parse(&bytes).unwrap(), hs);
347    }
348
349    #[test]
350    fn handshake_extension_and_dht_bits() {
351        let mut hs = Handshake::new([0u8; 20], [0u8; 20]);
352        hs.reserved[5] = 0x10;
353        hs.reserved[7] = 0x01;
354        assert!(hs.supports_extensions());
355        assert!(hs.supports_dht());
356        let parsed = Handshake::parse(&hs.encode()).unwrap();
357        assert!(parsed.supports_extensions() && parsed.supports_dht());
358    }
359
360    #[test]
361    fn keepalive_is_a_zero_length_frame() {
362        assert_eq!(PeerMessage::KeepAlive.encode(), vec![0, 0, 0, 0]);
363        assert_eq!(decode_frame(&[0, 0, 0, 0]).unwrap(), Some((PeerMessage::KeepAlive, 4)));
364    }
365
366    #[test]
367    fn fixed_messages_round_trip_through_frames() {
368        let msgs = [
369            PeerMessage::Choke,
370            PeerMessage::Unchoke,
371            PeerMessage::Interested,
372            PeerMessage::NotInterested,
373            PeerMessage::Have(0x0102_0304),
374            PeerMessage::Request(Block { index: 1, begin: 2, length: 16384 }),
375            PeerMessage::Cancel(Block { index: 9, begin: 8, length: 7 }),
376            PeerMessage::Port(6881),
377        ];
378        for m in msgs {
379            let frame = m.encode();
380            assert_eq!(decode_frame(&frame).unwrap(), Some((m.clone(), frame.len())));
381        }
382    }
383
384    #[test]
385    fn bitfield_and_piece_and_extended_round_trip() {
386        for m in [
387            PeerMessage::Bitfield(vec![0xff, 0x80]),
388            PeerMessage::Piece { index: 3, begin: 16384, data: vec![1, 2, 3, 4, 5] },
389            PeerMessage::Extended { ext_id: 1, payload: b"d1:md".to_vec() },
390            PeerMessage::Unknown { id: 200, payload: vec![9, 9] },
391        ] {
392            let frame = m.encode();
393            assert_eq!(decode_frame(&frame).unwrap(), Some((m.clone(), frame.len())));
394        }
395    }
396
397    #[test]
398    fn partial_frames_ask_for_more() {
399        let frame = PeerMessage::Have(42).encode(); // 4 len + 5 body = 9 bytes
400        assert_eq!(decode_frame(&frame[..3]).unwrap(), None); // < length prefix
401        assert_eq!(decode_frame(&frame[..7]).unwrap(), None); // body incomplete
402        assert!(decode_frame(&frame).unwrap().is_some());
403    }
404
405    #[test]
406    fn wrong_payload_lengths_are_rejected() {
407        // Have with a 3-byte payload (id 4 + 2 bytes → body len 3)
408        let bad = [0, 0, 0, 3, 4, 1, 2];
409        assert!(matches!(
410            decode_frame(&bad),
411            Err(ProtocolError::BadPayloadLength { id: 4, .. })
412        ));
413    }
414
415    proptest::proptest! {
416        #[test]
417        fn any_message_round_trips(m in arb_msg()) {
418            let frame = m.encode();
419            let (decoded, consumed) = decode_frame(&frame).unwrap().unwrap();
420            proptest::prop_assert_eq!(decoded, m);
421            proptest::prop_assert_eq!(consumed, frame.len());
422        }
423    }
424
425    fn arb_msg() -> impl proptest::strategy::Strategy<Value = PeerMessage> {
426        use proptest::collection::vec;
427        use proptest::prelude::*;
428        let block = (any::<u32>(), any::<u32>(), any::<u32>())
429            .prop_map(|(index, begin, length)| Block { index, begin, length });
430        prop_oneof![
431            Just(PeerMessage::KeepAlive),
432            Just(PeerMessage::Choke),
433            Just(PeerMessage::Unchoke),
434            Just(PeerMessage::Interested),
435            Just(PeerMessage::NotInterested),
436            any::<u32>().prop_map(PeerMessage::Have),
437            vec(any::<u8>(), 0..32).prop_map(PeerMessage::Bitfield),
438            block.clone().prop_map(PeerMessage::Request),
439            (any::<u32>(), any::<u32>(), vec(any::<u8>(), 0..64))
440                .prop_map(|(index, begin, data)| PeerMessage::Piece { index, begin, data }),
441            block.prop_map(PeerMessage::Cancel),
442            any::<u16>().prop_map(PeerMessage::Port),
443            (any::<u8>(), vec(any::<u8>(), 0..32))
444                .prop_map(|(ext_id, payload)| PeerMessage::Extended { ext_id, payload }),
445        ]
446    }
447}