const crypto = require('crypto'); const hashGenerator = (...inputs) => { const hash = crypto.createHash('sha256'); hash.update(inputs.map(item => JSON.stringify(item)).join('')); return hash.digest('hex'); } class Block { constructor(timestamp, lastHash, hash, data, nonce) { this.timestamp = timestamp; this.lastHash = lastHash; this.hash = hash; this.data = data; this.nonce = nonce; } static createGenesis() { return new this("17/01/2020", "dummy-last-hash", "dummy-hash", "data in genesis block", 0) } static createBlock(previousBlock, data) { let hash, timestamp, nonce=0; const lastHash = previousBlock.hash; do { timestamp = Date.now(); nonce++; hash = hashGenerator(timestamp, lastHash, data, nonce); } while (hash.substr(0,4) !== '0'.repeat(4)); return new this(timestamp, lastHash, hash, data, nonce); } } class Blockchain { constructor() { this.blocks = [Block.createGenesis()]; } addBlock(data) { const createdBlock = Block.createBlock(this.blocks[this.blocks.length - 1], data); this.blocks.push(createdBlock); } } const webbyChain = new Blockchain(); webbyChain.addBlock('This dummy data is saved in the second block of the webbyChain'); webbyChain.addBlock('This immutable data is saved in the third block'); webbyChain.addBlock('Adding top secret in the fourth block'); console.log(webbyChain.blocks);