1 Commits

Author SHA1 Message Date
9cf202ce36 Update dependencies & fix package name to self-hosted registry 2023-09-18 01:31:37 -07:00
8 changed files with 9430 additions and 298 deletions

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
@tornado:registry=https://git.tornado.ws/api/packages/tornado-packages/npm/

View File

@@ -1,7 +0,0 @@
{
"semi": false,
"arrowParens": "always",
"singleQuote": true,
"printWidth": 110,
"trailingComma": "all"
}

9550
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,12 @@
{
"name": "fixed-merkle-tree",
"version": "1.0.0",
"name": "@tornado/fixed-merkle-tree",
"version": "0.3.4",
"description": "Fixed depth merkle tree implementation with sequential inserts",
"repository": "https://github.com/tornadocash/fixed-merkle-tree.git",
"main": "src/merkleTree.js",
"repository": {
"type": "git",
"url": "https://git.tornado.ws/tornado-packages/fixed-merkle-tree.git"
},
"scripts": {
"test": "mocha",
"lint": "eslint ."
@@ -18,6 +21,10 @@
"files": [
"src/*"
],
"dependencies": {
"@tornado/circomlib": "^0.0.21",
"@tornado/snarkjs": "^0.1.20"
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"chai": "^4.2.0",

View File

@@ -1,5 +1,9 @@
const defaultHash = require('./sha256')
// keccak256("tornado") % BN254_FIELD_SIZE
const DEFAULT_ZERO = '21663839004416932945382355908790599225266501822907911457504978515578255421292'
const defaultHash = require('./mimc')
// todo ensure consistent types in tree and inserted elements?
// todo make sha3 default hasher (and update tests) to get rid of mimc/snarkjs/circomlib dependency
/**
* @callback hashFunction
@@ -18,21 +22,22 @@ 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 = 0 } = {}) {
constructor(levels, elements = [], { hashFunction, zeroElement = DEFAULT_ZERO } = {}) {
this.levels = levels
this.capacity = 2 ** levels
this.capacity = 1 << 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._zeros[0] = zeroElement
this._layers = []
this._layers[0] = elements
this._zeros[0] = this.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()
}
@@ -42,9 +47,9 @@ class MerkleTree {
for (let i = 0; i < Math.ceil(this._layers[level - 1].length / 2); i++) {
this._layers[level][i] = this._hash(
this._layers[level - 1][i * 2],
i * 2 + 1 < this._layers[level - 1].length
? this._layers[level - 1][i * 2 + 1]
: this._zeros[level - 1],
i * 2 + 1 < this._layers[level - 1].length ?
this._layers[level - 1][i * 2 + 1] :
this._zeros[level - 1],
)
}
}
@@ -70,30 +75,15 @@ class MerkleTree {
}
/**
* Insert multiple elements into the tree.
* Insert multiple elements into the tree. Tree will be fully rebuilt during this operation.
* @param {Array} elements Elements to insert
*/
bulkInsert(elements) {
if (this._layers[0].length + elements.length > this.capacity) {
throw new Error('Tree is full')
}
// First we insert all elements except the last one
// updating only full subtree hashes (all layers where inserted element has odd index)
// the last element will update the full path to the root making the tree consistent again
for (let i = 0; i < elements.length - 1; i++) {
this._layers[0].push(elements[i])
let level = 0
let index = this._layers[0].length - 1
while (index % 2 === 1) {
level++
index >>= 1
this._layers[level][index] = this._hash(
this._layers[level - 1][index * 2],
this._layers[level - 1][index * 2 + 1],
)
}
}
this.insert(elements[elements.length - 1])
this._layers[0].push(...elements)
this._rebuild()
}
/**
@@ -110,9 +100,9 @@ class MerkleTree {
index >>= 1
this._layers[level][index] = this._hash(
this._layers[level - 1][index * 2],
index * 2 + 1 < this._layers[level - 1].length
? this._layers[level - 1][index * 2 + 1]
: this._zeros[level - 1],
index * 2 + 1 < this._layers[level - 1].length ?
this._layers[level - 1][index * 2 + 1] :
this._zeros[level - 1],
)
}
}
@@ -130,8 +120,9 @@ class MerkleTree {
const pathIndices = []
for (let level = 0; level < this.levels; level++) {
pathIndices[level] = index % 2
pathElements[level] =
(index ^ 1) < this._layers[level].length ? this._layers[level][index ^ 1] : this._zeros[level]
pathElements[level] = (index ^ 1) < this._layers[level].length ?
this._layers[level][index ^ 1] :
this._zeros[level]
index >>= 1
}
return {
@@ -161,44 +152,6 @@ class MerkleTree {
elements() {
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
* 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 = 2 ** instance.levels
instance.zeroElement = instance._zeros[0]
return instance
}
}
module.exports = MerkleTree

4
src/mimc.js Normal file
View File

@@ -0,0 +1,4 @@
const { mimcsponge } = require("@tornado/circomlib");
const { bigInt } = require("@tornado/snarkjs");
module.exports = (left, right) =>
mimcsponge.multiHash([bigInt(left), bigInt(right)]).toString();

View File

@@ -1,15 +0,0 @@
const crypto = require('crypto')
function toBuffer256(number) {
return Buffer.from(number.toString(16).padStart(512, '0'), 'hex')
}
function sha256(left, right) {
return crypto
.createHash('sha256')
.update(toBuffer256(left))
.update(toBuffer256(right))
.digest('hex')
}
module.exports = sha256

View File

@@ -71,32 +71,6 @@ describe('MerkleTree', () => {
tree.root().should.equal('10132905325673518287563057607527946096399700874345297651940963130460267058606')
})
it('should give the same result as sequental inserts', () => {
const initialArray = [
[1],
[1, 2],
[1, 2, 3],
[1, 2, 3, 4],
]
const insertedArray = [
[11],
[11, 12],
[11, 12, 13],
[11, 12, 13, 14],
]
for (const initial of initialArray) {
for (const inserted of insertedArray) {
const tree1 = new MerkleTree(10, initial)
const tree2 = new MerkleTree(10, initial)
tree1.bulkInsert(inserted)
for (const item of inserted) {
tree2.insert(item)
}
tree1.root().should.equal(tree2.root())
}
}
}).timeout(10000)
it('should work with max elements', () => {
const tree = new MerkleTree(2, [1, 2])
tree.bulkInsert([3, 4])
@@ -228,19 +202,4 @@ 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())
})
})
})