This commit is contained in:
poma 2020-07-31 04:00:33 +03:00
commit 932a2ed587
No known key found for this signature in database
GPG Key ID: BA20CB01FE165657
9 changed files with 4911 additions and 0 deletions

9
.editorconfig Normal file
View File

@ -0,0 +1,9 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

26
.eslintrc Normal file
View File

@ -0,0 +1,26 @@
{
"env": {
"node": true,
"browser": true,
"es6": true,
"mocha": true
},
"extends": "eslint:recommended",
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 2018
},
"rules": {
"indent": ["error", 2],
"linebreak-style": ["error", "unix"],
"quotes": ["error", "single"],
"semi": ["error", "never"],
"object-curly-spacing": ["error", "always"],
"comma-dangle": ["error", "always-multiline"],
"require-await": "error"
}
}

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules

31
README.md Normal file
View File

@ -0,0 +1,31 @@
# Merkle Tree
This is a fixed depth merkle tree implementation with sequential inserts
## Usage
```javascript
const MerkleTree = require('MerkleTree')
const tree = new MerkleTree(10, [1, 2, 3, 4, 5])
tree.insert(6)
tree.update(3, 42)
const proof = tree.proof(tree.indexOf(2))
console.log(proof)
// output:
{
pathIndex: [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
pathElements: [
'42',
'19814528709687996974327303300007262407299502847885145507292406548098437687919',
'11545490348087423460235196042660837039811055736960842865648632633825765931887',
'14506027710748750947258687001455876266559341618222612722926156490737302846427',
'4766583705360062980279572762279781527342845808161105063909171241304075622345',
'16640205414190175414380077665118269450294358858897019640557533278896634808665',
'13024477302430254842915163302704885770955784224100349847438808884122720088412',
'11345696205391376769769683860277269518617256738724086786512014734609753488820',
'17235543131546745471991808272245772046758360534180976603221801364506032471936',
'155962837046691114236524362966874066300454611955781275944230309195800494087'
]
}
```

4600
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "merkle-tree",
"version": "1.0.0",
"description": "",
"main": "src/merkleTree.js",
"scripts": {
"test": "mocha"
},
"keywords": [],
"author": "Roman Semenov <semenov.roma@gmail.com>",
"license": "ISC",
"dependencies": {
"snarkjs": "git+https://github.com/tornadocash/snarkjs.git#869181cfaf7526fe8972073d31655493a04326d5",
"circomlib": "git+https://github.com/tornadocash/circomlib.git#c372f14d324d57339c88451834bf2824e73bbdbc"
},
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^8.1.0"
}
}

91
src/merkleTree.js Normal file
View File

@ -0,0 +1,91 @@
// 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
class MerkleTree {
constructor(levels, elements = [], zeroElement = DEFAULT_ZERO, hashFunction) {
this.levels = levels
this.capacity = 2 << levels
this.zeroElement = zeroElement
this._hash = hashFunction ?? defaultHash
this._zeros = []
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._rebuild()
}
_rebuild() {
for (let level = 1; level <= this.levels; level++) {
this._layers[level] = []
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],
this._layers[level - 1]?.[i * 2 + 1] ?? this._zeros[level - 1]
)
}
}
}
root() {
return this._layers[this.levels]?.[0] ?? this._zeros[this.levels]
}
insert(element) {
if (this._layers[0].length >= this.capacity) {
throw new Error('Tree is full')
}
this.update(this._layers[0].length, element)
}
bulkInsert(elements) {
if (this._layers[0].length + elements > this.capacity) {
throw new Error('Tree is full')
}
this._layers[0].push(...elements)
this._rebuild()
}
update(index, element) {
if (index < 0 || index > this._layers[0].length || index >= this.capacity) {
throw new Error('Insert index out of bounds: ' + index)
}
this._layers[0][index] = element
for (let level = 1; level <= this.levels; level++) {
index >>= 1
this._layers[level][index] = this._hash(
this._layers[level - 1][index * 2],
this._layers[level - 1]?.[index * 2 + 1] ?? this._zeros[level - 1]
)
}
}
proof(index) {
if (index < 0 || index >= this._layers[0].length) {
throw new Error('Index out of bounds: ' + index)
}
const pathElements = []
const pathIndex = []
for (let level = 0; level < this.levels; level++) {
pathIndex[level] = index % 2
pathElements[level] = this._layers[level]?.[index ^ 1] ?? this._zeros[level]
index >>= 1
}
return {
pathElements,
pathIndex,
}
}
indexOf(element) {
return this._layers[0].indexOf(element)
}
}
module.exports = MerkleTree

3
src/mimc.js Normal file
View File

@ -0,0 +1,3 @@
const { mimcsponge } = require('circomlib')
const { bigInt } = require('snarkjs')
module.exports = (left, right) => mimcsponge.multiHash([bigInt(left), bigInt(right)]).toString()

130
test/merkleTree.test.js Normal file
View File

@ -0,0 +1,130 @@
const MerkleTree = require('../src/merkleTree')
require('chai').should()
// todo negative test cases for:
// - full tree
// - invalid indexes
describe('MerkleTree', () => {
describe('#constructor', () => {
it('should have correct zero root', () => {
const tree = new MerkleTree(10, [1, 2, 3, 4, 5])
tree.insert(6)
tree.update(3, 42)
const proof = tree.proof(tree.indexOf(3))
console.log(proof)
// const tree = new MerkleTree(10)
// return tree.root().should.equal('14030416097908897320437553787826300082392928432242046897689557706485311282736')
})
it('should have correct 1 element root', () => {
const tree = new MerkleTree(10, [1])
return tree.root().should.equal('8423266420989796135179818298985240707844287090553672312129988553683991994663')
})
it('should have correct even elements root', () => {
const tree = new MerkleTree(10, [1, 2])
return tree.root().should.equal('6632020347849276860492323008882350357301732786233864934344775324188835172576')
})
it('should have correct odd elements root', () => {
const tree = new MerkleTree(10, [1, 2, 3])
return tree.root().should.equal('13605252518346649016266481317890801910232739395710162921320863289825142055129')
})
})
describe('#insert', () => {
it('should insert into empty tree', () => {
const tree = new MerkleTree(10)
tree.insert(42)
return tree.root().should.equal('5305397050004975530787056746976521882221645950652996479084366175595194436378')
})
it('should insert into odd tree', () => {
const tree = new MerkleTree(10, [1])
tree.insert(42)
return tree.root().should.equal('4732716818150428188641303198013632061441036732749853605989871103991103096471')
})
it('should insert into even tree', () => {
const tree = new MerkleTree(10, [1, 2])
tree.insert(42)
return tree.root().should.equal('6204016789747878948181936326719724987136198810274146408545977300318734508764')
})
})
describe('#update', () => {
it('should update first element', () => {
const tree = new MerkleTree(10, [1, 2, 3, 4, 5])
tree.update(0, 42)
return tree.root().should.equal('153077538697962715163231177553585573790587443799974092612333826693999310199')
})
it('should update last element', () => {
const tree = new MerkleTree(10, [1, 2, 3, 4, 5])
tree.update(4, 42)
return tree.root().should.equal('1955192134603843666100093417117434845771298375724087600313714421260719033775')
})
it('should update odd element', () => {
const tree = new MerkleTree(10, [1, 2, 3, 4, 5])
tree.update(1, 42)
return tree.root().should.equal('6642888742811380760154112624880866754768235565211186414088321870395007150538')
})
it('should update even element', () => {
const tree = new MerkleTree(10, [1, 2, 3, 4, 5])
tree.update(2, 42)
return tree.root().should.equal('11739358667442647096377238675718917508981868161724701476635082606510350785683')
})
})
describe('#indexOf', () => {
it('should find index', () => {
const tree = new MerkleTree(10, [1, 2, 3, 4, 5])
tree.indexOf(3).should.equal(2)
})
it('should return -1 for non existent element', () => {
const tree = new MerkleTree(10, [1, 2, 3, 4, 5])
tree.indexOf(42).should.equal(-1)
})
})
describe('#proof', () => {
it('should work for even index', () => {
const tree = new MerkleTree(10, [1, 2, 3, 4, 5])
const proof = tree.proof(2)
proof.pathIndex.should.be.deep.equal([0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
proof.pathElements.should.be.deep.equal([
4,
'19814528709687996974327303300007262407299502847885145507292406548098437687919',
'21305827034995891902714687670641862055126514524916463201449278400604999416145',
'14506027710748750947258687001455876266559341618222612722926156490737302846427',
'4766583705360062980279572762279781527342845808161105063909171241304075622345',
'16640205414190175414380077665118269450294358858897019640557533278896634808665',
'13024477302430254842915163302704885770955784224100349847438808884122720088412',
'11345696205391376769769683860277269518617256738724086786512014734609753488820',
'17235543131546745471991808272245772046758360534180976603221801364506032471936',
'155962837046691114236524362966874066300454611955781275944230309195800494087',
])
})
it('should work for odd index', () => {
const tree = new MerkleTree(10, [1, 2, 3, 4, 5])
const proof = tree.proof(3)
proof.pathIndex.should.be.deep.equal([1, 1, 0, 0, 0, 0, 0, 0, 0, 0])
proof.pathElements.should.be.deep.equal([
3,
'19814528709687996974327303300007262407299502847885145507292406548098437687919',
'21305827034995891902714687670641862055126514524916463201449278400604999416145',
'14506027710748750947258687001455876266559341618222612722926156490737302846427',
'4766583705360062980279572762279781527342845808161105063909171241304075622345',
'16640205414190175414380077665118269450294358858897019640557533278896634808665',
'13024477302430254842915163302704885770955784224100349847438808884122720088412',
'11345696205391376769769683860277269518617256738724086786512014734609753488820',
'17235543131546745471991808272245772046758360534180976603221801364506032471936',
'155962837046691114236524362966874066300454611955781275944230309195800494087',
])
})
})
})