minor refactor

This commit is contained in:
poma 2021-09-15 20:01:17 +03:00
parent 29021a8028
commit c775fc35f4
No known key found for this signature in database
GPG Key ID: BA20CB01FE165657
3 changed files with 899 additions and 486 deletions

1363
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,8 @@
{
"name": "fixed-merkle-tree",
"version": "0.5.1",
"version": "0.6.0",
"description": "Fixed depth merkle tree implementation with sequential inserts",
"repository": "https://github.com/tornadocash/fixed-merkle-tree.git",
"main": "src/merkleTree.js",
"scripts": {
"test": "mocha",

View File

@ -25,19 +25,18 @@ class MerkleTree {
constructor(levels, elements = [], { hashFunction, zeroElement = DEFAULT_ZERO } = {}) {
this.levels = levels
this.capacity = 2 ** levels
this.zeroElement = zeroElement
this._hash = hashFunction || defaultHash
if (elements.length > this.capacity) {
throw new Error('Tree is full')
}
this._hash = hashFunction || defaultHash
this.zeroElement = zeroElement
this._zeros = []
this._layers = []
this._layers[0] = elements
this._zeros[0] = this.zeroElement
this._zeros[0] = zeroElement
for (let i = 1; i <= levels; i++) {
this._zeros[i] = this._hash(this._zeros[i - 1], this._zeros[i - 1])
}
this._layers = []
this._layers[0] = elements.slice()
this._rebuild()
}
@ -152,6 +151,14 @@ class MerkleTree {
return this._layers[0].slice()
}
/**
* Returns a copy of n-th zero elements array
* @returns {Object[]}
*/
zeros() {
return this._zeros.slice()
}
/**
* Serialize entire tree state including intermediate layers into a plain object
* Deserializing it back will not require to recompute any hashes