BitTorrent is a good protocol to study because it is small enough to implement and it touches a lot: a custom encoding, a file format, two tracker protocols (one over HTTP, one over UDP), a binary peer protocol over TCP, hashing, and a design built on the idea that you cannot trust the other side.
bittorrent is my learning project on it: a BitTorrent client and tracker written from scratch in Go, using only the standard library. Everything in the README's walkthrough runs on localhost with content you create yourself, and the tests never touch a real tracker or torrent. This article describes the parts, how to run them, and what each one taught me.
What it does
The project is split into six packages, from the bottom up:
-
bencode: the BEP 3 encoding, with access to the raw bytes of a dictionary value. That raw access is how the info hash is computed. -
metainfo: parsing and creating.torrentfiles, single-file and multi-file, with announce-list (BEP 12). -
tracker: an HTTP tracker client (compact and dictionary peer lists, BEP 23), a UDP tracker client (BEP 15: connect, announce, retransmission with backoff), and an in-memory tracker server for both. -
peer: the peer wire protocol: the handshake, length-prefixed messages (choke, unchoke, interested, have, bitfield, request, piece, cancel) and bitfields. -
storage: maps the torrent's flat byte space onto its files, so a piece that spans several files is one read or write. -
torrent: the engine. It announces, dials and accepts peers, downloads pieces with pipelined block requests, verifies each one with SHA-1, sendshaveto everyone, and serves the pieces it has. Existing data is re-checked at start, so downloads resume and complete files seed.
The engine's shape fits in a few lines:
Run ─┬─ announce loop: every tracker, every interval → dial new peers
├─ accept loop: incoming peers
└─ per peer:
handshake (info hash must match, not ourselves)
→ send our bitfield
→ reader goroutine: choke/unchoke, have/bitfield, serve requests,
hand piece blocks to the downloader
→ downloader: interested → wait for unchoke
pick a random missing piece the peer has (not in
progress elsewhere) → keep Pipeline (8) block
requests in flight → SHA-1 → write → have to all
bad hash: release the piece, drop the peer after 3
What I built from scratch, and what it teaches
The info hash must come from the original bytes. A torrent is identified by the SHA-1 of its info dictionary. The tempting implementation is to decode the file, re-encode the info dictionary and hash that. It is wrong: the hash must be the SHA-1 of the original bytes, not of a re-encoding. That is why the bencode decoder gives access to the raw bytes of a dictionary value.
Framing on TCP and UDP. The peer protocol is length-prefixed messages over TCP. The UDP tracker protocol adds something TCP gives you for free: a connection ID. The client first asks for an ID and then uses it in the announce. The reason is to stop spoofed-source amplification, where someone sends requests with a forged source address so the replies hit a victim. The client also retransmits with backoff, because UDP packets get lost.
Throughput versus latency. Pieces are downloaded in 16 KiB blocks. If you send one request and wait for the block before sending the next, your speed is capped by the round trip time. Keeping several requests in flight (pipelining) fills the pipe. The engine keeps 8 block requests in flight. One of the tests proves it with a separate seeder, written in the test, that answers slowly.
Distrust of peers. Every piece is verified with SHA-1 before it is written. On a bad hash the piece is released, and a peer that keeps sending bad data is dropped after 3 failures. Message sizes and bitfields are bounds-checked. And file paths inside a .torrent cannot escape the download directory: path traversal is rejected when the file is parsed.
Files are a detail of storage. The protocol sees one flat sequence of bytes cut into pieces. The storage package maps that space onto the real files, so a piece that crosses a file boundary is still a single read or write for the engine.
How to use it
Install the bt binary with Go:
go install github.com/AbdeldjalilChougui/bittorrent/cmd/bt@latest
Then run the full loop on localhost, with a file you generate yourself:
go build -o bt ./cmd/bt
head -c 5000000 /dev/urandom > demo.bin
./bt tracker -http 127.0.0.1:6969 -udp 127.0.0.1:6969 &
./bt create -announce udp://127.0.0.1:6969,http://127.0.0.1:6969/announce demo.bin
./bt info demo.bin.torrent
./bt seed -dir . demo.bin.torrent &
./bt download -dir /tmp/out demo.bin.torrent
cmp demo.bin /tmp/out/demo.bin
This starts a tracker, creates a .torrent for a random 5 MB file, seeds it, downloads it into another directory and compares the two files. download -seed keeps the downloader running as a seeder, and -v logs peer and tracker errors.
How it is tested
go test -race ./...
All content is generated by the tests and every socket is on 127.0.0.1. The lower packages have focused tests: bencode decoding and its error cases (leading zeros, -0, truncation, duplicate keys, nesting depth) plus a fuzz test, torrent creation and parsing with cross-file piece hashes, HTTP and UDP announces against the local tracker including retransmission when the server drops packets, and reads and writes across file boundaries.
The end-to-end tests of the engine are the interesting ones:
- a single-file download found through the HTTP tracker, served by the slow test seeder, which shows that requests are pipelined;
- a multi-file download through the UDP tracker with one peer that corrupts every block and one honest peer: hash failures are detected and the files still come out right;
- resume: only the missing pieces are requested;
- a swarm of library peers: A seeds, B downloads from A, A leaves, and C downloads from B.
Things to know
This is a learning project. The README lists what is missing compared with a real client:
- No piece-picking strategy beyond random. No rarest-first and no endgame mode, so the last piece can be slow on a slow peer.
-
No choking algorithm. Every interested peer is unchoked, with no tit-for-tat or optimistic unchoke. Upload slots are unlimited up to
MaxPeers. - One piece per peer at a time; pipelining is within a piece.
- No DHT, PEX, magnet links or metadata exchange (BEP 9/10), extension protocol, encryption (MSE/PE), µTP, or IPv6 peers in UDP announces to IPv4 trackers.
- Requests are served synchronously from disk, and
cancelis accepted but has nothing to cancel. - The tracker server is in-memory, with no scrape endpoint and no access control. It is for local testing.
- The UDP tracker client starts at a 2 s timeout instead of BEP 15's 15 s.
And one line from the README that I repeat as it is: only use it for content you are allowed to share.
What I learned
The strongest lesson is how much of the design is defensive. The protocol assumes that any peer may be broken or hostile, so nothing is accepted without a check: the hash of every piece, the size of every message, every path in the metainfo. Writing the test with a peer that corrupts every block, and watching the download still finish correctly from the honest peer, made that concrete.
The second is the raw-bytes rule for the info hash. It is a general point about hashing structured data: hash the bytes you received, not your interpretation of them.
The third is that the missing features are the ones that make real swarms work well. Random piece selection and unchoking everybody are fine between three processes on localhost. Rarest-first and tit-for-tat exist because a real swarm is not that friendly.
Get the code
The source and the tests are on GitHub: https://github.com/AbdeldjalilChougui/bittorrent. It is MIT licensed.
Originally published at abdeldjalilchougui.biz.
Top comments (0)