Created
June 16, 2023 03:01
-
-
Save gentlyawesome/aeb2be044116b2caacd6d334461a5f5d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const CryptoJS = require('crypto-js'); | |
// Create an array of data items | |
const data = ['data1', 'data2', 'data3', 'data4']; | |
// Function to generate Merkle tree | |
function generateMerkleTree(data) { | |
if (data.length === 0) return []; | |
if (data.length === 1) { | |
return [CryptoJS.SHA256(data[0]).toString()]; | |
} | |
const newData = []; | |
for (let i = 0; i < data.length; i += 2) { | |
const left = CryptoJS.SHA256(data[i]).toString(); | |
const right = (i + 1 < data.length) ? CryptoJS.SHA256(data[i + 1]).toString() : left; | |
newData.push(CryptoJS.SHA256(left + right).toString()); | |
} | |
return generateMerkleTree(newData); | |
} | |
// Generate the Merkle tree | |
const merkleTree = generateMerkleTree(data); | |
// Function to generate Merkle proof for a specific data item | |
function generateMerkleProof(dataItem, merkleTree) { | |
const proof = []; | |
let index = data.indexOf(dataItem); | |
if (index === -1) { | |
throw new Error('Data item not found in the Merkle tree'); | |
} | |
for (let i = 0; i < merkleTree.length; i++) { | |
const isRightNode = index % 2 === 0; | |
const siblingIndex = isRightNode ? index + 1 : index - 1; | |
if (siblingIndex < merkleTree.length) { | |
proof.push({ | |
data: merkleTree[siblingIndex], | |
isLeftNode: !isRightNode | |
}); | |
} | |
index = Math.floor(index / 2); | |
} | |
return proof; | |
} | |
// Generate the Merkle proof for 'data2' | |
const proof = generateMerkleProof('data2', merkleTree); | |
// Print the proof | |
console.log(proof); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment