block: add toJSON and fromJSON to Block.

Signed-off-by: Fedor Indutny <fedor@indutny.com>
This commit is contained in:
Christopher Jeffrey 2014-05-18 12:32:56 -05:00 committed by Fedor Indutny
parent f3c9ebd9a5
commit 810e4f5ea7

View File

@ -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;
};