Make your first Blockchain!

Juhi Tiwari
tech@iiit-gwalior
Published in
5 min readApr 21, 2020

This tutorial is in continuation with a previous blog here where you can get an idea of what Blockchains are. We now move on to make our very own simple blockchain using Python. We would be demonstrating it by making a web app on Flask. But before we move on to the code let’s get some basics covered! The whole code would be divided into two steps :

1. Create a Blockchain : We would be making blocks that can be added in our chain. Every block would be having its on index number, a timestamp telling us the time at which it is created, the hash of the previous block of the chain and a nonce or the proof of work. To know what a nonce is we shall first understand our second part of the code.

2. Mining a Blockchain : This is the part where we will be mining, creating our web app and display our blockchain. Now what is mining? Apart from your usual fields in a blockchain like data, hash, index etc. We have an extra field as well known as nonce aka “number used only once”.

The nonce is under our control meaning the other fields cannot be changed by us, but we can change the value of nonce. All these fields together can computer the hash for the block. Since we can change the value of the nonce, we can change the hash of the block.

Now, after a certain fixed time, a minimum value for the hashes is set. Only the hashes below this target value are considered valid. A very important thing in this is the number of leading zeroes in the hash value. With every leading zero the hash value decreases.

And that’s where we are presented with a super geeky puzzle: find a nonce that can generate a valid hash and then only your block will be added into the chain. This is mining and if you are in the race of solving this problem you are a miner. The more miners, the lower target hash, the more difficulty. In Bitcoin, the difficulty is as such that only one new block is added in 10 minutes.

Image result for blockchain target hash

So let’s get our hands dirty now!

We need to import flask (for our web app), hashlib (to generate our sha256 hash), json(to send our response in JSON format and datetime( to get the current time).

from flask import Flask,jsonify
import json
import datetime
import hashlib

We will be now building our blockchain and for that we would be creating its class. This will help us in making as many instances of a blockchain as we want.

Our blockchain will be initialized with our Genesis Block whose previous hash will be zero as there are no blocks before that. Also we can initialize our nonce for this block with any number, we choose 1. We also make an empty chain.

We will be creating a function create_block which will be responsible for making a new block in our chain.

class blockchain:
#creating an empty chain at the first instance
#making our genesis block
def __init__(self):
self.chain=[]
self.create_block(nonce=1,previous_hash='0')
#our block will be in the form of a dictionary with an index number, timestamp, nonce(which we will be getting on solving our cryptography puzzle and the hash of the previous block (which we will be providing)
#we also append this block in our chain and return our block
def create_block(self,nonce,previous_hash):
block={'index':len(self.chain)+1,
'timestamp':str(datetime.datetime.now()),
'nonce’:nonce,
'previous_hash':previous_hash}
self.chain.append(block)
return block

We now make a function that can generate a hash for our block

def hash(self,block):
encoded_block=json.dumps(block,sort_keys=True).encode()
return hashlib.sha256(encoded_block).hexdigest()

To provide the nonce for our block in our create_block function, we now make another function nonce that checks if our hash value is below our targeted value, if it is so it will return this nonce to us.

In this function, we solve our puzzle by calculating the difference between squares of the nonce of the previous block and our new nonce. We then check if the hash for this has 4 leading zeroes (we have defined that the target hash has 4 leading zeroes, any hash greater than this is invalid), if yes we return that nonce (yaay you solved the puzzle!). You can come up with any other expression, the only trick is that it shouldn’t be symmetrical.

def nonce(self,prev_nonce):
new_nonce=1
check_nonce=False
while check_nonce is False:
hash_operation=hashlib.sha256(str(new_nonce**2-prev_nonce**2).encode()).hexdigest()
if hash_operation[:4]=='0000':
check_nonce=True
else:
new_nonce+=1
return new_ nonce

We can also write a quick function for getting the previous block:

def get_prev_block(self):
return self.chain[-1]

Create a web app

app=Flask(__name__)

Make your blockchain

blockchain=blockchain()

At this instance we have our genesis block and an empty chain

Now let’s mine our first block:

@app.route('/mine_block',methods=['GET'])
def mine_block():
prev_block=blockchain.get_prev_block()
prev_nonce=prev_block['nonce']
nonce=blockchain.nonce(prev_nonce)
prev_hash=blockchain.hash(prev_block)
block=blockchain.create_block(nonce,prev_hash)
response={'message':'mission accomplished',
'index':block['index'],
'timestamp':block['timestamp'],
'nonce':block['nonce'],
'prev_hash':block['previous_hash']}
return jsonify(response),200

Using our get_prev_block() function, we get the last block i.e. right now our previous block is genesis block. Thus, prev_nonce contains a value of 1. And with this value we can now easily solve our puzzle using our nonce function and get a nonce value for our block that will make our hash valid. We can also calculate the hash of our genesis block. With these two values we are ready to create our block. We can store our response in the form of a dictionary and then return this in JSON format.

@app.route('/get_chain',methods=['GET'])
def get_chain():
response={'chain':blockchain.chain,
'length':len(blockchain.chain)}
return jsonify(response),200

This will simply return our complete blockchain and will also show us the length of our blockchain.

Finally run your app and let the magic begin!

app.run(host='0.0.0.0',port=5000)

You can quickly visualise your blockchain on Postman celebrate your first blockchain!

This is a very basic blockchain and in the coming posts we would be playing with them and making our own cryptocurrencies. Any suggestions or doubts are welcomed. Until then happy blockchaining!

--

--