2 Commits

Author SHA1 Message Date
poma
4f6ff9b777 simpler serialization 2020-09-25 17:16:01 +03:00
poma
96e254a46b serialization 2020-09-23 19:22:14 +03:00
3 changed files with 46 additions and 1 deletions

View File

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

View File

@@ -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,
_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
instance.capacity = 1 << instance.levels
instance.zeroElement = instance._zeros[0]
return instance
}
}
module.exports = MerkleTree

View File

@@ -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())
})
})
})