merkle-tree-solidity
JS - Solidity sha3 merkle tree bridge. Generate proofs in JS; verify in Solidity.
Install
npm install --save merkle-tree-solidity
Credit
This is partly a port of Raiden's merkle tree python module and the solidity code is a close copy.
Merkle Tree https://github.com/raiden-network/raiden/blob/master/raiden/mtree.py
Usage
// create merkle tree// expects unique 32 byte buffers as inputs (no hex strings)// if using web3.sha3, convert first -> Buffer(web3.sha3('a'), 'hex')const elements = 1 2 3const merkleTree = elements // get the merkle root// returns 32 byte bufferconst root = merkleTree // for convenience if only the root is desired// this creates a new MerkleTree under the hoodconst easyRoot = // generate merkle proof// returns array of 32 byte buffersconst proof = merkleTree // check merkle proof in JS// returns bool // create the contract abstractionconst merkleProof = await // then use the contract directly// but the contract requires hex prefixed strings, not buffersmerkleProof // -> throws // or create a helper function from the abstraction// this function converts the buffers to hex prefixed stringsconst checkProofSolidity = // check merkle proof in Solidity// we can now safely pass in the buffers returned by previous methodsawait // -> true
Ordered Merkle Trees
By default, generating the tree doesn't preserve leaf order, but we can optionally do so.
// create merkle tree// expects 32 byte buffers as inputs (no hex strings)// if using web3.sha3, convert first -> Buffer(web3.sha3('a'), 'hex')const elements = 1 2 3 // include the 'true' flag when generating the merkle treeconst merkleTree = elements true // [same as above]// get the merkle root// returns 32 byte bufferconst root = merkleTree // for convenience if only the root is desired// this creates a new MerkleTree under the hood// 2nd arg is "preserveOrder" flagconst easyRoot = // generate merkle proof// 2nd argugment is the 1-n index of the element// returns array of 32 byte buffersconst index = 1const proof = merkleTree // this is useful if you have duplicates in your treeconst elements2 = 3 2 3const index2 = 3const proof2 = merkleTree // check merkle proof of ordered tree in JS// expects 1-n indexed element position as last param// returns boolconst index = 1 // create the contract abstractionconst merkleProof = await // then use the contract directly// but the contract requires hex prefixed strings, not buffersmerkleProof // -> throws // or create a helper function from the abstraction// this function converts the buffers to hex prefixed stringsconst checkProofOrderedSolidity = // check merkle proof in Solidity// we can now safely pass in the buffers returned by previous methodsawait // -> true
Licence
This project is licensed under the MIT license, Copyright (c) 2016 Ameen Soleimani