bitmessage-js/lib/structs.js

1066 lines
33 KiB
JavaScript
Raw Permalink Normal View History

2015-01-01 20:26:06 +01:00
/**
* Implements common structures.
2015-02-12 11:36:44 +01:00
* @see {@link
2023-01-09 02:46:20 +01:00
* https://pybitmessage.rtfd.io/en/v0.6/protocol.html#common-structures}
2015-01-03 16:58:41 +01:00
* @module bitmessage/structs
2015-02-12 11:36:44 +01:00
* @example
* var structs = require("bitmessage").structs;
*
* var encoded = Buffer.concat([
* structs.var_int.encode(4),
* Buffer.from("test"),
2015-02-12 11:36:44 +01:00
* structs.var_str.encode("test2"),
* structs.var_int_list.encode([1, 2, 3]),
* ]);
*
* var decoded1 = structs.var_str.decode(encoded);
* console.log(decoded1.str); // test
* var decoded2 = structs.var_str.decode(decoded1.rest);
* console.log(decoded2.str); // test2
* var decoded3 = structs.var_int.decode(decoded2.rest);
* console.log(decoded3.value); // 3
* var decoded4 = structs.var_int_list.decode(decoded2.rest);
* console.log(decoded4.list); // [1, 2, 3]
2015-01-01 20:26:06 +01:00
*/
"use strict";
2015-01-06 12:06:15 +01:00
var objectAssign = Object.assign || require("object-assign");
2015-01-04 21:22:14 +01:00
var bufferEqual = require("buffer-equal");
var bmcrypto = require("./crypto");
2015-01-30 18:13:09 +01:00
var POW = require("./pow");
var util = require("./_util");
2015-01-04 21:22:14 +01:00
var assert = util.assert;
var IPv4_MAPPING = util.IPv4_MAPPING;
var inet_pton = util.inet_pton;
2015-01-04 21:22:14 +01:00
function isAscii(str) {
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 127) {
return false;
}
}
return true;
}
2015-01-08 03:00:19 +01:00
// Compute the message checksum for the given data.
function getmsgchecksum(data) {
2015-01-04 21:22:14 +01:00
return bmcrypto.sha512(data).slice(0, 4);
}
2015-02-06 18:44:27 +01:00
// \ :3 /
function findMagic(buf) {
var i;
var len = buf.length;
var firstb = false;
var secondb = false;
var thirdb = false;
for (i = 0; i < len; ++i) {
switch (buf[i]) {
case 0xE9:
firstb = true;
break;
case 0xBE:
if (firstb) { secondb = true; }
break;
case 0xB4:
if (firstb && secondb) { thirdb = true; }
break;
case 0xD9:
if (firstb && secondb && thirdb) { return i - 3; }
break;
default:
firstb = false;
secondb = false;
thirdb = false;
}
}
// If we reached the end of the buffer but part of the magic matches
// we'll still return index of the magic's start position.
if (firstb) {
if (secondb) {
--i;
}
if (thirdb) {
--i;
}
return i - 1; // Compensate for last i's increment
} else {
return -1;
}
}
2015-01-04 21:22:14 +01:00
/**
* Message structure.
2023-01-09 02:46:20 +01:00
* @see {@link https://pybitmessage.rtfd.io/en/v0.6/protocol.html#id1}
2015-01-04 21:22:14 +01:00
* @namespace
* @static
*/
var message = exports.message = {
2015-01-31 12:51:35 +01:00
/**
* Bitmessage magic value.
* @constant {number}
*/
2015-01-04 21:22:14 +01:00
MAGIC: 0xE9BEB4D9,
2015-02-11 13:18:38 +01:00
/**
* @typedef {Object} TryDecodeResult
* @property {Object} message - Decoded message
* @property {string} message.command - Message command
* @property {Buffer} message.payload - Message payload
* @property {number} message.length - Full message length
* @property {Error} error - ...or decoding error
* @property {Buffer} rest - The rest of the input buffer after
* processing message
* @memberof module:bitmessage/structs.message
*/
2015-02-06 18:44:27 +01:00
/**
* Decode message in "stream" mode.
* NOTE: message payload and `rest` are copied (so the runtime can GC
* processed buffer data).
* @param {Buffer} buf - Data buffer
2015-02-11 13:18:38 +01:00
* @return {?TryDecodeResult}
* [Decoded result.]{@link module:bitmessage/structs.message.TryDecodeResult}
2015-02-06 18:44:27 +01:00
*/
tryDecode: function(buf) {
if (buf.length < 24) {
// Message is not yet fully received, just skip to next process
// cycle.
return;
}
var res = {};
// Magic.
var mindex = findMagic(buf);
if (mindex !== 0) {
if (mindex === -1) {
res.error = new Error("Magic not found, skipping buffer data");
res.rest = Buffer.alloc(0);
2015-02-06 18:44:27 +01:00
} else {
res.error = new Error(
"Magic in the middle of buffer, skipping some data at start"
);
res.rest = Buffer.alloc(buf.length - mindex);
2015-02-06 18:44:27 +01:00
buf.copy(res.rest, 0, mindex);
}
return res;
}
// Payload length.
var payloadLength = buf.readUInt32BE(16, true);
var msgLength = 24 + payloadLength;
// See: <https://github.com/Bitmessage/PyBitmessage/issues/767>.
2015-02-06 18:44:27 +01:00
if (payloadLength > 1600003) {
res.error = new Error("Message is too large, skipping it");
if (buf.length > msgLength) {
res.rest = Buffer.alloc(buf.length - msgLength);
2015-02-06 18:44:27 +01:00
buf.copy(res.rest, 0, msgLength);
} else {
res.rest = Buffer.alloc(0);
2015-02-06 18:44:27 +01:00
}
return res;
}
if (buf.length < msgLength) {
// Message is not yet fully received, just skip to next process
// cycle.
return;
}
// Now we can set `rest` value.
res.rest = Buffer.alloc(buf.length - msgLength);
2015-02-06 18:44:27 +01:00
buf.copy(res.rest, 0, msgLength);
// Command.
var command = buf.slice(4, 16);
var firstNonNull = 0;
var i;
for (i = 11; i >=0; i--) {
if (command[i] > 127) {
res.error = new Error(
"Non-ASCII characters in command, skipping message"
);
return res;
}
if (!firstNonNull && command[i] !== 0) {
firstNonNull = i + 1;
}
}
command = command.slice(0, firstNonNull).toString("ascii");
// Payload.
var payload = Buffer.alloc(payloadLength);
2015-02-06 18:44:27 +01:00
buf.copy(payload, 0, 24, msgLength);
var checksum = buf.slice(20, 24);
if (!bufferEqual(checksum, getmsgchecksum(payload))) {
res.error = new Error("Bad checksum, skipping message");
return res;
}
res.message = {command: command, payload: payload, length: msgLength};
return res;
},
2015-02-11 13:18:38 +01:00
/**
* @typedef {Object} DecodeResult
* @property {string} command - Message command
* @property {Buffer} payload - Message payload
* @property {number} length - Full message length
* @property {Buffer} rest - The rest of the input buffer
* @memberof module:bitmessage/structs.message
*/
2015-01-04 21:22:14 +01:00
/**
* Decode message.
2015-01-11 18:24:39 +01:00
* NOTE: `payload` is copied, `rest` references input buffer.
2015-01-04 21:22:14 +01:00
* @param {Buffer} buf - Buffer that starts with encoded message
2015-02-11 13:18:38 +01:00
* @return {DecodeResult}
* [Decoded message structure.]{@link module:bitmessage/structs.message.DecodeResult}
2015-01-04 21:22:14 +01:00
*/
decode: function(buf) {
assert(buf.length >= 24, "Buffer is too small");
assert(buf.readUInt32BE(0, true) === message.MAGIC, "Wrong magic");
var command = buf.slice(4, 16);
2015-01-08 03:00:19 +01:00
var firstNonNull = 0;
2015-01-04 21:22:14 +01:00
for (var i = 11; i >=0; i--) {
assert(command[i] <= 127, "Non-ASCII characters in command");
2015-01-08 03:00:19 +01:00
if (!firstNonNull && command[i] !== 0) {
firstNonNull = i + 1;
2015-01-04 21:22:14 +01:00
}
}
2015-01-27 14:35:49 +01:00
// 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.
2015-01-08 03:00:19 +01:00
command = command.slice(0, firstNonNull).toString("ascii");
2015-01-04 21:22:14 +01:00
var payloadLength = buf.readUInt32BE(16, true);
assert(payloadLength <= 1600003, "Message payload is too big");
2015-01-04 21:22:14 +01:00
var length = 24 + payloadLength;
2015-01-15 18:13:02 +01:00
assert(buf.length >= length, "Truncated payload");
var checksum = buf.slice(20, 24);
2015-01-11 14:59:43 +01:00
// NOTE(Kagami): We do copy instead of slice to protect against
// possible source buffer modification by user.
var payload = Buffer.alloc(payloadLength);
2015-01-11 14:59:43 +01:00
buf.copy(payload, 0, 24, length);
2015-01-15 18:13:02 +01:00
assert(bufferEqual(checksum, getmsgchecksum(payload)), "Bad checksum");
2015-01-04 21:22:14 +01:00
var rest = buf.slice(length);
return {command: command, payload: payload, length: length, rest: rest};
},
/**
* Encode message.
2015-01-26 17:34:29 +01:00
* @param {string} command - Message command
* @param {Bufer} payload - Message payload
2015-01-04 21:22:14 +01:00
* @return {Buffer} Encoded message structure.
*/
2015-01-26 17:34:29 +01:00
encode: function(command, payload) {
assert(command.length <= 12, "Command is too long");
assert(isAscii(command), "Non-ASCII characters in command");
payload = payload || Buffer.alloc(0);
assert(payload.length <= 1600003, "Message payload is too big");
var buf = Buffer.alloc(24 + payload.length);
2015-01-04 21:22:14 +01:00
buf.fill(0);
buf.writeUInt32BE(message.MAGIC, 0, true);
2015-01-26 17:34:29 +01:00
buf.write(command, 4);
buf.writeUInt32BE(payload.length, 16, true);
getmsgchecksum(payload).copy(buf, 20);
payload.copy(buf, 24);
2015-01-04 21:22:14 +01:00
return buf;
},
};
/**
2015-01-31 12:51:35 +01:00
* An `object` is a message which is shared throughout a stream. It is
* the only message which propagates; all others are only between two
* nodes.
2023-01-09 02:46:20 +01:00
* @see {@link https://pybitmessage.rtfd.io/en/v0.6/protocol.html#object}
* @namespace
* @static
*/
var object = exports.object = {
2015-02-11 13:18:38 +01:00
/**
* [getpubkey]{@link module:bitmessage/objects.getpubkey} object type.
* @constant {number}
*/
GETPUBKEY: 0,
2015-02-11 13:18:38 +01:00
/**
* [pubkey]{@link module:bitmessage/objects.pubkey} object type.
* @constant {number}
*/
PUBKEY: 1,
2015-02-11 13:18:38 +01:00
/**
* [msg]{@link module:bitmessage/objects.msg} object type.
* @constant {number}
*/
MSG: 2,
2015-02-11 13:18:38 +01:00
/**
* [broadcast]{@link module:bitmessage/objects.broadcast} object type.
* @constant {number}
*/
BROADCAST: 3,
2015-02-11 13:18:38 +01:00
/**
* @typedef {Object} DecodeResult
* @property {Buffer} nonce - A 8-byte object nonce
* @property {number} ttl - Time to live in seconds
2015-03-07 19:05:39 +01:00
* @property {Date} expires - Object expiration date
2015-02-11 13:18:38 +01:00
* @property {number} type - Object type
* @property {number} version - Object version
* @property {number} stream - Object stream
* @property {number} headerLength - Length of the object header
* @property {Buffer} objectPayload - Object payload
* @memberof module:bitmessage/structs.object
*/
/**
2015-01-31 12:51:35 +01:00
* Decode `object` message.
* NOTE: `nonce` and `objectPayload` are copied.
* @param {Buffer} buf - Message
2015-02-10 19:23:20 +01:00
* @param {Object=} opts - Decoding options
2015-02-11 13:18:38 +01:00
* @param {boolean} opts.allowExpired - Allow expired objects
* @param {boolean} opts.skipPow - Do not validate object POW
2015-02-16 17:47:19 +01:00
* @return {DecodeResult} [Decoded `object` structure.]{@link
* module:bitmessage/structs.object.DecodeResult}
* @throws {Error} Invalid object
*/
2015-01-30 18:13:09 +01:00
decode: function(buf, opts) {
var decoded = message.decode(buf);
2015-02-16 17:47:19 +01:00
assert(decoded.command === "object", "Given message is not an object");
2015-01-30 18:13:09 +01:00
return object.decodePayload(decoded.payload, opts);
},
/**
2015-02-11 13:18:38 +01:00
* Decode `object` message payload.
* The same as [decode]{@link module:bitmessage/structs.object.decode}.
*/
2015-01-30 18:13:09 +01:00
decodePayload: function(buf, opts) {
opts = opts || {};
2015-02-16 17:47:19 +01:00
// 8 + 8 + 4 + (1+) + (1+)
assert(buf.length >= 22, "object message payload is too small");
assert(buf.length <= 262144, "object message payload is too big");
2015-02-16 17:47:19 +01:00
var nonce;
if (!opts._validate) {
nonce = Buffer.alloc(8);
2015-02-16 17:47:19 +01:00
buf.copy(nonce, 0, 0, 8);
}
2015-01-30 18:13:09 +01:00
// TTL.
var expiresTime = util.readTimestamp64BE(buf.slice(8, 16));
2015-03-07 19:05:39 +01:00
var expires = new Date(expiresTime * 1000);
var ttl = expiresTime - util.tnow();
assert(ttl <= 2430000, "expiresTime is too far in the future");
2015-01-30 18:13:09 +01:00
if (!opts.allowExpired) {
assert(ttl >= -3600, "Object expired more than a hour ago");
}
// POW.
if (!opts.skipPow) {
// User may specify trials/payload extra options and we will
// account in here.
var targetOpts = objectAssign({}, opts, {ttl: ttl, payload: buf});
var target = POW.getTarget(targetOpts);
assert(POW.check({target: target, payload: buf}), "Insufficient POW");
}
var type = buf.readUInt32BE(16, true);
var decodedVersion = var_int.decode(buf.slice(20));
var decodedStream = var_int.decode(decodedVersion.rest);
var headerLength = 20 + decodedVersion.length + decodedStream.length;
2015-02-16 17:47:19 +01:00
if (opts._validate) { return {stream: decodedStream.value}; }
2015-02-16 17:47:19 +01:00
var objectPayload = Buffer.alloc(decodedStream.rest.length);
decodedStream.rest.copy(objectPayload);
2015-01-30 18:13:09 +01:00
return {
nonce: nonce,
ttl: ttl,
2015-03-07 19:05:39 +01:00
expires: expires,
type: type,
version: decodedVersion.value,
stream: decodedStream.value,
headerLength: headerLength,
objectPayload: objectPayload,
};
},
2015-02-16 17:47:19 +01:00
/**
* 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 and:
* @param {number} opts.stream - Expected object's stream
2015-02-16 17:47:19 +01:00
* @return {?Error} Return an error with description if object is
* invalid.
*/
validate: function(buf, opts) {
var decoded;
try {
decoded = message.decode(buf);
} catch(e) {
return e;
}
if (decoded.command !== "object") {
return new Error("Given message is not an object");
}
return object.validatePayload(decoded.payload, opts);
},
/**
* Check whether `object` message payload is valid.
* The same as [validate]{@link
* module:bitmessage/structs.object.validate}.
*/
validatePayload: function(buf, opts) {
opts = objectAssign({}, opts, {_validate: true});
var decoded;
2015-02-16 17:47:19 +01:00
try {
decoded = object.decodePayload(buf, opts);
2015-02-16 17:47:19 +01:00
} 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"
);
}
2015-02-16 17:47:19 +01:00
},
/**
* Encode `object` message.
* @param {Object} opts - Object options
2015-02-11 13:18:38 +01:00
* @param {Object} opts.nonce - A 8-byte object nonce
* @param {number} opts.ttl - Time to live in seconds
* @param {number} opts.type - Object type
* @param {number} opts.version - Object version
* @param {number=} opts.stream - Object stream (1 by default)
* @param {Buffer} opts.objectPayload - Object payload
* @return {Buffer} Encoded message.
*/
encode: function(opts) {
var payload = object.encodePayload(opts);
return message.encode("object", payload);
},
/**
* Encode `object` message payload.
2015-02-11 13:18:38 +01:00
* The same as [encode]{@link module:bitmessage/structs.object.encode}.
*/
encodePayload: function(opts) {
2015-01-30 20:45:45 +01:00
// NOTE(Kagami): We do not try to calculate nonce here if it is not
// provided because:
// 1) It's async operation but in `structs` module all operations
// are synchronous.
// 2) It shouldn't be useful because almost all objects signatures
// include object header and POW is computed for entire object so at
// first the object header should be assembled and only then we can
// do a POW.
assert(opts.nonce.length === 8, "Bad nonce");
// NOTE(Kagami): This may be a bit inefficient since we allocate
// twice.
return Buffer.concat([
opts.nonce,
object.encodePayloadWithoutNonce(opts),
]);
},
/**
* Encode `object` message payload without leading nonce field (may be
* useful if you are going to calculate it later).
* @param {Object} opts - Object options
2015-02-11 13:18:38 +01:00
* @param {number} opts.ttl - Time to live in seconds
* @param {number} opts.type - Object type
* @param {number} opts.version - Object version
* @param {number=} opts.stream - Object stream (1 by default)
* @param {Buffer} opts.objectPayload - Object payload
* @return {Buffer} Encoded payload.
*/
encodePayloadWithoutNonce: function(opts) {
assert(opts.ttl > 0, "Bad TTL");
assert(opts.ttl <= 2430000, "TTL may not be larger than 28 days + 3 hours");
var expiresTime = util.tnow() + opts.ttl;
var type = Buffer.alloc(4);
type.writeUInt32BE(opts.type, 0);
var stream = opts.stream || 1;
var obj = Buffer.concat([
util.writeUInt64BE(null, expiresTime),
type,
var_int.encode(opts.version),
var_int.encode(stream),
opts.objectPayload,
]);
assert(obj.length <= 262136, "object message payload is too big");
return obj;
},
};
2015-01-01 20:26:06 +01:00
/**
2015-01-06 00:32:10 +01:00
* Variable length integer.
2023-01-09 02:46:20 +01:00
* @see {@link https://pybitmessage.rtfd.io/en/v0.6/protocol.html#variable-length-integer}
2015-01-03 16:58:41 +01:00
* @namespace
* @static
2015-01-01 20:26:06 +01:00
*/
2015-01-01 21:00:33 +01:00
var var_int = exports.var_int = {
2015-02-11 13:18:38 +01:00
/**
* @typedef {Object} DecodeResult
* @property {number} value - Stored value
* @property {number} length - `var_int` full length
* @property {Buffer} rest - The rest of the input buffer
* @memberof module:bitmessage/structs.var_int
*/
2015-01-01 20:26:06 +01:00
/**
2015-01-31 12:51:35 +01:00
* Decode `var_int`.
2015-01-11 18:24:39 +01:00
* NOTE: `rest` references input buffer.
2015-01-06 00:32:10 +01:00
* @param {Buffer} buf - A buffer that starts with encoded `var_int`
2015-02-11 13:18:38 +01:00
* @return {DecodeResult}
* [Decoded `var_int` structure.]{@link module:bitmessage/structs.var_int.DecodeResult}
2015-01-01 20:26:06 +01:00
*/
decode: function(buf) {
var value, length;
2015-01-03 01:11:02 +01:00
assert(buf.length > 0, "Empty buffer");
2015-01-01 20:26:06 +01:00
switch (buf[0]) {
case 253:
value = buf.readUInt16BE(1);
assert(value >= 253, "Impractical var_int");
length = 3;
break;
case 254:
value = buf.readUInt32BE(1);
assert(value >= 65536, "Impractical var_int");
length = 5;
break;
case 255:
var hi = buf.readUInt32BE(1);
assert(hi !== 0, "Impractical var_int");
// Max safe number = 2^53 - 1 =
// 0b0000000000011111111111111111111111111111111111111111111111111111
2015-01-03 01:11:02 +01:00
// = 2097151*(2^32) + (2^32 - 1).
// So it's safe until hi <= 2097151. See
// <http://mdn.io/issafeinteger>,
// <https://stackoverflow.com/q/307179> for details.
// TODO(Kagami): We may want to return raw Buffer for
2015-01-28 23:13:41 +01:00
// 2^53 <= value <= 2^64 - 1 range. Probably using the optional
2015-01-03 01:11:02 +01:00
// argument because most of the code expect to get a number when
// calling `var_int.decode`.
assert(hi <= 2097151, "Unsafe integer");
2015-01-01 20:26:06 +01:00
var lo = buf.readUInt32BE(5);
value = hi * 4294967296 + lo;
2015-01-01 20:26:06 +01:00
length = 9;
break;
default:
value = buf[0];
length = 1;
}
var rest = buf.slice(length);
return {value: value, length: length, rest: rest};
},
/**
2015-01-06 00:32:10 +01:00
* Encode number into `var_int`.
* @param {(number|Buffer)} value - Input number
2015-01-06 00:32:10 +01:00
* @return {Buffer} Encoded `var_int`.
2015-01-01 20:26:06 +01:00
*/
encode: function(value) {
var buf, targetStart;
2015-01-01 20:26:06 +01:00
if (typeof value === "number") {
assert(value >= 0, "Value cannot be less than zero");
if (value < 253) {
buf = Buffer.alloc(1);
buf[0] = value;
2015-01-01 20:26:06 +01:00
} else if (value < 65536) {
buf = Buffer.alloc(3);
2015-01-01 20:26:06 +01:00
buf[0] = 253;
2015-01-03 16:58:41 +01:00
buf.writeUInt16BE(value, 1, true);
2015-01-01 20:26:06 +01:00
} else if (value < 4294967296) {
buf = Buffer.alloc(5);
2015-01-01 20:26:06 +01:00
buf[0] = 254;
2015-01-03 16:58:41 +01:00
buf.writeUInt32BE(value, 1, true);
2015-01-01 20:26:06 +01:00
} else {
assert(value <= 9007199254740991, "Unsafe integer");
buf = Buffer.alloc(9);
2015-01-01 20:26:06 +01:00
buf[0] = 255;
2015-01-03 16:58:41 +01:00
buf.writeUInt32BE(Math.floor(value / 4294967296), 1, true); // high32
buf.writeUInt32BE(value % 4294967296, 5, true); // low32
2015-01-01 20:26:06 +01:00
}
} else if (Buffer.isBuffer(value)) {
2015-01-03 01:11:02 +01:00
assert(value.length <= 8, "Buffer is too big");
buf = Buffer.alloc(9);
buf.fill(0);
buf[0] = 255;
targetStart = 1 + (8 - value.length);
value.copy(buf, targetStart);
2015-01-01 20:26:06 +01:00
} else {
2015-01-08 14:47:29 +01:00
throw new Error("Unknown value type");
2015-01-01 20:26:06 +01:00
}
return buf;
},
};
2015-01-01 21:00:33 +01:00
/**
2015-01-06 00:32:10 +01:00
* Variable length string.
2023-01-09 02:46:20 +01:00
* @see {@link https://pybitmessage.rtfd.io/en/v0.6/protocol.html#variable-length-string}
2015-01-03 16:58:41 +01:00
* @namespace
2015-01-01 21:00:33 +01:00
*/
exports.var_str = {
2015-02-11 13:18:38 +01:00
/**
* @typedef {Object} DecodeResult
* @property {number} str - The string itself
* @property {number} length - `var_str` full length
* @property {Buffer} rest - The rest of the input buffer
* @memberof module:bitmessage/structs.var_str
*/
2015-01-01 21:00:33 +01:00
/**
2015-01-31 12:51:35 +01:00
* Decode `var_str`.
2015-01-11 18:24:39 +01:00
* NOTE: `rest` references input buffer.
2015-01-06 00:32:10 +01:00
* @param {Buffer} buf - A buffer that starts with encoded `var_str`
2015-02-11 13:18:38 +01:00
* @return {DecodeResult}
* [Decoded `var_str` structure.]{@link module:bitmessage/structs.var_str.DecodeResult}
2015-01-01 21:00:33 +01:00
*/
decode: function(buf) {
var decoded = var_int.decode(buf);
var strLength = decoded.value;
2015-01-11 16:27:14 +01:00
var length = decoded.length + strLength;
assert(buf.length >= length, "Buffer is too small");
2015-01-01 21:00:33 +01:00
// XXX(Kagami): Spec doesn't mention encoding, using UTF-8.
2015-01-15 23:43:15 +01:00
var str = decoded.rest.slice(0, strLength).toString("utf8");
2015-01-01 21:00:33 +01:00
var rest = decoded.rest.slice(strLength);
2015-01-11 16:27:14 +01:00
return {str: str, length: length, rest: rest};
2015-01-01 21:00:33 +01:00
},
/**
2015-01-06 00:32:10 +01:00
* Encode string into `var_str`.
2015-01-01 21:00:33 +01:00
* @param {string} str - A string
2015-01-06 00:32:10 +01:00
* @return {Buffer} Encoded `var_str`.
2015-01-01 21:00:33 +01:00
*/
encode: function(str) {
// XXX(Kagami): Spec doesn't mention encoding, using UTF-8.
var strBuf = Buffer.from(str, "utf8");
2015-01-01 21:00:33 +01:00
return Buffer.concat([var_int.encode(strBuf.length), strBuf]);
},
};
2015-01-02 15:27:03 +01:00
/**
2015-01-06 00:32:10 +01:00
* Variable length list of integers.
2023-01-09 02:46:20 +01:00
* @see {@link https://pybitmessage.rtfd.io/en/v0.6/protocol.html#variable-length-list-of-integers}
2015-01-03 16:58:41 +01:00
* @namespace
2015-01-02 15:27:03 +01:00
*/
exports.var_int_list = {
2015-02-11 13:18:38 +01:00
/**
* @typedef {Object} DecodeResult
* @property {number} list - Stored numbers
* @property {number} length - `var_int_list` full length
* @property {Buffer} rest - The rest of the input buffer
* @memberof module:bitmessage/structs.var_int_list
*/
2015-01-02 15:27:03 +01:00
/**
2015-01-31 12:51:35 +01:00
* Decode `var_int_list`.
2015-01-11 18:24:39 +01:00
* NOTE: `rest` references input buffer.
2015-01-03 16:58:41 +01:00
* @param {Buffer} buf - A buffer that starts with encoded
2015-01-06 00:32:10 +01:00
* `var_int_list`
2015-02-11 13:18:38 +01:00
* @return {DecodeResult}
* [Decoded `var_int_list` structure.]{@link module:bitmessage/structs.var_int_list.DecodeResult}
2015-01-02 15:27:03 +01:00
*/
decode: function(buf) {
var decoded = var_int.decode(buf);
var listLength = decoded.value;
var list = new Array(listLength);
var rest = decoded.rest;
var sumLength = decoded.length;
for (var i = 0; i < listLength; i++) {
decoded = var_int.decode(rest);
list[i] = decoded.value;
rest = decoded.rest;
sumLength += decoded.length;
}
return {list: list, length: sumLength, rest: rest};
2015-01-02 15:27:03 +01:00
},
/**
2015-01-06 00:32:10 +01:00
* Encode list of numbers into `var_int_list`.
2015-01-02 15:27:03 +01:00
* @param {number[]} list - A number list
2015-01-06 00:32:10 +01:00
* @return {Buffer} Encoded `var_int_list`.
2015-01-02 15:27:03 +01:00
*/
encode: function(list) {
var var_ints = list.map(var_int.encode);
var bufs = [var_int.encode(list.length)].concat(var_ints);
return Buffer.concat(bufs);
2015-01-02 15:27:03 +01:00
},
};
2015-01-04 21:59:14 +01:00
2015-01-06 12:06:15 +01:00
// Very simple inet_ntop(3) equivalent.
2015-01-06 00:32:10 +01:00
function inet_ntop(buf) {
assert(buf.length === 16, "Bad buffer size");
// IPv4 mapped to IPv6.
if (bufferEqual(buf.slice(0, 12), IPv4_MAPPING)) {
return Array.prototype.join.call(buf.slice(12), ".");
// IPv6.
} else {
// TODO(Kagami): Join empty groups to make address looks nicer.
2015-01-06 00:32:10 +01:00
var groups = [];
for (var i = 0; i < 8; i++) {
groups.push(buf.readUInt16BE(i * 2, true).toString(16));
}
return groups.join(":");
}
}
/**
* Network address.
2023-01-09 02:46:20 +01:00
* @see {@link https://pybitmessage.rtfd.io/en/v0.6/protocol.html#network-address}
2015-01-06 00:32:10 +01:00
* @namespace
*/
exports.net_addr = {
2015-02-11 13:18:38 +01:00
/**
* @typedef {Object} DecodeResult
* @property {Date} time - Time the node was last active, not included
* in short mode
* @property {number} stream - Stream number of the node, not included
* in short mode
* @property {Object} services -
* [Services]{@link module:bitmessage/structs.ServicesBitfield}
* provided by the node
* @property {string} host - IPv4/IPv6 address of the node
* @property {number} port - Incoming port of the node
* @memberof module:bitmessage/structs.net_addr
*/
2015-01-06 00:32:10 +01:00
/**
* Decode `net_addr`.
* @param {Buffer} buf - A buffer that contains encoded `net_addr`
2015-02-10 19:23:20 +01:00
* @param {Object=} opts - Decoding options; use `short` option to
2015-01-31 12:51:35 +01:00
* decode `net_addr` from
* [version message]{@link module:bitmessage/messages.version}
2015-02-11 13:18:38 +01:00
* @return {DecodeResult}
* [Decoded `net_addr` structure.]{@link module:bitmessage/structs.net_addr.DecodeResult}
2015-01-06 00:32:10 +01:00
*/
decode: function(buf, opts) {
var short = !!(opts || {}).short;
var res = {};
if (short) {
assert(buf.length === 26, "Bad buffer size");
} else {
assert(buf.length === 38, "Bad buffer size");
var timeHi = buf.readUInt32BE(0, true);
var timeLo = buf.readUInt32BE(4, true);
// JavaScript's Date object can't work with timestamps higher than
2015-01-06 12:06:15 +01:00
// 8640000000000 (~2^43, ~275760 year). Hope JavaScript will
// support 64-bit numbers up to this date.
2015-01-06 00:32:10 +01:00
assert(timeHi <= 2011, "Time is too high");
assert(timeHi !== 2011 || timeLo <= 2820767744, "Time is too high");
res.time = new Date((timeHi * 4294967296 + timeLo) * 1000);
res.stream = buf.readUInt32BE(8, true);
buf = buf.slice(12);
}
2015-01-19 00:05:53 +01:00
res.services = ServicesBitfield(buf.slice(0, 8), {copy: true});
2015-01-06 00:32:10 +01:00
res.host = inet_ntop(buf.slice(8, 24));
res.port = buf.readUInt16BE(24, true);
return res;
},
/**
* Encode `net_addr`.
2015-02-11 13:18:38 +01:00
* @param {Object} opts - Encoding options
* @param {boolean=} opts.short - Encode `net_addr` for
2015-01-31 12:51:35 +01:00
* [version message]{@link module:bitmessage/messages.version}
2015-02-11 13:18:38 +01:00
* (false by default)
* @param {Date=} opts.time - Time the node was last active, not
* included in short mode (current time by default)
* @param {number=} opts.stream - Stream number of the node, not
* included in short mode (1 by default)
* @param {(Object|Buffer)=} opts.services -
2015-02-11 13:18:38 +01:00
* [Services]{@link module:bitmessage/structs.ServicesBitfield}
* provided by the node (`NODE_NETWORK` by default)
* @param {string} opts.host - IPv4/IPv6 address of the node
* @param {number} opts.port - Incoming port of the node
2015-01-06 00:32:10 +01:00
* @return {Buffer} Encoded `net_addr`.
*/
encode: function(opts) {
// Be aware of `Buffer.slice` quirk in browserify:
// <http://git.io/lNZF1A> (does not modify parent buffer's memory in
2015-01-15 18:13:02 +01:00
// old browsers). So we use offset instead of `buf = buf.slice`.
2015-01-06 00:32:10 +01:00
var buf, shift;
if (opts.short) {
buf = Buffer.alloc(26);
2015-01-06 00:32:10 +01:00
shift = 0;
} else {
buf = Buffer.alloc(38);
2015-01-06 00:32:10 +01:00
var time = opts.time || new Date();
time = Math.floor(time.getTime() / 1000);
buf.writeUInt32BE(Math.floor(time / 4294967296), 0, true); // high32
buf.writeUInt32BE(time % 4294967296, 4, true); // low32
2015-01-15 18:13:02 +01:00
var stream = opts.stream || 1;
buf.writeUInt32BE(stream, 8);
2015-01-06 00:32:10 +01:00
shift = 12;
}
2015-01-19 00:05:53 +01:00
var services = opts.services ||
ServicesBitfield().set(ServicesBitfield.NODE_NETWORK);
if (Buffer.isBuffer(services)) {
assert(services.length === 8, "Bad services buffer length");
} else {
services = services.buffer;
}
services.copy(buf, shift);
2015-01-06 00:32:10 +01:00
inet_pton(opts.host).copy(buf, shift + 8);
buf.writeUInt16BE(opts.port, shift + 24);
return buf;
},
};
2015-01-15 22:00:27 +01:00
/**
* Inventory vector.
2023-01-09 02:46:20 +01:00
* @see {@link https://pybitmessage.rtfd.io/en/v0.6/protocol.html#inventory-vectors}
2015-01-15 22:00:27 +01:00
* @namespace
*/
exports.inv_vect = {
2015-02-11 13:18:38 +01:00
// NOTE(Kagami): Only encode operation is defined because decoding of
// the encoded vector is impossible.
2015-01-15 22:00:27 +01:00
/**
* Encode inventory vector.
2015-01-31 12:51:35 +01:00
* @param {Buffer} buf - Payload to calculate the inventory vector for
* @return {Buffer} A 32-byte encoded `inv_vect`.
2015-01-15 22:00:27 +01:00
*/
encode: function(buf) {
return bmcrypto.sha512(bmcrypto.sha512(buf)).slice(0, 32);
},
};
2015-01-11 14:59:43 +01:00
/**
* Encrypted payload.
2023-01-09 02:46:20 +01:00
* @see {@link https://pybitmessage.rtfd.io/en/v0.6/protocol.html#encrypted-payload}
* @namespace encrypted
2015-01-31 12:51:35 +01:00
* @static
2015-01-11 14:59:43 +01:00
*/
2015-02-11 13:18:38 +01:00
/**
* @typedef {Object} DecodeResult
* @property {Buffer} iv - Initialization vector (16 bytes)
* @property {Buffer} ephemPrivateKey - Ephemeral private key (32 bytes)
* @property {Buffer} ciphertext - The result of encryption (variable
* size)
* @property {Buffer} mac - Message authentication code (32 bytes)
* @memberof module:bitmessage/structs.encrypted
*/
/**
2015-01-31 12:51:35 +01:00
* Decode encrypted payload.
* NOTE: all structure members are copied.
* @param {Buffer} buf - A buffer that contains encrypted payload
2015-02-11 13:18:38 +01:00
* @return {DecodeResult}
* [Decoded `encrypted` structure.]{@link module:bitmessage/structs.encrypted.DecodeResult}
2015-01-31 12:51:35 +01:00
* @function decode
* @memberof module:bitmessage/structs.encrypted
*/
/**
* Encode `encrypted`.
2015-02-11 13:18:38 +01:00
* @param {Object} opts - Encoding options
* @param {Buffer} opts.iv - Initialization vector (16 bytes)
* @param {Buffer} opts.ephemPrivateKey - Ephemeral private key (32
* bytes)
* @param {Buffer} opts.ciphertext - The result of encryption (variable
* size)
* @param {Buffer} opts.mac - Message authentication code (32 bytes)
* @return {Buffer} Encoded `encrypted` payload.
2015-01-31 12:51:35 +01:00
* @function encode
* @memberof module:bitmessage/structs.encrypted
*/
// Reexport struct.
exports.encrypted = bmcrypto.encrypted;
2015-01-11 14:59:43 +01:00
2015-01-21 19:05:00 +01:00
// Creates bitfield (MSB 0) class of the specified size.
2015-01-19 00:05:53 +01:00
var Bitfield = function(size) {
2015-01-05 00:40:52 +01:00
var bytesize = size / 8;
2015-01-19 00:05:53 +01:00
2015-01-19 13:08:56 +01:00
// Inspired by <https://github.com/fb55/bitfield>.
2015-01-19 00:05:53 +01:00
function BitfieldInner(buf, opts) {
if (!(this instanceof BitfieldInner)) {
return new BitfieldInner(buf);
}
opts = opts || {};
if (buf) {
2015-01-05 00:40:52 +01:00
assert(buf.length === bytesize, "Bad buffer size");
2015-01-19 00:05:53 +01:00
if (opts.copy) {
var dup = Buffer.alloc(bytesize);
2015-01-19 00:05:53 +01:00
dup.fill(0);
buf.copy(dup);
buf = dup;
2015-01-05 00:40:52 +01:00
}
2015-01-19 00:05:53 +01:00
} else {
buf = Buffer.alloc(bytesize);
2015-01-05 00:40:52 +01:00
buf.fill(0);
2015-01-19 00:05:53 +01:00
}
this.buffer = buf;
}
BitfieldInner.prototype.get = function(bits) {
if (!Array.isArray(bits)) {
bits = [bits];
}
var buf = this.buffer;
return bits.every(function(bit) {
assert(bit >= 0, "Bit number is too low");
assert(bit < size, "Bit number is too high");
2015-01-21 19:05:00 +01:00
var index = Math.floor(bit / 8);
var shift = 7 - (bit % 8);
return (buf[index] & (1 << shift)) !== 0; // jshint ignore:line
2015-01-19 00:05:53 +01:00
});
2015-01-05 00:40:52 +01:00
};
2015-01-19 00:05:53 +01:00
BitfieldInner.prototype.set = function(bits) {
if (!Array.isArray(bits)) {
bits = [bits];
}
var buf = this.buffer;
bits.forEach(function(bit) {
assert(bit >= 0, "Bit number is too low");
assert(bit < size, "Bit number is too high");
2015-01-21 19:05:00 +01:00
var index = Math.floor(bit / 8);
var shift = 7 - (bit % 8);
buf[index] |= 1 << shift; // jshint ignore:line
2015-01-19 00:05:53 +01:00
});
return this;
};
2015-02-23 18:55:30 +01:00
BitfieldInner.prototype.toString = function() {
var i;
var str = "";
for (i = 0; i < this.buffer.length; i++) {
// Should be faster than pushing to array and joining on v8.
str += ("0000000" + this.buffer[i].toString(2)).slice(-8);
}
return "<Bitfield:" + str + ">";
};
2015-01-19 00:05:53 +01:00
return BitfieldInner;
2015-01-04 21:59:14 +01:00
};
2015-01-05 00:40:52 +01:00
/**
2015-02-10 17:16:07 +01:00
* Service features bitfield (MSB 0).
2023-01-09 02:46:20 +01:00
* @see {@link https://pybitmessage.rtfd.io/en/v0.6/protocol.html#version}
2015-02-10 19:23:20 +01:00
* @param {Buffer=} buf - A 8-byte bitfield buffer (will be created if
2015-02-10 17:16:07 +01:00
* not provided or will be copied if `opts.copy` is `true`)
2015-02-10 19:23:20 +01:00
* @param {Object=} opts - Options
2015-02-10 14:40:57 +01:00
* @constructor
2015-01-06 00:32:10 +01:00
* @static
2015-02-10 17:16:07 +01:00
* @example
* var ServicesBitfield = require("bitmessage").structs.ServicesBitfield;
* var services = ServicesBitfield().set(ServicesBitfield.NODE_NETWORK);
* console.log(services.get(ServicesBitfield.NODE_NETWORK)); // true
* console.log(services.get(15)); // false
2015-01-05 00:40:52 +01:00
*/
2015-01-21 19:05:00 +01:00
// NOTE(Kagami): Since pubkey bitfield uses MSB 0, we use it here too.
// See <https://github.com/Bitmessage/PyBitmessage/issues/769> for
// details.
2015-01-19 00:05:53 +01:00
var ServicesBitfield = exports.ServicesBitfield = objectAssign(Bitfield(64), {
2015-01-31 12:51:35 +01:00
/**
2015-02-10 17:16:07 +01:00
* Returns a boolean indicating whether the bit is set.
* @param {number} index - Bit index (MSB 0)
* @function get
* @instance
* @return {boolean}
* @memberof module:bitmessage/structs.ServicesBitfield
*/
/**
* Set the given bit(s) to `1`.
* @param {(number|number[])} index - Bit(s) index (MSB 0)
* @function set
* @instance
* @return {Object} Returns self so methods can be chained.
* @memberof module:bitmessage/structs.ServicesBitfield
*/
2015-02-11 13:18:38 +01:00
/**
* The contents of the bitfield.
* @type {Buffer}
* @var buffer
* @instance
* @memberof module:bitmessage/structs.ServicesBitfield
*/
2015-02-10 17:16:07 +01:00
/**
* Bit index indicating normal network node.
2015-01-31 12:51:35 +01:00
* @memberof module:bitmessage/structs.ServicesBitfield
* @constant {number}
*/
2015-01-21 19:05:00 +01:00
NODE_NETWORK: 63,
/**
* Bit index indicating web/mobile client with limited network
* capabilities (proposal feature).
* @memberof module:bitmessage/structs.ServicesBitfield
* @see {@link https://bitmessage.org/wiki/Mobile_Protocol_specification}
* @constant {number}
*/
NODE_MOBILE: 62,
/**
* Bit index indicating node which can work as a WebSocket gateway for
* web/mobile clients (proposal feature).
* @memberof module:bitmessage/structs.ServicesBitfield
* @see {@link https://bitmessage.org/wiki/Mobile_Protocol_specification}
* @constant {number}
*/
NODE_GATEWAY: 61,
2015-01-05 00:40:52 +01:00
});
/**
2015-02-10 17:16:07 +01:00
* Pubkey features bitfield (MSB 0).
2023-01-09 02:46:20 +01:00
* @see {@link https://pybitmessage.rtfd.io/en/v0.6/protocol.html#pubkey-bitfield-features}
2015-02-10 19:23:20 +01:00
* @param {Buffer=} buf - A 4-byte bitfield buffer (will be created if
2015-02-10 17:16:07 +01:00
* not provided or will be copied if `opts.copy` is `true`)
2015-02-10 19:23:20 +01:00
* @param {Object=} opts - Options
2015-02-10 14:40:57 +01:00
* @constructor
2015-02-10 17:16:07 +01:00
* @example
* var PubkeyBitfield = require("bitmessage").structs.PubkeyBitfield;
* var behavior = PubkeyBitfield().set([
* PubkeyBitfield.INCLUDE_DESTINATION,
* PubkeyBitfield.DOES_ACK,
* ]).set(1);
* console.log(behavior.get(PubkeyBitfield.DOES_ACK)); // true
* console.log(behavior.get(15)); // false
2015-01-05 00:40:52 +01:00
*/
2015-01-19 00:05:53 +01:00
exports.PubkeyBitfield = objectAssign(Bitfield(32), {
2015-01-05 00:40:52 +01:00
/**
2015-02-10 17:16:07 +01:00
* Returns a boolean indicating whether the bit is set.
* @param {number} index - Bit index (MSB 0)
* @function get
* @instance
* @return {boolean}
* @memberof module:bitmessage/structs.PubkeyBitfield
*/
/**
* Set the given bit(s) to `1`.
* @param {(number|number[])} index - Bit(s) index (MSB 0)
* @function set
* @instance
* @return {Object} Returns self so methods can be chained.
* @memberof module:bitmessage/structs.PubkeyBitfield
*/
2015-02-11 13:18:38 +01:00
/**
* The contents of the bitfield.
* @type {Buffer}
* @var buffer
* @instance
* @memberof module:bitmessage/structs.PubkeyBitfield
*/
2015-02-10 17:16:07 +01:00
/**
* Bit index.
* If set, the receiving node does send acknowledgements (rather than
* dropping them).
2015-01-31 12:51:35 +01:00
* @memberof module:bitmessage/structs.PubkeyBitfield
* @constant {number}
2015-01-05 00:40:52 +01:00
*/
DOES_ACK: 31,
2015-01-21 19:05:00 +01:00
/**
2015-02-10 17:16:07 +01:00
* Bit index.
* If set, the receiving node expects that the RIPEMD hash encoded in
* their address preceedes the encrypted message data of msg messages
* bound for them.
2015-01-31 12:51:35 +01:00
* @memberof module:bitmessage/structs.PubkeyBitfield
* @constant {number}
2015-01-21 19:05:00 +01:00
*/
INCLUDE_DESTINATION: 30,
2015-01-05 00:40:52 +01:00
});