diff --git a/lib/bcoin/coin.js b/lib/bcoin/coin.js index 6385ecca..5338b9e3 100644 --- a/lib/bcoin/coin.js +++ b/lib/bcoin/coin.js @@ -127,6 +127,49 @@ Coin.fromJSON = function fromJSON(json) { }); }; +// Not totally necessary, but this is 3 times +// faster than JSON serialization if high performance +// is a goal. +Coin.prototype.toRaw = function toRaw(enc) { + var script = bcoin.script.encode(this.script); + var height = this.height; + var data = new Buffer(48 + script.length); + + if (height === -1) + height = 0xffffffff; + + utils.copy(utils.toArray(this.hash, 'hex'), data, 0); + utils.writeU32BE(data, this.index, 32); + utils.writeU32BE(data, height, 36); + utils.write64BE(data, this.value, 40); + utils.copy(script, data, 48); + + if (enc === 'hex') + data = utils.toHex(data); + + return data; +}; + +Coin.fromRaw = function fromRaw(data, enc) { + var height; + + if (enc === 'hex') + data = utils.toArray(data, 'hex'); + + height = utils.readU32BE(data, 36); + + if (height === 0xffffffff) + height = -1; + + return new Coin({ + hash: utils.toHex(data.slice(0, 32)), + index: utils.readU32BE(data, 32), + height: height, + value: utils.read64BE(data, 40), + script: bcoin.script.decode(utils.toArray(data.slice(48))) + }); +}; + /** * Expose */ diff --git a/lib/bcoin/output.js b/lib/bcoin/output.js index e3ef3c78..d58cf134 100644 --- a/lib/bcoin/output.js +++ b/lib/bcoin/output.js @@ -287,6 +287,9 @@ Output.prototype.inspect = function inspect() { n: this.n, text: this.text, locktime: this.locktime, + hash: this.hash, + index: this.index, + height: this.height, value: utils.btc(this.value), script: bcoin.script.format(this.script) };