Skip to content

Instantly share code, notes, and snippets.

@fletcherist
Created November 3, 2017 23:15
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 fletcherist/641244b37bfe4053a69c9eed1ed1b10b to your computer and use it in GitHub Desktop.
Save fletcherist/641244b37bfe4053a69c9eed1ed1b10b to your computer and use it in GitHub Desktop.
// 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