Created
November 3, 2017 23:15
-
-
Save fletcherist/641244b37bfe4053a69c9eed1ed1b10b to your computer and use it in GitHub Desktop.
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
// 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment