Skip to content

wsoule/torrent-client

Repository files navigation

BitTorrent Client in Go

A functional BitTorrent client built from scratch in Go, capable of downloading files from the BitTorrent network using the peer-to-peer protocol.

Features

  • Torrent file parsing - Reads and decodes .torrent files using Bencode format
  • Torrent file creation - Generates .torrent files from any file
  • Tracker communication - Contacts HTTP trackers to discover peers
  • Peer wire protocol - Implements the BitTorrent peer protocol including handshakes, bitfields, and piece exchange
  • Concurrent downloads - Downloads from multiple peers simultaneously using Go goroutines
  • Piece verification - Validates downloaded pieces using SHA-1 hashes
  • Automatic retry - Handles connection failures and retries with different peers

Project Structure

torrent-client/
├── main.go              # CLI interface
├── torrentfile/
│   └── torrentfile.go   # .torrent file parsing and creation
├── tracker/
│   └── tracker.go       # Tracker communication and peer discovery
└── p2p/
    ├── p2p.go           # Peer connections and piece downloading
    ├── message.go       # BitTorrent message encoding/decoding
    └── download.go      # Download orchestration with work queue

Installation

# Clone the repository
git clone <your-repo-url>
cd torrent-client

# Initialize Go module
go mod init torrent-client

# Install dependencies
go get github.com/jackpal/bencode-go

Usage

Create a torrent file

go run main.go create <file-path> <tracker-url>

Example:

go run main.go create photo.png http://tracker.example.com:6969/announce

Parse a torrent file

go run main.go parse <torrent-file>

Example:

go run main.go parse debian.torrent

Get peers for a torrent

go run main.go peers <torrent-file>

Download a single piece (for testing)

go run main.go download-piece <torrent-file> <piece-index>

Example:

go run main.go download-piece debian.torrent 0

Download the complete file

go run main.go download <torrent-file> <output-path>

Example:

go run main.go download debian.torrent debian.iso

How It Works

1. Parsing Torrent Files

The client decodes .torrent files written in Bencode format, extracting:

  • File metadata (name, size, piece length)
  • SHA-1 hashes for each piece
  • Tracker URL
  • Info hash (unique identifier for the torrent)

2. Discovering Peers

The client contacts the tracker via HTTP with the info hash and receives a list of peers (IP addresses and ports) that have the file.

3. Connecting to Peers

For each peer:

  • Establishes a TCP connection
  • Performs a BitTorrent handshake
  • Exchanges bitfields (which pieces each peer has)
  • Sends "interested" message

4. Downloading Pieces

The client uses a work queue pattern with Go concurrency:

  • Creates a queue of all pieces to download
  • Spawns a goroutine (worker) for each peer
  • Workers pull pieces from the queue and download them
  • Each piece is split into 16KB blocks for efficient transfer
  • Downloaded pieces are verified against their SHA-1 hash

5. Assembling the File

As pieces complete, they're written to the correct position in the output file, regardless of download order.

Technical Highlights

Concurrency

  • Uses Go channels for communication between goroutines
  • Work queue pattern ensures efficient distribution of download tasks
  • Multiple peers download simultaneously without explicit synchronization

Error Handling

  • Automatically retries failed pieces with different peers
  • Detects and exits workers with broken connections
  • Handles out-of-order piece delivery
  • Gracefully handles keep-alive messages and connection timeouts

Binary Protocol Implementation

  • Custom encoding/decoding of BitTorrent wire protocol messages
  • Efficient parsing of compact peer lists (6 bytes per peer)
  • Bitfield manipulation for tracking piece availability

Learning Resources

This project was built as a learning exercise to understand:

  • BitTorrent protocol specification
  • Go concurrency patterns (goroutines and channels)
  • Network programming and TCP/IP
  • Binary data parsing and encoding
  • Peer-to-peer architecture

Limitations

  • Only supports single-file torrents (not multi-file)
  • Uses HTTP trackers only (no DHT or magnet links)
  • No upload functionality (download only)
  • No support for encrypted connections
  • Does not persist download state (can't resume)

Future Enhancements

  • DHT support for trackerless torrents
  • Magnet link support
  • Multi-file torrent support
  • Upload/seeding capability
  • Resume incomplete downloads
  • Protocol encryption
  • Web UI for monitoring downloads

License

MIT

Acknowledgments

Inspired by the BitTorrent protocol specification and various educational implementations of BitTorrent clients.


Note: This is an educational project. For production use, consider battle-tested clients like qBittorrent or Transmission.

About

BitTorrent Client in Go - Full implementation of the BitTorrent protocol demonstrating distributed systems concepts, peer-to-peer networking, concurrent programming patterns, and binary protocol parsing.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages