krpc

Simple KRPC protocol implementaion of bencoded messages.

Usage no npm install needed!

<script type="module">
  import krpc from 'https://cdn.skypack.dev/krpc';
</script>

README

KRPC.js

build npm npm npm

Simple KRPC protocol implementation of bencoded messages. See BitTorent DHT specifications for more details.

Install

$ npm install krpc

API

KRPC (constructor)

krpc = new KRPC([opts])

Create a new krpc instance.

If opts is specified, then the default options (shown below) will be overridden.

var KRPC = require('krpc');

var krpc = new KRPC({
  transIdBytes: 2,     // transaction id string length
  queryTimeout: 2000   // in milliseconds, maximum time to wait for response
});

KRPC.Errors

KRPC default error codes:

KRPC.Errors = {
    GENERIC:         201,
    SERVER:          202,
    PROTOCOL:        203,
    METHOD_UNKNOWN:  204
};

KRPC.ForeignError

err = new KRPC.ForeignError(caughtError);

An Error class for foreign errors that caught while parsing messages.

socket.on('message', function(buffer, rinfo) {
    try {
        krpc.parse(buffer, rinfo.address, rinfo.port);
    } catch(err) {
        if(err instanceof KRPC.ForeignError)
            throw err.error;

        // else, ignore errors
    }
});

krpc.parse

krpc.parse(buffer, ip, port);

Parse a massage. See events section for handling parsed messages. Returns the parsed message. Throws an Error on failure or ForeignError when some emit throws an error.

socket.on('message', function(buffer, rinfo) {
    try {
        krpc.parse(buffer, rinfo.address, rinfo.port);
    } catch(err) {
        if(err instanceof KRPC.ForeignError)
            throw err.error;

        // else, ignore errors
    }
});

krpc.genTransId

transId = krpc.genTransId([ip], [port], callback, [timeout]);

Returns a new transaction id as Buffer.

callback(err, res) will be called when a parsed message with that transaction id will parse within the query timeout. If no message received within timeout a callback with an err will be called.

If ip or port are not null callback would be called only if the message received form that ip and port.

You may set timeout and change the default timeout queryTimeout that given on the constructor. Set timeout to null will disable the timeout for this transaction.

var transId = krpc.genTransId('1.1.1.1', 20000, function(err, res) {
    if(err) return console.trace(err);

    console.log(res);
});

krpc.query

buffer = krpc.query(transId, type, query);

Create an query message with type type and the query data query. Returns the message as Buffer.

transId is the query transaction id.

var buffer = krpc.query(transId, 'ping', {id: 'abcdefghij0123456789'});
socket.send(buffer, 0, buffer.length, 20000, '1.1.1.1');

krpc.respond

buffer = krpc.respond(transId, res);

Create a respond message with the data res. Returns the message as Buffer.

transId is the query transaction id.

krpc.on('query_ping', function(query, transId, ip, port) {
    console.log(query.id);

    var buffer = krpc.respond(transId, {id: 'mnopqrstuvwxyz123456'});
    socket.send(buffer, 0, buffer.length, port, ip);
});

krpc.error

buffer = krpc.error(transId, errorCode, errorMsg)

Create an error message with the code errorCode and message errorMsg. Returns the message as Buffer.

transId is the query transaction id.

krpc.on('parseError', function(transId, errorMsg, ip, port) {
    var buffer = krpc.error(transId, KRPC.Errors.PROTOCOL, errorMsg);
    socket.send(buffer, 0, buffer.length, port, ip);
});

krpc.on('parseError')

krpc.on('parseError', function(transId, errorMsg, ip, port) { ... })

Emits when a parse error should send back to the querying node.

krpc.on('parseError', function(transId, errorMsg, ip, port) {
    var buffer = krpc.error(transId, KRPC.Errors.PROTOCOL, errorMsg);
    socket.send(buffer, 0, buffer.length, port, ip);
});

krpc.on('query')

krpc.on('query', function(type, query, transId, ip, port) { ... })

Emits for each parsed query message.

krpc.on('query_{type}')

krpc.on('query_{type}', function(query, transId, ip, port) { ... })

Emits for each parsed query message with type {type}.

krpc.on('query_ping', function(query, transId, ip, port) {
    console.log(query.id);

    var buffer = krpc.respond(transId, {id: 'mnopqrstuvwxyz123456'});
    socket.send(buffer, 0, buffer.length, port, ip);
});

krpc.on('respond')

krpc.on('respond', function(res, transId, ip, port) { ... })

Emits for each parsed respond message.

krpc.on('{transId}')

krpc.on('{transId}', function(err, ip, port, res) { ... })

Emits for each parsed respond or error message with transaction id {transId} has hex string.

krpc.on('error')

krpc.on('error', function(errorCode, errorMsg, transId, ip, port) { ... })

Emits for each parsed error message.

License

KRPC.js is freely distributable under the terms of the MIT license.

Copyright (c) Moshe Simantov