Public
Edited
May 15, 2021
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
transactions = [{to: '0xme', from: '0xyou', value: 10}, {to: '0xyou', from: '0xme', value: 5}, {to: '0xalice', from: '0xbob', value: 5}, {to: '0xbob', from: '0xme', value: 15}, {to: '0xjon', from: '0xme', value: 15}, {to: '0xbob', from: '0xsally', value: 1}, {to: '0xjan', from: '0xsally', value: 105}]
Insert cell
Insert cell
Insert cell
leaves = transactions.map(x => sha256(JSON.stringify(x)))
Insert cell
Insert cell
// For demonstration purposes only!!

function createMerkleTree(nodes){
// if the nodes.length is greater than 1, we have not yet found the root, so loop through the the leaves and compute the hashes
if (nodes.length > 1) {
let newNodes = []
let leafNodes = []

// if leaf nodes, format them
if(typeof nodes[0] =='string'){
nodes.forEach((value, index, array) => {
leafNodes.push({hash: value})
})
nodes = leafNodes
}
// if odd number of nodes, duplicate the last one
// reference: https://ethereum.stackexchange.com/questions/29286/can-a-mined-block-have-an-odd-number-of-transactions-if-so-how-does-the-merkle
if(nodes.length % 2 == 1){
nodes.push(nodes[nodes.length - 1])
}
// iterate over the nodes, hashing pairs into a single node 1 level up
nodes.forEach((value, index, array) => {
if(index % 2 == 0){
newNodes.push({hash: sha256(value.hash + array[index + 1].hash), children: [value, array[index+1]]})
}
})
return createMerkleTree(newNodes)
} else {
// if the nodes.length === 1, it's the root, so let's return it
return nodes[0]
}
}
Insert cell
Insert cell
simpleMerkleTree = createMerkleTree(leaves, 0)
Insert cell
Insert cell
Insert cell
function verify(transaction, orderedHashes){
// get the txHash
let txHash = sha256(JSON.stringify(transaction))
let hash = txHash
for(var i = 0; i < orderedHashes.length; i++){
hash = sha256(hash + orderedHashes[i])
}
return (hash === simpleMerkleTree.hash)
}
Insert cell
Insert cell
verify({ to: "0xme", from: "0xyou", value: 10 }, [
"4b747a7bff5efc9779aeb5c48a25f17c70c9248672296f31c6478315422c6d45",
"181008b794801718f90d20b75debe23c93090db9f4eb32bc3b049112f1e9724b",
"f98b6d71345b950b83d392528b2240c68c0d4454ef9840c208a818e0e7d27df9"
])
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more