Skip to content

Instantly share code, notes, and snippets.

@tristanwagner
Forked from riccjohn/SimpleBlockchain.js
Created September 23, 2018 00:28
Show Gist options
  • Save tristanwagner/6db58de3d1b599e1e8c57e9f7de0a77e to your computer and use it in GitHub Desktop.
Save tristanwagner/6db58de3d1b599e1e8c57e9f7de0a77e to your computer and use it in GitHub Desktop.
const sha256 = require('sha256');
class Block {
constructor(index, timestamp, data, prevHash) {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.prevHash = prevHash;
this.thisHash = sha256(
this.index + this.timestamp + this.data + this.prevHash
);
}
}
const createGenesisBlock = () => new Block(0, Date.now(), 'Genesis Block', '0');
const nextBlock = (lastBlock, data) =>
new Block(lastBlock.index + 1, Date.now(), data, lastBlock.thisHash);
const createBlockchain = num => {
const blockchain = [createGenesisBlock()];
let previousBlock = blockchain[0];
for (let i = 1; i < num; i += 1) {
const blockToAdd = nextBlock(previousBlock, `This is block #${i}`);
blockchain.push(blockToAdd);
previousBlock = blockToAdd;
}
console.log(blockchain);
};
const lengthToCreate = 20;
createBlockchain(lengthToCreate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment