From db0552874bbca4fc5d64199336d4d52c026d4318 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Wed, 27 Jul 2016 03:59:24 -0700 Subject: [PATCH] bip151: more micro-optimization. --- lib/bcoin/bip151.js | 35 ++++++++++++++--------------------- 1 file changed, 14 insertions(+), 21 deletions(-) diff --git a/lib/bcoin/bip151.js b/lib/bcoin/bip151.js index 8180f31f..ba150125 100644 --- a/lib/bcoin/bip151.js +++ b/lib/bcoin/bip151.js @@ -72,6 +72,8 @@ function BIP151Stream(cipher, key) { this.tag = null; this.seqHi = 0; this.seqLo = 0; + this.iv = new Buffer(12); + this.iv.fill(0); this.highWaterMark = 1024 * (1 << 20); this.processed = 0; @@ -92,7 +94,6 @@ utils.inherits(BIP151Stream, EventEmitter); BIP151Stream.prototype.init = function init(publicKey) { var p = bcoin.writer(); - var iv; this.publicKey = publicKey; this.secret = bcoin.ec.ecdh(this.publicKey, this.privateKey); @@ -108,10 +109,10 @@ BIP151Stream.prototype.init = function init(publicKey) { this.seqHi = 0; this.seqLo = 0; - iv = this.iv(); + this.update(); - this.chacha.init(this.k1, iv); - this.aead.init(this.k2, iv); + this.chacha.init(this.k1, this.iv); + this.aead.init(this.k2, this.iv); this.lastRekey = utils.now(); }; @@ -142,8 +143,6 @@ BIP151Stream.prototype.maybeRekey = function maybeRekey(data) { */ BIP151Stream.prototype.rekey = function rekey() { - var iv; - assert(this.prk, 'Cannot rekey before initialization.'); // All state is reinitialized @@ -151,10 +150,8 @@ BIP151Stream.prototype.rekey = function rekey() { this.k1 = utils.hash256(this.k1); this.k2 = utils.hash256(this.k2); - iv = this.iv(); - - this.chacha.init(this.k1, iv); - this.aead.init(this.k2, iv); + this.chacha.init(this.k1, this.iv); + this.aead.init(this.k2, this.iv); }; /** @@ -165,8 +162,6 @@ BIP151Stream.prototype.rekey = function rekey() { */ BIP151Stream.prototype.sequence = function sequence() { - var iv; - // Wrap sequence number a la openssh. if (++this.seqLo === 0x100000000) { this.seqLo = 0; @@ -174,12 +169,12 @@ BIP151Stream.prototype.sequence = function sequence() { this.seqHi = 0; } - iv = this.iv(); + this.update(); // State of the ciphers is // unaltered aside from the iv. - this.chacha.init(null, iv); - this.aead.init(null, iv); + this.chacha.init(null, this.iv); + this.aead.init(null, this.iv); }; /** @@ -187,12 +182,10 @@ BIP151Stream.prototype.sequence = function sequence() { * @returns {Buffer} */ -BIP151Stream.prototype.iv = function _iv() { - var iv = new Buffer(12); - iv.writeUInt32LE(this.seqLo, 0, true); - iv.writeUInt32LE(this.seqHi, 4, true); - iv.writeUInt32LE(0, 8, true); - return iv; +BIP151Stream.prototype.update = function update() { + this.iv.writeUInt32LE(this.seqLo, 0, true); + this.iv.writeUInt32LE(this.seqHi, 4, true); + return this.iv; }; /**