• Stars
    star
    1,744
  • Rank 26,695 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🌊 Simple, robust, BitTorrent tracker (client & server) implementation

bittorrent-tracker ci npm downloads javascript style guide

Simple, robust, BitTorrent tracker (client & server) implementation

tracker visualization

Node.js implementation of a BitTorrent tracker, client and server.

A BitTorrent tracker is a web service which responds to requests from BitTorrent clients. The requests include metrics from clients that help the tracker keep overall statistics about the torrent. The response includes a peer list that helps the client participate in the torrent swarm.

This module is used by WebTorrent.

features

  • Includes client & server implementations
  • Supports all mainstream tracker types:
  • Supports ipv4 & ipv6
  • Supports tracker "scrape" extension
  • Robust and well-tested
  • Tracker statistics available via web interface at /stats or JSON data at /stats.json

Also see bittorrent-dht.

Tracker stats

Screenshot

install

npm install bittorrent-tracker

usage

client

To connect to a tracker, just do this:

var Client = require('bittorrent-tracker')

var requiredOpts = {
  infoHash: new Buffer('012345678901234567890'), // hex string or Buffer
  peerId: new Buffer('01234567890123456789'), // hex string or Buffer
  announce: [], // list of tracker server urls
  port: 6881 // torrent client port, (in browser, optional)
}

var optionalOpts = {
  // RTCPeerConnection config object (only used in browser)
  rtcConfig: {},
  // User-Agent header for http requests
  userAgent: '',
  // Custom webrtc impl, useful in node to specify [wrtc](https://npmjs.com/package/wrtc)
  wrtc: {},
  getAnnounceOpts: function () {
    // Provide a callback that will be called whenever announce() is called
    // internally (on timer), or by the user
    return {
      uploaded: 0,
      downloaded: 0,
      left: 0,
      customParam: 'blah' // custom parameters supported
    }
  },
  // Proxy config object
  proxyOpts: {
      // Socks proxy options (used to proxy requests in node)
      socksProxy: {
          // Configuration from socks module (https://github.com/JoshGlazebrook/socks)
          proxy: {
              // IP Address of Proxy (Required)
              ipaddress: "1.2.3.4",
              // TCP Port of Proxy (Required)
              port: 1080,
              // Proxy Type [4, 5] (Required)
              // Note: 4 works for both 4 and 4a.
              // Type 4 does not support UDP association relay 
              type: 5,
              
              // SOCKS 4 Specific:
              
              // UserId used when making a SOCKS 4/4a request. (Optional)
              userid: "someuserid",

              // SOCKS 5 Specific:
      
              // Authentication used for SOCKS 5 (when it's required) (Optional)
              authentication: {
                  username: "Josh",
                  password: "somepassword"
              }
          },
          
          // Amount of time to wait for a connection to be established. (Optional)
          // - defaults to 10000ms (10 seconds)
          timeout: 10000
      },
      // NodeJS HTTP agents (used to proxy HTTP and Websocket requests in node)
      // Populated with Socks.Agent if socksProxy is provided
      httpAgent: {},
      httpsAgent: {}
  },
}

var client = new Client(requiredOpts)

client.on('error', function (err) {
  // fatal client error!
  console.log(err.message)
})

client.on('warning', function (err) {
  // a tracker was unavailable or sent bad data to the client. you can probably ignore it
  console.log(err.message)
})

// start getting peers from the tracker
client.start()

client.on('update', function (data) {
  console.log('got an announce response from tracker: ' + data.announce)
  console.log('number of seeders in the swarm: ' + data.complete)
  console.log('number of leechers in the swarm: ' + data.incomplete)
})

client.once('peer', function (addr) {
  console.log('found a peer: ' + addr) // 85.10.239.191:48623
})

// announce that download has completed (and you are now a seeder)
client.complete()

// force a tracker announce. will trigger more 'update' events and maybe more 'peer' events
client.update()

// provide parameters to the tracker
client.update({
  uploaded: 0,
  downloaded: 0,
  left: 0,
  customParam: 'blah' // custom parameters supported
})

// stop getting peers from the tracker, gracefully leave the swarm
client.stop()

// ungracefully leave the swarm (without sending final 'stop' message)
client.destroy()

// scrape
client.scrape()

client.on('scrape', function (data) {
  console.log('got a scrape response from tracker: ' + data.announce)
  console.log('number of seeders in the swarm: ' + data.complete)
  console.log('number of leechers in the swarm: ' + data.incomplete)
  console.log('number of total downloads of this torrent: ' + data.downloaded)
})

server

To start a BitTorrent tracker server to track swarms of peers:

const Server = require('bittorrent-tracker').Server

const server = new Server({
  udp: true, // enable udp server? [default=true]
  http: true, // enable http server? [default=true]
  ws: true, // enable websocket server? [default=true]
  stats: true, // enable web-based statistics? [default=true]
  trustProxy: false, // enable trusting x-forwarded-for header for remote IP [default=false]
  filter: function (infoHash, params, cb) {
    // Blacklist/whitelist function for allowing/disallowing torrents. If this option is
    // omitted, all torrents are allowed. It is possible to interface with a database or
    // external system before deciding to allow/deny, because this function is async.

    // It is possible to block by peer id (whitelisting torrent clients) or by secret
    // key (private trackers). Full access to the original HTTP/UDP request parameters
    // are available in `params`.

    // This example only allows one torrent.

    const allowed = (infoHash === 'aaa67059ed6bd08362da625b3ae77f6f4a075aaa')
    if (allowed) {
      // If the callback is passed `null`, the torrent will be allowed.
      cb(null)
    } else {
      // If the callback is passed an `Error` object, the torrent will be disallowed
      // and the error's `message` property will be given as the reason.
      cb(new Error('disallowed torrent'))
    }
  }
})

// Internal http, udp, and websocket servers exposed as public properties.
server.http
server.udp
server.ws

server.on('error', function (err) {
  // fatal server error!
  console.log(err.message)
})

server.on('warning', function (err) {
  // client sent bad data. probably not a problem, just a buggy client.
  console.log(err.message)
})

server.on('listening', function () {
  // fired when all requested servers are listening

  // HTTP
  const httpAddr = server.http.address()
  const httpHost = httpAddr.address !== '::' ? httpAddr.address : 'localhost'
  const httpPort = httpAddr.port
  console.log(`HTTP tracker: http://${httpHost}:${httpPort}/announce`)

  // UDP
  const udpAddr = server.udp.address()
  const udpHost = udpAddr.address
  const udpPort = udpAddr.port
  console.log(`UDP tracker: udp://${udpHost}:${udpPort}`)

  // WS
  const wsAddr = server.ws.address()
  const wsHost = wsAddr.address !== '::' ? wsAddr.address : 'localhost'
  const wsPort = wsAddr.port
  console.log(`WebSocket tracker: ws://${wsHost}:${wsPort}`)

})


// start tracker server listening! Use 0 to listen on a random free port.
const port = 0
const hostname = "localhost"
server.listen(port, hostname, () => {
  // Do something on listening...
})

// listen for individual tracker messages from peers:

server.on('start', function (addr) {
  console.log('got start message from ' + addr)
})

server.on('complete', function (addr) {})
server.on('update', function (addr) {})
server.on('stop', function (addr) {})

// get info hashes for all torrents in the tracker server
Object.keys(server.torrents)

// get the number of seeders for a particular torrent
server.torrents[infoHash].complete

// get the number of leechers for a particular torrent
server.torrents[infoHash].incomplete

// get the peers who are in a particular torrent swarm
server.torrents[infoHash].peers

The http server will handle requests for the following paths: /announce, /scrape. Requests for other paths will not be handled.

multi scrape

Scraping multiple torrent info is possible with a static Client.scrape method:

var Client = require('bittorrent-tracker')
Client.scrape({ announce: announceUrl, infoHash: [ infoHash1, infoHash2 ]}, function (err, results) {
  results[infoHash1].announce
  results[infoHash1].infoHash
  results[infoHash1].complete
  results[infoHash1].incomplete
  results[infoHash1].downloaded

  // ...
})

command line

Install bittorrent-tracker globally:

$ npm install -g bittorrent-tracker

Easily start a tracker server:

$ bittorrent-tracker
http server listening on 8000
udp server listening on 8000
ws server listening on 8000

Lots of options:

$ bittorrent-tracker --help
  bittorrent-tracker - Start a bittorrent tracker server

  Usage:
    bittorrent-tracker [OPTIONS]

  If no --http, --udp, or --ws option is supplied, all tracker types will be started.

  Options:
    -p, --port [number]  change the port [default: 8000]
        --trust-proxy    trust 'x-forwarded-for' header from reverse proxy
        --interval       client announce interval (ms) [default: 600000]
        --http           enable http server
        --udp            enable udp server
        --ws             enable websocket server
    -q, --quiet          only show error output
    -s, --silent         show no output
    -v, --version        print the current version

license

MIT. Copyright (c) Feross Aboukhadijeh and WebTorrent, LLC.

More Repositories

1

webtorrent

⚡️ Streaming torrent client for the web
JavaScript
29,385
star
2

webtorrent-desktop

❤️ Streaming torrent app for Mac, Windows, and Linux
JavaScript
9,659
star
3

instant.io

🚀 Streaming file transfer over WebTorrent (torrents on the web)
JavaScript
3,423
star
4

bittorrent-dht

🕸 Simple, robust, BitTorrent DHT implementation
JavaScript
1,216
star
5

webtorrent-cli

WebTorrent, the streaming torrent client. For the command line.
JavaScript
1,154
star
6

webtorrent-hybrid

WebTorrent (with WebRTC support in Node.js)
JavaScript
518
star
7

parse-torrent

Parse a torrent identifier (magnet uri, .torrent file, info hash)
JavaScript
438
star
8

create-torrent

Create .torrent files
JavaScript
342
star
9

bittorrent-protocol

Simple, robust, BitTorrent peer wire protocol implementation
JavaScript
342
star
10

magnet-uri

Parse a magnet URI and return an object of keys/values
JavaScript
221
star
11

torrent-discovery

Discover BitTorrent and WebTorrent peers
JavaScript
216
star
12

node-bencode

bencode de/encoder for nodejs
JavaScript
165
star
13

webtorrent.io

The code that runs the WebTorrent website
JavaScript
125
star
14

ut_metadata

BitTorrent Extension for Peers to Send Metadata Files (BEP 9)
JavaScript
110
star
15

bittorrent-peerid

Map a BitTorrent peer ID to a human-readable client name and version
JavaScript
65
star
16

parse-torrent-file

DEPRECATED: Parse a .torrent file and return an object of keys/values
JavaScript
63
star
17

ut_pex

Implementation of ut_pex bittorrent protocol (PEX) for webtorrent
JavaScript
58
star
18

workshop

Learn WebTorrent and WebRTC in a guided workshop!
48
star
19

bittorrent-lsd

Local Service Discovery (BEP14) implementation
JavaScript
35
star
20

fs-chunk-store

Filesystem (fs) chunk store that is abstract-chunk-store compliant
JavaScript
33
star
21

torrent-piece

Torrent piece abstraction
JavaScript
23
star
22

webtorrent-fixtures

Sample torrent files for the WebTorrent test suite
JavaScript
22
star
23

load-ip-set

download and parse ip-set (blocklist) files
JavaScript
22
star
24

lt_donthave

The BitTorrent lt_donthave extension (BEP 54)
JavaScript
11
star
25

addr-to-ip-port

Convert an "address:port" string to an array [address:string, port:number]
JavaScript
10
star
26

bep53-range

Parse and compose Magnet URI extension (BEP53) ranges
JavaScript
9
star
27

string2compact

Convert 'hostname:port' strings to BitTorrent's compact ip/host binary returned by Trackers
JavaScript
9
star
28

renovate-config

Renovate's config
1
star
29

semantic-release-config

JavaScript
1
star
30

.github

1
star