Learn Blockchain by Building One using Python

Prachi Gopalani
Analytics Vidhya
Published in
5 min readMar 2, 2021

--

Bitcoin

Before getting into building the blockchain, you need to understand some of the basics of blockchain.

As the name suggests, A Blockchain is a “chain of Blocks”. Each block contains a “Block Number”, “Nonce”, “Information (data)” where particular transaction takes place, “Previous Hash” and, “hash”.

All the Blocks in the Blockchain are linked to each other with the “hash” variable. A “hash” contains information of the previous block in the chain and that’s what keeps the entire chain-linked and connected. This hash is nothing but some keys which are some shuffled characters made from cryptographic algorithms (such as: SHA256, SHA512, SHA6 etc.)

Let’s take SH256 Alogorithm: contains 64 Characters (1, 2….9,0 &A, B, C, …. E, F) and 256 bits (4X64) each character.

Let’s get started

Explained step-by-step

(Here’s the code if you’d like to follow along)

Install Library

Make sure you have the most recent version of Python (Spider) installed. And for doing the requests, I used Postman. Also, you need to install two Python libraries called Flask and Requests, Library Needed:

Part 1: Building a Blockchain

Initializing variables for Block:

Creating a Python file named blockchain.py. Here firstly, we should create a Blockchain class and initialize the following variables:

Creating a constructor _init_(self) with self is instance of the Blockchain class

chain: an empty list in which blocks are added to.

create_block: In this method we have initialized previous hash with 0, and from here the blocks are made.

Creating Blockchain

Now that we have an empty chain, let’s add blocks to it! we’ll add a block variable describing a JSON object with these properties:

index: Taking the length of our blockchain and increment to it to 1. We’ll use this to reference an individual block, so for example the genesis block has index = 1

timestamp: using our time() import, Timestamp means time which is the time in their time clock on computer at that moment.

proof: this comes from our miner who thinks they found a valid “nonce”, or “proof”. We’ll talk about this some more in a bit.

previous_hash: a hashed version of the most recent approved block.

Now, we are going to add all this information regarding block to the list of blocks(self.chain) and return new block.

Working on previous Block

So far, all good! Let’s first define a get_previous_block() method, so that we can call our chain and receive the block that was added most recently (we’ll use this in a second for our new index).

Proof of Work

Now our simple blockchain is created, it’s now time to protect our genesis block. We don’t want anyone to alter our blockchain by providing new hash information to do so, we need to implement a proof of work algorithm. A proof of work algorithm simply makes sure that no one can change the hash. The algorithm will add some constraints to the hashes generated on the blockchain, making it impossible for anyone to make any change.

To do so, we add a nonce to our block field. This will ensure that our hash maintains the constraint.

The “proof of work” uses SHA-256 algorithm but a condition is placed instead of taking an input and giving a single output, for example the output hash needs to have the first four characters as zeros.

Here a function named Hasib is used and in it the .encode() and .hexdigest() are used to get hexadecimal output in the correct format. The math part in between is some simple math to generate a hash.

So basically, the “proof” will be incremented by 1 until the condition we have placed (first four zeros) is satisfied. Once the condition is satisfied, the proof variable will be added to the Block and then the Block will be added to the Blockchain.

Below is the code for the “proof of work” function

Check Validity of Block

The below snippet is to verify the integrity of the block. We take the block one at a time and check it with the previous hash value if it is true else someone has messed up with blockchain data at some point and hence we roll back. Or in case if any hash fails to match the condition that is the first four digits being zero. We return false.

Done with making of blockchain, now its time for mining the block and implementing in Flask API as I have used Postman over here to watch the mined blocks.

Part 2: Executing Code in Postman

Creating a Flask API

Calling the inbuilt function Flask in python and storing in app, also calling the main function build in previous steps Blockchain() and assigning to blockchain variable. Now the next will be to mine the block using app.route method.

Mining a Block

@app.route (‘/’,methods=[]) this is a flask beauty where you can name the URL and the method. The function below will be executed. @app.route() are called decorators in flask. We instantiate a Flask object and a blockchain object called blockchain. Step 1 create the block or in technical terms mine a new block. Which contains the following responses:

Message: message of mined block

Index: Block Number

Timestamp: Time when block was mined

Proof: which is the encrypted hash key

Previous_hash: Last encrypted hash key

Ans all this will get directed to JSON Flask API (as here we will be using postman for demonstration).

Now the question arises is how do we see the chain?

Getting full Blockchain

Well that is what the get_chain decorator is for. It returns the whole blockchain. You might have been seeing the jsonify function what it does it converts the python dictionary into a json object which can be sent across API’s. Here, in response chain and length which is already defined=200 means until 200 blocks can be mined.

The next function is_valid() is for displaying message in Flask API

Run Code

Once you run the code, Open postman and login and you will see a screen which looks like a URL bar. Go down there and choose method GET (which is actually by default) and type in http://0.0.0.0:5000/get_chain and you should see the genesis block of YOUR blockchain. Let’s mine more nodes http://0.0.0.0:5000/mine_block and you will be able to see more nodes. Make a few more nodes and once done with it you can check the http://0.0.0.0:5000/get_chain and see how YOUR blockchain is growing!

You can play around and add more fields in the block, maybe more data sections etc. I hope you get the use of Postman it is software to actually test our API’s.

Part 3: Output Snapshot

3 blocks Mined by get_chain function

3 Blocks Mined
Message dispalyed (Proof od block validity)

Conclusion:
In this article we learned basis of blockchain and some of workings also we have successfully created a blockchain application. Writing the code of blockchain and mining chain of blocks. From here you can do a lot of things and improve the application as much as you can.

Code Avaliable Here Github Link !

Happy Learnings!

Follow for more updates!

--

--