Skip to content

Instantly share code, notes, and snippets.

@fletcherist
Created November 3, 2017 23:15
Show Gist options
  • Save fletcherist/641244b37bfe4053a69c9eed1ed1b10b to your computer and use it in GitHub Desktop.
Save fletcherist/641244b37bfe4053a69c9eed1ed1b10b to your computer and use it in GitHub Desktop.

Revisions

  1. fletcherist renamed this gist Nov 3, 2017. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. fletcherist created this gist Nov 3, 2017.
    67 changes: 67 additions & 0 deletions gistfile1.txt
    Original 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)