Created
November 3, 2017 23:15
-
-
Save fletcherist/641244b37bfe4053a69c9eed1ed1b10b to your computer and use it in GitHub Desktop.
Revisions
-
fletcherist renamed this gist
Nov 3, 2017 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
fletcherist created this gist
Nov 3, 2017 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,67 @@ // This is blockchain implementaion // Be careful — it doesn't work as expected actually :) const CryptoJS = require('crypto-js') class Block { constructor(index, timestamp, data, previousHash = '0') { this.index = index this.previousHash = previousHash this.timestamp = timestamp this.data = data this.hash = this.calculateHash() } calculateHash() { return CryptoJS.SHA256([ this.index, this.previousHash, this.timestamp, this.data ].map(element => JSON.stringify(element)).join('') ).toString() } } class Blockchain { constructor() { this.chain = [this.createGenesisBlock()] } createGenesisBlock() { return new Block(0, Date.now(), 'genesis block') } getLatestBlock() { return this.chain[this.chain.length - 1] } addBlock(newBlock) { newBlock.previousHash = this.getLatestBlock().hash console.log('just added', newBlock) this.chain.push(newBlock) } isValidChain() { for (let i = 1; i < this.chain.length; i++) { const currentBlock = this.chain[i] const previousBlock = this.chain[i - 1] if (currentBlock.hash !== currentBlock.calculateHash()) { console.log(currentBlock) console.log(currentBlock.calculateHash()) return false } if (currentBlock.previousHash !== previousBlock.hash) { return false } } return true } } const blockchain = new Blockchain() blockchain.addBlock(new Block(1, Date.now(), { amount: 4 })) console.log(blockchain.isValidChain()) // WTF? why false damn it? console.log(blockchain)