Blockchain has found application in numerous fields, including cryptocurrency, banking, supply chain management, and healthcare. Simplistically speaking, blockchain enables data to be embedded in a digital code and stored in transparent and shared databases in a way that is secure and cannot be tampered with, deleted, or revised.
Let us assume that we have been asked to create a blockchain that can store cross-border transactional data. Donning your coder’s hat, you could start with the following five building blocks to implement a blockchain in Python:
1. Storing data in blocks
The data inside a blockchain is stored in the JSON format. This data is often referred to as “transactions”; these transactions are stored in blocks, where a block might contain more than one transaction.
Every block would have a unique block ID (index in the above code).
2. Hashing the blocks
The purpose of a hash function in blockchain is to ensure that the data in the chain cannot be meddled with. This function takes data as input and produces another piece of data (also called “hash”) of a fixed size as output. The hash is produced in a way that it becomes impossible for someone to detect the input from the hash. One of the hash functions in Python is sha224(). Its implementation is as follows:
This hash function can be kept inside the existing Block object to ensure that the data inside the block is secure.
3. Linking the blocks together – Step 1
Since a blockchain is meant to be a collection of blocks, we must ensure that blocks are linked in a specific order and this order cannot be compromised. To achieve this, every block is associated with a “previous hash” – i.e. the hash of the previous block. Since the first block does not have any preceding block, it is called a “genesis block”. 
4. Adding a nonce variable – Step 2
A nonce is a variable that can be changed until we get a hash with some pre-defined constraint. This would make the task of calculating the hash from the input difficult and random. A simple implementation could be:
5. Putting additional blocks in the chain – Step 3
To add a block to the chain, we first keep a function to verify the integrity of the data present. The next step is to make sure that the previous hash field of the added block is the last block that was present in our blockchain.
- The truth about Blockchain
- Develop a blockchain application from scratch in Python
- From zero to blockchain in Python part-1