diff --git a/lib/messages.js b/lib/messages.js index 0b0c129..41fbcc3 100644 --- a/lib/messages.js +++ b/lib/messages.js @@ -18,6 +18,30 @@ var util = require("./_util"); var message = structs.message; var ServicesBitfield = structs.ServicesBitfield; +/** + * Try to get command for the given encoded message. + * Note that this function doesn't do any validation because it is + * already provided by `message.decode` routine. Normally you call this + * for each incoming message and then call decode function of the + * appropriate message handler. + * @param {Buffer} buf - Buffer that starts with encoded message + * @return {?string} Message's command if any + */ +exports.getCommand = function(buf) { + if (buf.length < 16) { + return; + } + var command = buf.slice(4, 16); + var firstNonNull = 0; + for (var i = 11; i >=0; i--) { + if (command[i] !== 0) { + firstNonNull = i + 1; + break; + } + } + return command.slice(0, firstNonNull).toString("ascii"); +}; + /** * `version` message. * @see {@link https://bitmessage.org/wiki/Protocol_specification#version} diff --git a/lib/structs.js b/lib/structs.js index bf3387d..f6b0534 100644 --- a/lib/structs.js +++ b/lib/structs.js @@ -41,7 +41,6 @@ var message = exports.message = { * Decode message structure. * NOTE: `payload` is copied, `rest` references input buffer. * @param {Buffer} buf - Buffer that starts with encoded message - * structure * @return {{command: string, payload: Buffer, length: number, rest: Buffer}} * Decoded message structure. */ @@ -56,7 +55,10 @@ var message = exports.message = { firstNonNull = i + 1; } } - // Command could be empty. + // NOTE(Kagami): Command can be empty. + // NOTE(Kagami): "ascii" encoding is not necessary here since we + // already validated the command but that should be quite faster + // than default "utf-8" encoding. command = command.slice(0, firstNonNull).toString("ascii"); var payloadLength = buf.readUInt32BE(16, true); assert(payloadLength <= 262144, "Payload is too big"); diff --git a/test.js b/test.js index 53e6b07..46e7bca 100644 --- a/test.js +++ b/test.js @@ -363,6 +363,12 @@ describe("Common structures", function() { // TODO(Kagami): Add tests for encodePayload/decodePayload as well. describe("Message types", function() { + it("should get command for encoded message", function() { + var encoded = message.encode("test", Buffer(0)); + expect(messages.getCommand(encoded)).to.equal("test"); + expect(messages.getCommand(Buffer("test"))).to.be.undefined; + }); + describe("version", function() { it("should encode and decode", function() { var encoded = version.encode({