BitTorrent Client
Build a BitTorrent Client with go to parse .torrent files
Go Code
🚀 Overview
This project is a fully functional BitTorrent client built from scratch using Go. Rather than using high-level libraries, I implemented the core protocol layers—from parsing bencoded data to managing peer-to-peer TCP connections and verifying file integrity.
🛠Technical Details
- Bencode Parsing
BitTorrent metadata (the .torrent file) is stored in a format called Bencode. I built a parser to map these recursive structures (integers, strings, lists, and dictionaries) into Go structs. Used Go's interface and reflection principles to handle the dynamic nature of bencoded data.
- Concurrency with Goroutines and Channels
The "magic" of BitTorrent is downloading different pieces of a file from different peers simultaneously. The Worker Pool: I implemented a worker pattern where each peer connection runs in its own Goroutine. Work Queue: Pieces are distributed via a workQueue channel. If a peer drops or a piece fails a hash check, the piece is sent back to the channel to be retried by another worker.
- Bitfield and Piece Management
To keep track of which parts of the file I have versus what the peers have, I implemented a Bitfield data structure. This involves bitwise operations to efficiently check and set progress. Integrity: Every downloaded piece is hashed using SHA-1 and compared against the info-hash in the torrent file to prevent data corruption.
- TCP Peer Wire Protocol
I implemented the low-level handshake and messaging protocol: Message Types: Handshaking, Choking/Unchoking, Interested, and Requesting/Receiving blocks. Flow Control: Managed the state machine of each peer connection to ensure we only request data when "Unchoked."
🔧 Challenges & Lessons
Network Reliability: Dealing with flaky TCP connections taught me the importance of robust error handling and timeouts in Go. Binary Math: Working with big-endian integers and byte slices deepened my understanding of how data is actually transmitted over the wire. Resource Optimization: Balancing the number of active goroutines to maximize throughput without hitting system file descriptor limits.
📖 Usage
Only provides a CLI
torrent archlinux.iso.torrent
💻 Tech Stack
Language: Go
Concepts: TCP Networking, Binary Protocols, SHA-1 Hashing, Concurrency Patterns, Bencode.