Skip to content

Instantly share code, notes, and snippets.

@eduardonunesp
Last active September 1, 2018 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eduardonunesp/f82b97ab41a1435cc736f8f29215c8e2 to your computer and use it in GitHub Desktop.
Save eduardonunesp/f82b97ab41a1435cc736f8f29215c8e2 to your computer and use it in GitHub Desktop.
Fibonacci List + Merkle Tree
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