Skip to content

About

A minimal command-line BitTorrent client written in Go, with parallel piece downloads, SHA-1 checks and live progress.

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Latest commit

 

History

18 Commits

Folders and files

Repository files navigation

BitTorrent-client-Go

Go License: MIT

A BitTorrent client written from scratch in Go. Give it a .torrent file and it finds peers, downloads every piece from them in parallel, checks each piece against its SHA-1 hash and writes the files to disk.

It is about 2,200 lines of Go, tests included. Apart from a bencode parser it only uses the standard library, and it is covered by 29 tests that run without network access.

Why I built it

I wanted to understand what actually happens on the wire when a torrent downloads: how a client finds peers, how two strangers agree they are talking about the same file, and how you trust data that arrives from hundreds of machines you know nothing about. Writing the protocol by hand from BEP 3 was the best way to find out. It was also a good exercise in Go concurrency and in treating every input as hostile.

What it looks like

$ ./bittorrent-client-go -dir ~/Downloads debian.torrent
downloading debian-netinst.iso (754.0 MiB)
   41.37%  312.0 MiB / 754.0 MiB  6.8 MiB/s  peers 27/50  eta 1m05s

The status line updates in place once a second with the progress, speed, number of connected peers and time left. Ctrl+C stops the download cleanly.

How it works

flowchart LR
    A[".torrent file"] -->|bencode parse<br/>SHA-1 of raw info dict| B["torrentfile"]
    B -->|info hash, piece hashes| C["tracker<br/>HTTP announce"]
    C -->|peer list| D["p2p.Download"]
    D --> W1["peer worker 1"]
    D --> W2["peer worker 2"]
    D --> Wn["peer worker N"]
    PM[("piece manager<br/>pending / in progress / done")] <--> W1 & W2 & Wn
    W1 & W2 & Wn -->|verified pieces<br/>WriteAt offset| F["files on disk"]
Loading
  1. Parse the torrent. torrentfile decodes the bencoded file. The info hash is the SHA-1 of the raw bytes of the info dictionary, taken as they appear in the file instead of being decoded and re-encoded, because re-encoding can change the bytes and produce a hash no peer recognises.
  2. Find peers. tracker announces to the HTTP tracker and reads back the peer list in either the compact 6-byte format or the older list of dictionaries.
  3. Download from every peer at once. p2p starts one goroutine per peer. Each one runs the conversation below, asks a shared piece manager for a piece that peer has and nobody else is downloading, and fetches it.
  4. Verify and write. A finished piece is checked against its SHA-1 hash and written straight to its offset in the output. Multi-file torrents go through a writer that maps a torrent offset to the right file with a binary search.

Each worker talks to its peer like this:

sequenceDiagram
    participant C as client
    participant P as peer
    C->>P: handshake (protocol, info hash, peer id)
    P->>C: handshake (must echo the same info hash)
    C->>P: bitfield (empty) + interested
    P->>C: bitfield / have
    P->>C: unchoke
    loop up to 5 requests in flight
        C->>P: request (piece, offset, 16 KiB)
        P->>C: piece (block)
    end
    Note over C: SHA-1 check, then WriteAt
Loading

Design decisions

  • Pipelined requests. A worker keeps up to 5 block requests of 16 KiB in flight instead of waiting for each block, so throughput is not limited by the round-trip time to the peer.
  • Pieces go back in the queue when they fail. If a peer chokes us, drops the connection or sends a piece with the wrong hash, the piece is released and another worker picks it up. One bad peer cannot stall or corrupt the download.
  • An empty bitfield is still sent. Many clients treat a peer that never sends a bitfield as a crawler and never unchoke it, so the client sends an empty one even though it has nothing to share.
  • Bounded memory. Output files are preallocated and every piece is written as soon as it is verified, so memory use is about one piece per connected peer, whatever the size of the torrent.
  • Torrent files are untrusted input. File paths containing .., absolute paths and drive letters are rejected, and the final path is checked again to make sure it is still inside the download folder. Tracker responses are capped at 4 MiB, oversized peer messages are rejected, and every network step has a timeout.
  • Clean cancellation. Everything runs under one context. Ctrl+C, or the last piece arriving, cancels it, which closes every open connection and stops every worker.

Install

Download a binary for Windows, Linux or macOS from the releases page, or install it with Go 1.22 or newer:

go install github.com/Moudjib16/BitTorrent-client-Go@latest

go install names the program BitTorrent-client-Go, after the repository.

Build and run

go build -o bittorrent-client-go .

./bittorrent-client-go ubuntu.torrent
./bittorrent-client-go -dir /downloads ubuntu.torrent

The torrent is downloaded into the directory given with -dir (the current directory by default), inside a folder named after the torrent.

Tests

go test ./...

The tests use a fake peer and a fake tracker, so they need no network access. They cover the handshake (including a wrong info hash), message framing, a peer that sends its bitfield only after unchoking, multi-file writes and path traversal attempts.

Package Coverage
tracker 81.9%
p2p 78.5%
torrentfile 77.4%

Code layout

Package What it does
torrentfile Parses .torrent files, checks file paths and writes the data to disk
tracker Announces to HTTP trackers and parses the peer list
p2p Handshake, peer messages, the piece manager and the download workers
main Command line flags and the status line

Limitations

This is a minimal client, so some things are missing on purpose:

  • UDP trackers (BEP 15) are not supported, only HTTP and HTTPS
  • No DHT and no magnet links
  • It only downloads, it never seeds
  • No resume after a restart and no protocol encryption

What I would add next

  • UDP trackers (BEP 15). Most public torrents list a UDP tracker first, so this would make the client work with far more torrents.
  • Rarest-first piece selection. Pieces are handed out in order today. Picking the rarest piece first is what keeps a swarm healthy.
  • Endgame mode. Request the last few pieces from several peers at once so one slow peer cannot hold up the end of the download.
  • Re-announcing. Use the interval the tracker returns to fetch fresh peers during long downloads.
  • Resume. Hash the pieces already on disk at startup and skip those.
  • DHT and magnet links (BEP 5 and BEP 9).

License

MIT, see LICENSE.

About

A minimal command-line BitTorrent client written in Go, with parallel piece downloads, SHA-1 checks and live progress.

Topics

Resources

Stars

4 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages