diff --git a/lib/bcoin/bip70/protobuf.js b/lib/bcoin/bip70/protobuf.js index 9e9a83e0..a077067a 100644 --- a/lib/bcoin/bip70/protobuf.js +++ b/lib/bcoin/bip70/protobuf.js @@ -160,18 +160,20 @@ ProtoWriter.prototype.writeVarint = function writeVarint(num) { this.writeBytes(buf); }; -ProtoWriter.prototype.writeFieldValue = function writeFieldValue(tag, value) { +ProtoWriter.prototype.writeFieldVarint = function writeFieldVarint(tag, value) { var header = (tag << 3) | wireType.VARINT; this.writeVarint(header); this.writeVarint(value); }; ProtoWriter.prototype.writeFieldU64 = function writeFieldU64(tag, value) { - this.writeFieldValue(tag, value); + assert(utils.isSafeInteger(value)); + this.writeFieldVarint(tag, value); }; ProtoWriter.prototype.writeFieldU32 = function writeFieldU32(tag, value) { - this.writeFieldValue(tag, value); + assert(value <= 0xffffffff); + this.writeFieldVarint(tag, value); }; ProtoWriter.prototype.writeFieldBytes = function writeFieldBytes(tag, data) { @@ -199,7 +201,21 @@ exports.readVarint = function readVarint(data, off) { } ch = data[off++]; assert(size + 1 < 6, 'Number exceeds 2^53-1.'); - num += (ch & 0x7f) * Math.pow(2, 7 * size); + // Optimization for javascript insanity. + switch (size) { + case 0: + case 1: + case 2: + case 3: + num += (ch & 0x7f) << (7 * size); + break; + case 4: + num += (ch & 0x7f) * (1 << (7 * size)); + break; + default: + num += (ch & 0x7f) * Math.pow(2, 7 * size); + break; + } size++; }