Created
June 7, 2023 03:23
-
-
Save gentlyawesome/30b50aa975a53b07251b6abe36c46779 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 crypto = require('crypto'); | |
// Transactions | |
const transactions = ['T1', 'T2', 'T3', 'T4', 'T5']; | |
// Merkle Root Calculation | |
function calculateMerkleRoot(transactions) { | |
if (transactions.length === 0) { | |
return null; | |
} | |
if (transactions.length === 1) { | |
return transactions[0]; | |
} | |
const pairedTransactions = []; | |
if (transactions.length % 2 !== 0) { | |
transactions.push(transactions[transactions.length - 1]); | |
} | |
for (let i = 0; i < transactions.length; i += 2) { | |
const pair = transactions[i] + transactions[i + 1]; | |
const hash = crypto.createHash('sha256').update(pair).digest('hex'); | |
pairedTransactions.push(hash); | |
} | |
return calculateMerkleRoot(pairedTransactions); | |
} | |
// Calculate Merkle Root | |
const merkleRoot = calculateMerkleRoot(transactions); | |
console.log('Merkle Root:', merkleRoot); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment