bip151: more micro-optimization.

This commit is contained in:
Christopher Jeffrey 2016-07-27 03:59:24 -07:00
parent 227e9a18b2
commit db0552874b
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD

View File

@ -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;
};
/**