diff --git a/lib/bcoin/block.js b/lib/bcoin/block.js index 8ba5b785..6c67be5a 100644 --- a/lib/bcoin/block.js +++ b/lib/bcoin/block.js @@ -107,3 +107,30 @@ Block.prototype._verifyMerkle = function verifyMerkle() { return utils.toHex(utils.dsha256(left + right, 'hex')); } }; + +Block.prototype.toJSON = function toJSON() { + return { + v: '1', + type: 'block', + subtype: this.subtype, + hash: this._hash || this.hash('hex'), + prevBlock: this.prevBlock, + ts: this.ts, + block: utils.toHex(bcoin.protocol.framer.block(this, this.subtype)) + }; +}; + +Block.fromJSON = function fromJSON(json) { + utils.assert.equal(json.v, 1); + utils.assert.equal(json.type, 'block'); + + var raw = utils.toArray(json.block, 'hex'); + + var block = new bcoin.block(json.subtype === 'merkleblock' + ? new bcoin.protocol.parser().parseMerkleBlock(raw) + : new bcoin.protocol.parser().parseBlock(raw), type); + + block._hash = json.hash; + + return block; +};