protocol: optimize framer.

This commit is contained in:
Christopher Jeffrey 2016-07-27 05:40:57 -07:00
parent 20d69b7cbc
commit cd8adbcc74
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD

View File

@ -33,42 +33,6 @@ function Framer(options) {
this.bip151 = options.bip151;
}
/**
* Create a header for a payload.
* @param {String} cmd - Packet type.
* @param {Buffer} payload
* @returns {Buffer} Header.
*/
Framer.prototype.header = function header(cmd, payload, checksum) {
var h = new Buffer(24);
var len, i;
cmd = new Buffer(cmd, 'ascii');
assert(cmd.length < 12);
assert(payload.length <= 0xffffffff);
// Magic value
h.writeUInt32LE(this.network.magic, 0, true);
// Command
len = cmd.copy(h, 4);
for (i = 4 + len; i < 4 + 12; i++)
h[i] = 0;
// Payload length
h.writeUInt32LE(payload.length, 16, true);
if (!checksum)
checksum = utils.hash256(payload);
// Checksum
checksum.copy(h, 20, 0, 4);
return h;
};
/**
* Frame a payload with a header.
* @param {String} cmd - Packet type.
@ -77,16 +41,39 @@ Framer.prototype.header = function header(cmd, payload, checksum) {
*/
Framer.prototype.packet = function packet(cmd, payload, checksum) {
var header;
var i, packet;
assert(payload, 'No payload.');
if (this.bip151 && this.bip151.handshake)
return this.bip151.packet(cmd, payload);
header = this.header(cmd, payload, checksum);
assert(cmd.length < 12);
assert(payload.length <= 0xffffffff);
return Buffer.concat([header, payload]);
packet = new Buffer(24 + payload.length);
// Magic value
packet.writeUInt32LE(this.network.magic, 0, true);
// Command
packet.write(cmd, 4, 'ascii');
for (i = 4 + cmd.length; i < 16; i++)
packet[i] = 0;
// Payload length
packet.writeUInt32LE(payload.length, 16, true);
if (!checksum)
checksum = utils.hash256(payload);
// Checksum
checksum.copy(packet, 20, 0, 4);
payload.copy(packet, 24);
return packet;
};
/**