serialization

This commit is contained in:
poma 2020-09-23 19:22:14 +03:00
parent 53cb08d9b9
commit 96e254a46b
No known key found for this signature in database
GPG Key ID: BA20CB01FE165657
3 changed files with 46 additions and 1 deletions

@ -1,6 +1,6 @@
{
"name": "fixed-merkle-tree",
"version": "0.3.4",
"version": "0.4.0",
"description": "Fixed depth merkle tree implementation with sequential inserts",
"main": "src/merkleTree.js",
"scripts": {

@ -152,6 +152,36 @@ class MerkleTree {
elements() {
return this._layers[0].slice()
}
/**
* Serialize entire tree state including intermediate layers into a plain object
* Deserializing it back will not require to recompute any hashes
* Elements are not converted to a plain type, this is responsibility of the caller
*/
serialize() {
return {
levels: this.levels,
capacity: this.capacity,
zeroElement: this.zeroElement,
_zeros: this._zeros,
_layers: this._layers,
}
}
/**
* Deserialize data into a MerkleTree instance
* Make sure to provide the same hashFunction as was used in the source tree,
* otherwise the tree state will be invalid
*
* @param data
* @param hashFunction
* @returns {MerkleTree}
*/
static deserialize(data, hashFunction) {
const instance = Object.assign(Object.create(this.prototype), data)
instance._hash = hashFunction || defaultHash
return instance
}
}
module.exports = MerkleTree

@ -202,4 +202,19 @@ describe('MerkleTree', () => {
])
})
})
describe('#serialize', () => {
it('should work', () => {
const src = new MerkleTree(10, [1, 2, 3])
const data = src.serialize()
const dst = MerkleTree.deserialize(data)
src.root().should.equal(dst.root())
src.insert(10)
dst.insert(10)
src.root().should.equal(dst.root())
})
})
})