Peer Wire Protocol
peer-wire-protocol is a node stream implementation of the peer wire protocol specification.
The protocol is the main communication layer when transferring files using BitTorrent and is used by peerflix.
It is available through npm:
npm install peer-wire-protocol
Usage is simple
Since the protocol is implemented as a stream all you have to do is pipe some to and from it
var pwp = require('peer-wire-protocol');
var net = require('net');
net.createServer(function(socket) {
var wire = pwp();
socket.pipe(wire).pipe(socket);
wire.on('handshake', function(infoHash, peerId) {
wire.handshake(Buffer.from('my info hash'), Buffer.from('my peer id'));
});
wire.on('unchoke', function() {
console.log('peer is no longer choking us: '+wire.peerChoking);
});
}).listen(6881);
Full API
Handshaking
Send and receive a handshake from the peer. This is the first message.
wire.handshake(infoHash, peerId, {dht:true});
wire.on('handshake', function(infoHash, peerId, extensions) {
});
Both the infoHash
and the peerId
should be 20 bytes
Choking
Check if you or the peer is choking
wire.peerChoking;
wire.amChoking;
wire.on('choke', function() {
});
wire.on('unchoke', function() {
});
Interested
See if you or the peer is interested
wire.peerInterested;
wire.amInterested;
wire.on('interested', function() {
});
wire.on('uninterested', function() {
});
Bitfield
Exchange piece information with the peer
wire.bitfield(buffer);
wire.on('bitfield', function(bitfield) {
});
wire.have(pieceIndex);
wire.on('have', function(pieceIndex) {
});
You can always see which pieces the peer have
wire.peerPieces[i];
Requests
Send and respond to requests for pieces
wire.request(pieceIndex, offset, length, function(err, block) {
if (err) {
return;
}
});
wire.cancel(pieceIndex, offset, length);
wire.on('request', function(pieceIndex, offset, length, callback) {
callback(null, piece);
});
wire.requests;
wire.peerRequests;
You can set a request timeout if you want to
wire.setTimeout(5000);
If the timeout is triggered the request callback is called with an error and a timeout
event is emitted.
DHT and port
You can set the extensions flag dht
in the handshake to true
if you participate in the torrent dht.
Afterwards you can send your dht port
wire.port(dhtPort);
wire.on('port', function(dhtPort) {
});
Keep-Alive
You can enable the keep-alive ping (triggered every 60s)
wire.setKeepAlive(true);
wire.on('keep-alive', function() {
});
Transfer stats
Check how many bytes you have uploaded and download
wire.uploaded;
wire.downloaded;
wire.on('download', function(numberOfBytes) {
...
});
wire.on('upload', function(numberOfBytes) {
...
});
License
MIT