minor refactor

This commit is contained in:
poma 2021-09-15 19:54:57 +03:00
parent 29021a8028
commit 2b6b5c481d
No known key found for this signature in database
GPG Key ID: BA20CB01FE165657
3 changed files with 900 additions and 487 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

@ -22,22 +22,21 @@ class MerkleTree {
* @param {hashFunction} [options.hashFunction] Function used to hash 2 leaves
* @param [options.zeroElement] Value for non-existent leaves
*/
constructor(levels, elements = [], { hashFunction, zeroElement = DEFAULT_ZERO } = {}) {
constructor(levels, elements = [], { hashFunction = defaultHash, 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
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