Skip to content

Instantly share code, notes, and snippets.

@petscheit
Created December 2, 2020 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petscheit/ecc63b5b25cf0dc2143b1b5cee33f77a to your computer and use it in GitHub Desktop.
Save petscheit/ecc63b5b25cf0dc2143b1b5cee33f77a to your computer and use it in GitHub Desktop.
const { MerkleTree } = require('merkletreejs')
const SHA256 = require('crypto-js/sha256')
let users = initializeUsers(256);
function addAddress(index, address) {
users[index] = address;
}
function verifyProof(sorted, hex){
const leaves = users.map(x => SHA256(x))
let tree;
if(sorted){
tree = new MerkleTree(leaves, SHA256, {sortPairs: true})
} else {
tree = new MerkleTree(leaves, SHA256)
}
const root = tree.getRoot().toString('hex')
const leaf = SHA256('hahaha')
let proof;
if(hex){
proof = tree.getHexProof(leaf)
} else {
proof = tree.getProof(leaf)
}
console.log("Verified: ", tree.verify(proof, leaf, root))
}
function initializeUsers(length){
let users = new Array(length)
for(var i = 0; i < users.length; i++) users[i] = "0x0";
return users;
}
addAddress(0, "hahaha")
console.log("Not sorted, not hex => works")
verifyProof(false, false)
console.log()
console.log("Sorted, Hex => works")
verifyProof(true, true)
console.log()
console.log("Sorted, not hex => Works")
verifyProof(true, false)
console.log()
console.log("Not sorted, Hex => Doesn't work")
verifyProof(false, true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment