Created
August 13, 2018 08:04
-
-
Save xpepermint/4176834f492ae230f52a95dacba9eb05 to your computer and use it in GitHub Desktop.
Merkle tree implementation
This file contains 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
/** | |
* Converts a list of values into a list of pairs. | |
* @param arr Single dimensional array of values. | |
*/ | |
function toPairs(arr) { | |
return Array.from(Array(Math.ceil(arr.length / 2)), (_, i) => arr.slice(i * 2, i * 2 + 2)); | |
} | |
/** | |
* Converts a list of values into a list of pairs. | |
* @param arr Single dimensional array of values. | |
*/ | |
function hashValue(value): string { | |
return createHash('sha256').update(value).digest('hex'); | |
} | |
/** | |
* Converts a list of values into a list of pairs. | |
* @param arr Single dimensional array of values. | |
*/ | |
function hashList(arr): string[] { | |
return arr.map((v) => hashValue(v)); | |
} | |
/** | |
* Hash pair values. | |
* @param a Pair value. | |
* @param b Pair value. | |
*/ | |
function hashPair(a?, b?) { | |
return b ? hashValue(`${a}${b}`) : a; | |
} | |
/** | |
* Calculates merkle root hash. | |
* @param arr Array of pairs. | |
*/ | |
function toMerkle(arr) { | |
return arr.length === 1 ? arr[0] : toMerkle(toPairs(arr).reduce((tree, pair) => [...tree, hashPair(...pair)], [])); | |
} | |
/** | |
* Run implementation. | |
*/ | |
const values = ['foo', 'bar', 'baz']; | |
const root = toMerkle(hashList(values)); | |
console.log(root); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment