diff --git a/lib/bcoin/bip151.js b/lib/bcoin/bip151.js index 662813dc..f462b084 100644 --- a/lib/bcoin/bip151.js +++ b/lib/bcoin/bip151.js @@ -70,7 +70,8 @@ function BIP151Stream(cipher, key) { this.chacha = new chachapoly.ChaCha20(); this.aead = new chachapoly.AEAD(); this.tag = null; - this.seq = 0; + this.seqHi = 0; + this.seqLo = 0; this.highWaterMark = 1024 * (1 << 20); this.processed = 0; @@ -106,7 +107,8 @@ BIP151Stream.prototype.init = function init(publicKey) { this.k2 = utils.hkdfExpand(this.prk, INFO_KEY2, 32, 'sha256'); this.sid = utils.hkdfExpand(this.prk, INFO_SID, 32, 'sha256'); - this.seq = 0; + this.seqHi = 0; + this.seqLo = 0; this.chacha.init(this.k1, this.iv()); this.aead.init(this.k2, this.iv()); @@ -153,17 +155,18 @@ BIP151Stream.prototype.rekey = function rekey() { /** * Increment packet sequence number and update IVs - * (note, sequence number overflows after 2^32-1). + * (note, sequence number overflows after 2^64-1). * The IV will be updated without reinitializing * cipher state. */ BIP151Stream.prototype.sequence = function sequence() { - this.seq++; - // Wrap sequence number a la openssh. - if (this.seq === 0x100000000) - this.seq = 0; + if (++this.seqLo === 0x100000000) { + this.seqLo = 0; + if (++this.seqHi === 0x100000000) + this.seqHi = 0; + } // State of the ciphers is // unaltered aside from the iv. @@ -178,7 +181,8 @@ BIP151Stream.prototype.sequence = function sequence() { BIP151Stream.prototype.iv = function iv() { var p = bcoin.writer(); - p.writeU64(this.seq); + p.writeU32(this.seqLo); + p.writeU32(this.seqHi); p.writeU32(0); return p.render(); };