Just enough BitTorrent client to download ubuntu.iso
It is small for educational purposes.
The files are numbered so that you can read them in order and learn.
It does not support DHT, magnet links, UDP trackers, peer exchange, encryption, file selection, or uploading pieces to other peers.
Real BitTorrent clients do much more, and those features are useful, but they are not needed to understand the protocol or to download this Ubuntu torrent. This project keeps only the path from torrent metadata to verified bytes on disk.
On startup, PieceStore opens the output file or files. If they already contain
data, the client reads each piece and hashes it against the torrent metadata.
Matching pieces are marked complete and skipped. Missing or corrupt pieces are
downloaded again.
This is why a BitTorrent client can stop and restart safely. The .torrent
file is the source of truth, not the local file size.
bun install
bun run typecheck
bun test
bun run src/09-main.ts ubuntu.torrent --out downloads --peers 8The download is written to:
downloads/ubuntu-26.04-live-server-amd64.iso
The client creates the output file at its final size, so it may look like a 2.7 GiB file before every byte has arrived. Each piece is written only after its SHA-1 hash matches the torrent metadata.
src/01-bytes.ts Work with byte-oriented BitTorrent values.
src/02-bencode.ts Parse bencoded values and preserve raw byte spans.
src/03-torrent.ts Read torrent metadata and compute the info hash.
src/04-tracker.ts Announce to HTTP trackers and parse compact peers.
src/05-peer.ts Speak the TCP peer wire protocol.
src/06-pieces.ts Track piece completion, hashing, writes, and resume.
src/07-download.ts Coordinate trackers, peers, requests, and progress.
src/08-cli.ts Parse CLI options and print usage.
src/09-main.ts Read the torrent file and start the download.
bun run typecheck runs TypeScript in strict mode. The tests cover the bencode
parser, the included Ubuntu torrent metadata, multi-file layout mapping, a local
peer-wire exchange, and a complete local tracker-to-peer download.