Riccardo Canella
28 Feb 2018
•
7 min read
Find the original article from @ricanella92 here and if you’re passionate about Front End development, check out the JavaScript Works job-board here.
Disclaimer: chiccocoin is not a true cryptocurrency and we do not sell it , this article is for recreational / educational purposes only
Every day on our feeds we find news about new cryptocurrency or someone who says that they are a big bubble that will soon explode and of which only the blockchain will remain. But, what is the blockchain?
By definition:
So, the blockchain is an immutable, sequential chain of records called Blocks. Each block can contain transactions, files or any data you like. The important thing is that they’re chained together using hashes.
Blockchains are secure by design and are an example of a distributed computing system with high Byzantine fault tolerance. This makes blockchains potentially suitable for the recording of events, medical records, and other records management activities, such as identity management, transaction processing or voting.
Understanding Blockchains reading article or tutorials isn’t easy. Wandering among the many online guides I found this article by Daniel van Flymen and my curiosity to understand how it really worked has grown so much to try to create a blockchain using NodeJS.
The first step to creating a new project is to create the logo. It makes everything real. To do this I used Squarespace logo creator and this is the result:
Now we can really start with our project.
To facilitate the creation of the APIs to interact with the blockchain I started the project directly with ExpressJS using the package npm express-generator
npm install -g express-generator
express ./chiccocoin
cd chiccocoin
yarn
You can find all the code online on this repo.
Now we’re going to create our blockchain. Rereading the definition of blockchain we can summarize that the absolutely necessary functions are:
So we can create our blockchain.js file with this structure:
class Blockchain {
constructor () {
// Create chain and transaction
this.chain = []
this.current_transactions = []
// Binding of this
this.newBlock = this.newBlock.bind(this)
this.newTransaction = this.newTransaction.bind(this)
this.lastBlock = this.lastBlock.bind(this)
this.proofOfWork = this.proofOfWork.bind(this)
}
newBlock () { /* Create the new block */ }
newTransaction () { /* Store a new transaction */ }
hash (block) { /* hash the block */ }
lastBlock () { /* return the last block */}
}
module.exports = Blockchain
The constructor of our class will create two important variables, chain, and current__transaction. Chain will contain, in order, all our block. Current_transactions will contain all the transaction that will be added to a block at the next mining
But what is a block? The representation that will use of a block is a javascript object that will contain:
*- Index
const block = {
'index': 1,
'timestamp': 1506057125.900785,
'transactions': [
{
'sender': "8527147fe1f5426f9dd545de4b27ee00",
'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
'amount': 5,
}
],
'proof': 324984774000,
'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}
In this way the idea of blockchain becomes already a little clearer. Is a set of sequential blocks (index) linked to the previous one and secured using cryptography (previous__hash). The previous_hash inside the block it’s the crux of the whole blockchain. It allows us to guarantee the safety and immutability of the whole chain. If an attacker could modify a block of a chain all the hashes immediately after that block would be wrong. Obviously it could try to recalculate the hashes of the whole chain and that’s why more blocks there are more the blockchain is safe. Moreover there is an (identical) copy of the blockchain in every node (instance of NodeJS in this case) this makes it almost impossible for a hacker to be able to modify all the copies at the same time.
So create a new block is very simple in our case. We just need to push a new object to the chain. The function will receive the proof (then we’ll talk about what it is) and the previous block hash and will return the block. The function also will add to the block all the transactions that have not yet been saved and clean up our variable current_transactions
The hash function that uses for our Chiccocoin is a trivial SHA256 but you can use the hash function that you prefer. The important thing is to do the hash of the previous block, to do this we will do the hash of the serialized object
The function to add a new transaction is very trivial. Is to add to the current_transaction array the transaction. A transaction is an object formed of sender, recipient and amount. It will be the mining function of storing transactions within a block. For utility we will make sure that the function returns to us the index of the block on which it will be saved
class Blockchain {
constructor () {
// Create chain and transaction
this.chain = []
this.current_transactions = []
// Binding of this
this.newBlock = this.newBlock.bind(this)
this.newTransaction = this.newTransaction.bind(this)
this.lastBlock = this.lastBlock.bind(this)
this.proofOfWork = this.proofOfWork.bind(this)
}
newBlock (proof, previousHash) {
const block = {
index: this.chain.length + 1,
timestamp: new Date(),
transactions: this.current_transactions,
proof: proof,
previous_hash: previousHash
}
this.current_transactions = []
this.chain.push(block)
return block
}
newTransaction (sender, recipient, amount) {
this.current_transactions.push({
sender: sender,
recipient: recipient,
amount: amount
})
return this.lastBlock()['index'] + 1
}
hash (block) {
const blockString = JSON.stringify(block)
const hash = crypto.createHmac(process.env.HASH_TYPE, process.env.CRYPTO_SECRET)
.update(blockString)
.digest('hex')
return hash
}
lastBlock () {
return this.chain.slice(-1)[0]
}
}
module.exports = Blockchain
In general, the proof of work is a function or a protocol invented and used to deter denial of service attacks, but the blockchain used it to determinate how new Blocks are created or mined on themselves. The goal of a POW is to discover a number which solves a problem. This number must be difficult to find but easy to verify, like the calculation of prime numbers, more we go on the more difficult it will be to find one, but the effort to understand if it is or not will always be very banal.
To mining a Chiccocoin we decide the create a c4ff3. Our POW will be this:
Find a number p that when hashed with the previous block’s solution a hash which starts with c4ff3 is produced.
An example:
c4ff3e9373e...5e3600155e860
Let’s code it. The functions that will be necessary are two:
- validProof: given the previous POW and a p number checks if the solution to the problem is correct
- proofOfWork: cycle until a solution is found
validProof (lastProof, proof) {
const guessHash = crypto.createHmac(process.env.HASH_TYPE, process.env.CRYPTO_SECRET)
.update(`${lastProof}${proof}`)
.digest('hex')
return guessHash.substr(0, 5) === process.env.RESOLUTION_HASH
}
proofOfWork (lastProof) {
let proof = 0
while (true) {
if (!this.validProof(lastProof, proof)) {
proof++
} else {
break
}
}
return proof
}
Having started the project with expressjs serving our blockchain via API will be very simple.
We’ll create three API:
/transactions/new
to create a new transaction to a block/mine
to tell our server to mine a new block./chain
to return the full Blockchain.I created a Chiccocoin support class, inside /middleware/chiccocoin.js
, which contains all the necessary middleware for our APIs and instantiates a new blockchain
This endpoint will be very very simple. Just will return the chain array stored inside the blockchain
The transaction endpoint will check the data passed and will call the newTransaction function of the blockchain. In the future we could use this middleware to check if actually sender and recipient are correct and/or the transaction can be done. We will use the information returned by the newTransaction function to inform the user on which block the transaction will be saved.
Our mining endpoint is where the chiccocoin becomes reality. It has to do four things:
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()
We can test all our API’s via curl or via Postman. I added the postman_collection.json inside the repository in order to simplify you the use of postman.
The idea behind the blockchain is nothing new or complicated as we have seen. Banally developers use a blockchain every day without realizing it (git). It is a very old concept that, however, brought back to life under a new point of view is changing the way of thinking about the economy, creating bubbles (in my opinion) and new possibilities for a “safer” economy from the point of view of common knowledge. Having the ability to control when and how a transaction took place is something that is going quietly but has enormous potential.
What we have created is a simple blockchain that works with only one node and on which only one can make it (there are cryptocurrencies based on this). Surely the management of the multi-node and of all the problems around this topic are equally interesting. Maybe we’ll do a second article about this, but put a star in the repository for more updates.
I hope this article has pushed you to look beyond what is bitcoin trading and to have you intrigued over what you can really do with the blockchain.
Thanks and stay tuned :)
Ground Floor, Verse Building, 18 Brunswick Place, London, N1 6DZ
108 E 16th Street, New York, NY 10003
Join over 111,000 others and get access to exclusive content, job opportunities and more!