From 6e2b58c16df918b7b2ab55267766829abf2ea037 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Thu, 21 Apr 2016 23:11:14 -0700 Subject: [PATCH] script and reader. --- lib/bcoin/reader.js | 5 +++-- lib/bcoin/script.js | 2 +- lib/bcoin/utils.js | 19 +++++++++++++++++-- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/lib/bcoin/reader.js b/lib/bcoin/reader.js index d5ef5044..b67921fd 100644 --- a/lib/bcoin/reader.js +++ b/lib/bcoin/reader.js @@ -447,12 +447,13 @@ BufferReader.prototype.readNullString = function readNullString(enc) { /** * Read a varint. + * @param {Boolean?} big - Whether to read as a big number. * @returns {Number} */ -BufferReader.prototype.readVarint = function readVarint() { +BufferReader.prototype.readVarint = function readVarint(big) { assert(this.offset + 1 <= this.data.length); - var result = utils.readVarint(this.data, this.offset); + var result = utils.readVarint(this.data, this.offset, big); assert(result.off <= this.data.length); assert(result.r >= 0); this.offset = result.off; diff --git a/lib/bcoin/script.js b/lib/bcoin/script.js index 64b346a0..37469d50 100644 --- a/lib/bcoin/script.js +++ b/lib/bcoin/script.js @@ -3366,7 +3366,7 @@ Script.format = function format(code) { } } size = chunk.length.toString(16); - if (size.length < 2) + while (size.length % 2 !== 0) size = '0' + size; if (!constants.opcodesByVal[op]) { op = op.toString(16); diff --git a/lib/bcoin/utils.js b/lib/bcoin/utils.js index c31c381c..72481d26 100644 --- a/lib/bcoin/utils.js +++ b/lib/bcoin/utils.js @@ -2003,25 +2003,40 @@ utils.write64BE = function write64BE(dst, num, off) { * Read a varint. * @param {Buffer} arr * @param {Number} off + * @param {Boolean?} big - Whether to read as a big number. * @returns {Number} */ -utils.readVarint = function readVarint(arr, off) { +utils.readVarint = function readVarint(arr, off, big) { var r, bytes; off = off >>> 0; + assert(off < arr.length); + if (arr[off] < 0xfd) { r = arr[off]; + if (big) + r = new bn(r); bytes = 1; } else if (arr[off] === 0xfd) { + assert(off + 2 < arr.length); r = arr[off + 1] | (arr[off + 2] << 8); + if (big) + r = new bn(r); bytes = 3; } else if (arr[off] === 0xfe) { + assert(off + 4 < arr.length); r = utils.readU32(arr, off + 1); + if (big) + r = new bn(r); bytes = 5; } else if (arr[off] === 0xff) { - r = utils.readU64N(arr, off + 1); + assert(off + 8 < arr.length); + if (big) + r = utils.readU64(arr, off + 1); + else + r = utils.readU64N(arr, off + 1); bytes = 9; } else { assert(false, 'Malformed varint.');