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

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

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