Created
January 24, 2018 10:36
-
-
Save thecreazy/81d3f6112cc64f6070a92ed3098755dd to your computer and use it in GitHub Desktop.
Gist used for the blockchain article on medium
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 characters
const Blockchain = require('./blockchain') | |
const { validationResult } = require('express-validator/check') | |
class Chiccocoin { | |
constructor () { | |
this.blockchain = new Blockchain() | |
this.getChain = this.getChain.bind(this) | |
this.mine = this.mine.bind(this) | |
this.newTransaction = this.newTransaction.bind(this) | |
} | |
getChain (req, res, next) { | |
req.responseValue = { | |
message: 'Get Chain', | |
chain: this.blockchain.chain | |
} | |
return next() | |
} | |
mine (req, res, next) { | |
const lastBlock = this.blockchain.lastBlock() | |
const lastProof = lastBlock.proof | |
const proof = this.blockchain.proofOfWork(lastProof) | |
// Create a new transaction with from 0 (this node) to our node (NODE_NAME) of 1 Chiccocoin | |
this.blockchain.newTransaction('0', process.env.NODE_NAME, 1) | |
// Forge the new Block by adding it to the chain | |
const previousHash = this.blockchain.hash(lastProof) | |
const newBlock = this.blockchain.newBlock(proof, previousHash) | |
const responseValue = Object.assign({ | |
message: 'New Block mined' | |
}, newBlock) | |
req.responseValue = responseValue | |
return next() | |
} | |
newTransaction (req, res, next) { | |
const errors = validationResult(req) | |
if (!errors.isEmpty()) { | |
return res.status(422).json({ errors: errors.mapped() }) | |
} | |
const trans = req.body | |
const index = this.blockchain.newTransaction(trans['sender'], trans['recipient'], trans['amount']) | |
const responseValue = { | |
message: `Transaction will be added to Block ${index}` | |
} | |
req.responseValue = responseValue | |
return next() | |
} | |
} | |
module.exports = new Chiccocoin() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment