Skip to content

Instantly share code, notes, and snippets.

@gentlyawesome
Created June 9, 2023 03:07
Show Gist options
  • Save gentlyawesome/d5457aeac55bf11aa5f1af83ac28f69a to your computer and use it in GitHub Desktop.
Save gentlyawesome/d5457aeac55bf11aa5f1af83ac28f69a to your computer and use it in GitHub Desktop.
const crypto = require('crypto');
function calculateMerkleRoot(transactions) {
if (transactions.length === 0) {
return null;
}
// Create a copy of the transactions array
let hashes = [...transactions];
// Construct the Merkle tree
while (hashes.length > 1) {
const levelHashes = [];
// Pair adjacent hashes and compute their parent hash
for (let i = 0; i < hashes.length; i += 2) {
const left = hashes[i];
const right = i + 1 < hashes.length ? hashes[i + 1] : left; // Duplicate last hash if odd number of hashes
const parentHash = crypto.createHash('sha256').update(left + right).digest('hex');
levelHashes.push(parentHash);
}
hashes = levelHashes;
}
return hashes[0];
}
function validateMerkleRoot(transactions, merkleRoot) {
const calculatedRoot = calculateMerkleRoot(transactions);
return calculatedRoot === merkleRoot;
}
// Example usage
const transactions = ['TransactionA', 'TransactionB', 'TransactionC', 'TransactionD'];
const merkleRoot = '1b07e75f11e1e54f5d71f1696bca801485d5e7d61a3e55bb62081f2cc0e465a1';
// Validate the Merkle root
const isValid = validateMerkleRoot(transactions, merkleRoot);
console.log(`Merkle root validation: ${isValid}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment