Last active
September 1, 2018 12:45
-
-
Save eduardonunesp/f82b97ab41a1435cc736f8f29215c8e2 to your computer and use it in GitHub Desktop.
Fibonacci List + Merkle Tree
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
const crypto = require('crypto'); | |
// Generate the SHA256 from an input | |
const SHA256 = (input) => ( | |
crypto | |
.createHash('sha256') | |
.update(input) | |
.digest() | |
.toString('hex') | |
); | |
// Double hash for each input in the merkle tree | |
const SHA256x2 = (val, hashFunc = SHA256) => ( | |
hashFunc(hashFunc(val)) | |
); | |
// Generate the merkle tree according to bitcoin protocol | |
const merklelize = (list) => { | |
if (list.length === 1) { | |
return SHA256x2(list[0]) | |
} | |
let hashedConcatList = []; | |
for (let i = 0; i < list.length; i += 2) { | |
let a = list[i]; | |
let b; | |
if (i + 1 >= list.length) | |
b = list[i]; | |
else | |
b = list[i + 1]; | |
let concat = SHA256x2(`${a}`) + SHA256x2(`${b}`); | |
hashedConcatList.push(concat); | |
} | |
return merklelize(hashedConcatList); | |
}; | |
// Just a fibonacci array | |
const fibonacciList = (size) => { | |
const fib = [0, 1]; | |
for (let i = fib.length; fib.length < size; i++) | |
fib.push(fib[i - 1] + fib[i - 2]); | |
return fib; | |
} | |
// Generate a fibonacci array with 50 positions | |
const fibList = fibonacciList(50); | |
// Return the root of the merkle tree | |
console.log(merklelize(fibList).toString()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment