diff --git a/lib/bcoin/block.js b/lib/bcoin/block.js index 46311e57..c0858b1c 100644 --- a/lib/bcoin/block.js +++ b/lib/bcoin/block.js @@ -14,7 +14,7 @@ var constants = bcoin.protocol.constants; function Block(data, subtype) { var self = this; - var tx; + var tx, height; if (!(this instanceof Block)) return new Block(data, subtype); @@ -61,8 +61,11 @@ function Block(data, subtype) { if (this.version >= 2) { tx = this.txs[0]; - if (tx && tx.inputs[0] && +tx.inputs[0].out.hash === 0) - this._height = bcoin.script.coinbase(tx.inputs[0].script); + if (tx && tx.inputs[0] && +tx.inputs[0].out.hash === 0) { + var height = bcoin.script.coinbaseHeight(tx.inputs[0].script); + if (height > 0) + this._height = height; + } } this.invalid = !this._checkBlock(); diff --git a/lib/bcoin/script.js b/lib/bcoin/script.js index 0c9e7751..76ab1f76 100644 --- a/lib/bcoin/script.js +++ b/lib/bcoin/script.js @@ -1138,20 +1138,40 @@ script.isScripthashInput = function isScripthashInput(s, redeem) { return keys; }; -script.coinbase = function coinbase(s) { - var base = s._raw || script.encode(s); - var len = Math.min(base[0], base.length); - var height = 0; - var i, b; +script.coinbaseHeight = function coinbaseHeight(s) { + var raw = s._raw || script.encode(s); + var height; - for (i = 0; i < len; i++) { - b = base[i + 1] & 0xff; - height |= b << (8 * i); - } + if (!Array.isArray(s[0])) + return -1; + + if (raw[0] < 0x03 || s[0].length < 3) + return -1; + + height = new bn(s[0].reverse()).toNumber(); + + // Last v1 block + if (height < 227835) + return -1; return height; }; +script.coinbase = function coinbase(s) { + var raw = s._raw || script.encode(s); + var data = script.coinbaseHeight(s); + + if (height > 0) + raw = raw.slice(raw[0] + 1); + + return { + height: height, + script: s, + data: raw, + text: utils.array2utf8(raw) + }; +}; + // https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki /** * A canonical signature exists of: <30> <02> <02>