From 810e4f5ea75056b216c9e7ad4c6edff34849c55b Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Sun, 18 May 2014 12:32:56 -0500 Subject: [PATCH] block: add toJSON and fromJSON to Block. Signed-off-by: Fedor Indutny --- lib/bcoin/block.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) 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; +};