From f29f32b3aa0a5378009c929daa0b0bcf9c6f00f6 Mon Sep 17 00:00:00 2001 From: Kagami Hiiragi Date: Sat, 7 Mar 2015 00:35:30 +0300 Subject: [PATCH] Add option to check stream in object.validate --- lib/structs.js | 14 +++++++++++--- test.js | 14 +++++++++++++- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/lib/structs.js b/lib/structs.js index 898947b..e6beb41 100644 --- a/lib/structs.js +++ b/lib/structs.js @@ -367,7 +367,7 @@ var object = exports.object = { var decodedStream = var_int.decode(decodedVersion.rest); var headerLength = 20 + decodedVersion.length + decodedStream.length; - if (opts._validate) { return; } + if (opts._validate) { return {stream: decodedStream.value}; } var objectPayload = new Buffer(decodedStream.rest.length); decodedStream.rest.copy(objectPayload); @@ -387,7 +387,8 @@ var object = exports.object = { * Check whether given `object` message is valid. * @param {Buffer} buf - Message * @param {Object=} opts - Any of [object.decode]{@link - * module:bitmessage/structs.object.decode} options + * module:bitmessage/structs.object.decode} options and: + * @param {number} opts.stream - Expected object's stream * @return {?Error} Return an error with description if object is * invalid. */ @@ -411,11 +412,18 @@ var object = exports.object = { */ validatePayload: function(buf, opts) { opts = objectAssign({}, opts, {_validate: true}); + var decoded; try { - object.decodePayload(buf, opts); + decoded = object.decodePayload(buf, opts); } catch(e) { return e; } + if (opts.stream && decoded.stream !== opts.stream) { + return new Error( + "The stream number " + opts.stream + + " is not the one we are interested in" + ); + } }, /** diff --git a/test.js b/test.js index 058f4d2..6d2e5a9 100644 --- a/test.js +++ b/test.js @@ -261,7 +261,19 @@ describe("Common structures", function() { err = object.validatePayload(obj); expect(err.message).to.match(/insufficient pow/i); - expect(object.validatePayload(obj, {skipPow: true})).to.not.exist; + expect(object.validatePayload(obj, skipPow)).to.not.exist; + }); + + it("should allow to validate stream", function() { + var obj = object.encodePayload({ + nonce: Buffer(8), + ttl: 111, + type: object.MSG, + version: 1, + objectPayload: Buffer(0), + }); + var err = object.validatePayload(obj, {skipPow: true, stream: 3}); + expect(err.message).to.match(/stream.*is not the one/i); }); });