Skip to content
rahul-singh92Public

About

A torrent client for downloading torrent files.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

BitStream

BitStream is a lightweight, efficient BitTorrent client designed for downloading torrent files.

BitTorrent Protocol Overview

To understand how BitStream operates, the core BitTorrent mechanics can be broken down into two main phases:

  1. Tracker Discovery & Swarm Registration
    To begin a download, the client sends a request to a central server called a tracker, specifying the exact files it intends to download. The tracker responds with a curated list of active peers (IP addresses of other users hosting the file). By making this request, the client is automatically added to the tracker's list, allowing other network participants to discover and download pieces from it.

  2. Direct Peer-to-Peer Communication
    Once the client receives the peer list, it bypasses the tracker and connects directly to those users. The client and peers exchange structured network messages to declare which file pieces they currently hold. Based on this mutual availability data, the client requests missing pieces and begins the downloading process.


Bencoding (Data Format)

BitTorrent uses a terse data serialization format called Bencoding to structure .torrent files and tracker network messages. It supports four data types:

  • Byte Strings (<length>:<data>):
    • Example: 4:spam → "spam"
  • Integers (i<number>e): Signed 64-bit integers with no leading zeros.
    • Example: i3e → 3 (or i-3e → -3)
    • ⚠️ Invalid Encodings Note: Negative zero (i-0e) and numbers with leading zeros (like i03e) are strictly invalid. The only valid representation of zero is i0e.
  • Lists (l<values>e): Can contain any bencoded types.
    • Example: li3e4:spame → [3, "spam"]
  • Dictionaries (d<key><value>e): Keys must be bencoded strings and appear in sorted binary order.
    • Example: d3:cow3:mooe → {"cow": "moo"}

Metainfo File (.torrent) Structure

All data in a .torrent file is a bencoded dictionary. It contains the core metadata required to connect to the swarm, locate files, and verify data integrity.

Root Dictionary Keys

Key Type Description
info Dictionary Core file metadata (see below).
announce String The tracker's main URL.
announce-list List (Optional) Backup or alternate tracker URLs.
creation date Integer (Optional) UNIX epoch timestamp of creation.
comment / created by String (Optional) Free-form author text and program name.

The info Dictionary

The info dictionary describes the actual files being shared. It supports two structural modes depending on whether the torrent is for a single file or a folder.

Common Fields:

  • piece length: Size of each chunk in bytes (typically a power of 2, like 256 KB or 512 KB).
  • pieces: A single, continuous byte string containing the concatenated 20-byte SHA1 hashes for every piece.
  • private: (Optional) If set to 1, the client must restrict peer discovery strictly to the tracker (disabling DHT/PEX).

Mode-Specific Fields:

Mode Required Fields
Single File name (the filename) and length (file size in bytes).
Multiple File name (the root directory name) and files (a list of dictionaries containing the length and path for each individual file).

Note on Pieces: For multi-file torrents, files are treated as one continuous data stream when generating piece boundaries. The final piece is always irregular in size, and pieces can overlap file boundaries.


Tracker Announce Protocol (HTTP)

When the client communicates with an HTTP tracker to announce its presence and request peers, it passes specific parameters and receives a bencoded dictionary in response.

Request Parameters

Key parameters sent by the client to the tracker:

  • info_hash: The 20-byte SHA1 hash of the .torrent file's info dictionary.
  • peer_id: A unique 20-byte string generated by the client at startup.
  • port: The listening port of the client (typically 6881-6889).
  • uploaded / downloaded: Total bytes uploaded and downloaded so far.
  • left: Total bytes remaining until the download is 100% complete.
  • event: Indicates the client's status (started, completed, stopped). Left empty for regular interval updates.
  • compact: Set to 1 to request a compressed binary peer list (highly recommended/often required).
  • Optional fields: ip (external IP), numwant (requested peer count, defaults to 50), key, and trackerid.

Tracker Response

The tracker replies with a bencoded dictionary containing:

  • interval: Seconds the client must wait before making another regular request.
  • complete / incomplete: The number of seeders (complete) and leechers (incomplete) in the swarm.
  • peers: The peer list, returned in one of two formats:
    • Binary Model (Compact): A continuous byte string where every 6 bytes represents a peer (First 4 bytes = IP address, next 2 bytes = Port number).
    • Dictionary Model: A list of dictionaries containing peer id, ip, and port.
  • Optional/Error fields: failure reason (halts processing if present), warning message, min interval, and tracker id.

Implementer's Note: Limiting active connections to around 30-50 peers is optimal. Having too many peers generates excessive network overhead (via broadcasted HAVE messages) without yielding faster download speeds.


UDP Tracker Protocol

To get a list of peers specifically via UDP (avoiding HTTP overhead), the client communicates with the tracker using a strict 4-step sequence:

  1. Connect Request: Send an initial request to the tracker.
  2. Connect Response: Receive and extract the connection_id.
  3. Announce Request: Use the connection_id to tell the tracker which files you are interested in.
  4. Announce Response: Receive and extract the resulting peer list.

Connect Messaging Format

Both the connect request and response are lightweight 16-byte payloads.

Connect Request (16 bytes):

Offset Size Name Value
0 64-bit int connection_id 0x41727101980 (Magic constant)
8 32-bit int action 0 (Connect)
12 32-bit int transaction_id Random integer

Connect Response (16 bytes):

Offset Size Name Value
0 32-bit int action 0 (Connect)
4 32-bit int transaction_id Matches your request
8 64-bit int connection_id Assigned by the tracker

Announce Messaging Format

Once a connection_id is successfully obtained, the client sends an announce request containing the torrent details to get the peer list.

Announce Request (98 bytes):

Offset Size Name Value
0 64-bit int connection_id Returned from connect response
8 32-bit int action 1 (Announce)
12 32-bit int transaction_id Random integer
16 20-byte string info_hash The torrent's info hash
36 20-byte string peer_id The client's unique ID
56 64-bit int downloaded Total bytes downloaded
64 64-bit int left Bytes remaining
72 64-bit int uploaded Total bytes uploaded
80 32-bit int event 0 (none), 1 (completed), 2 (started), 3 (stopped)
84 32-bit int IP address 0 (default)
88 32-bit int key Random integer
92 32-bit int num_want -1 (default, typically 50)
96 16-bit int port Client's listening port

Announce Response (20 + 6 * N bytes):

Offset Size Name Value
0 32-bit int action 1 (Announce)
4 32-bit int transaction_id Matches your request
8 32-bit int interval Seconds to wait until next announce
12 32-bit int leechers Number of incomplete peers
16 32-bit int seeders Number of complete peers
20 + 6*n 32-bit int IP address Peer IP (for peer n)
24 + 6*n 16-bit int TCP port Peer Port (for peer n)

Peer Wire Protocol (TCP)

Once a list of peers is acquired from the tracker, the client establishes TCP connections with them to actually download the files. Torrent files are broken into smaller chunks called pieces, which are further divided into blocks for network transmission.

Connection State Overview

A client maintains four state flags for every connected peer. Data blocks are only transferred when the downloading client is "interested" and the uploading client has "unchoked" them.

  • am_choking (Default: 1): This client is not answering requests from the peer.
  • am_interested (Default: 0): This client does not want blocks from the peer.
  • peer_choking (Default: 1): The peer is not answering requests from this client.
  • peer_interested (Default: 0): The peer does not want blocks from this client.

1. The Handshake

The handshake must be the very first message sent by the initiator of the connection. It is 68 bytes long in standard version 1.0.

  • Format: <pstrlen><pstr><reserved><info_hash><peer_id>
    • pstrlen: Length of protocol identifier (byte value 19).
    • pstr: The string "BitTorrent protocol".
    • reserved: 8 bytes of zeroes (used for future protocol extensions).
    • info_hash: 20-byte SHA1 hash of the torrent's info dictionary.
    • peer_id: 20-byte unique ID of the client connecting (often starts with client identification strings, like -AZ... for Azureus).

2. Understanding Pieces

Immediately after the handshake, peers exchange information about which pieces of the file they currently possess.

A piece is a fixed-size chunk of the total file data, defined by the piece length in the .torrent file.

  • Zero-Indexed: Pieces are requested by their index number, starting at 0 (e.g., index 0 is the first chunk, index 1 is the second).
  • Final Piece Size: If the total file size is not perfectly divisible by the piece length, the final piece will simply be smaller than the rest to make up the exact remainder.

3. Protocol Messages

After the handshake, all communication takes the form of length-prefixed messages. Unless otherwise specified, all integers are 4-byte big-endian.

  • Message Format: <length prefix><message ID><payload>
Message ID Format Description
Keep-Alive None <len=0000> Keeps connection active. Sent typically every 2 minutes.
Choke 0 <len=0001><id=0> Notifies peer that requests will be ignored.
Unchoke 1 <len=0001><id=1> Notifies peer that requests will now be answered.
Interested 2 <len=0001><id=2> Client expresses desire to download pieces.
Not Interested 3 <len=0001><id=3> Client no longer wants pieces from this peer.
Have 4 <len=0005><id=4><piece index> Broadcasts that a new piece was downloaded and verified.
Bitfield 5 <len=0001+X><id=5><bitfield> Sent immediately after handshaking. Represents all pieces currently held as a binary bitfield.
Request 6 <len=0013><id=6><idx><beg><len> Requests a specific block. Standard block size (len) is 16 KB.
Piece 7 <len=0009+X><id=7><idx><beg><blk> Transfers the actual block data payload.
Cancel 8 <len=0013><id=8><idx><beg><len> Cancels a pending request (used during the "End Game" phase).
Port 9 <len=0003><id=9><port> Broadcasts DHT listening port for distributed routing.

Features

  • Custom TCP/UDP Networking Engine: Manages multiplexed block requests across dozens of concurrent peers.
  • Parallel Tracker Broadcasting: Simultaneously polls multiple UDP trackers to rapidly populate the peer queue.
  • Decentralized Peer Discovery: Integrates Kademlia-based Distributed Hash Tables (DHT) and Peer Exchange (PEX).
  • Rarest First Algorithm: Dynamically tracks piece availability across the swarm to prioritize the hardest-to-find data.
  • Resilient Data Verification: Uses SHA-1 hashing and synchronous file writing to guarantee data integrity and enable seamless download resuming.

About

A torrent client for downloading torrent files.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages