Learn to Build a Blockchain Application in Python

0
730
Blockchain Application

Have you ever heard of blockchain application? Well, if you didn’t, you surely are living under a rock.

The blockchain is currently transforming every industry. That’s why, in today’s tutorial, we will learn how to build a blockchain application using Python.

Building A blockchain application in Python

To get started, we first need to define the use of our application. Let’s stick to building a blockchain application that allows users to share stories using blockchain. As we will be using blockchain, there will be added benefits including immutability, unhackable system, and persistence.

The structure of the data that we are aiming is as below.

Story
Author
TimeStamp

These are the three minimum entities we need to create in the blockchain. You canadd more entities if you need. Also, to store the data, we will be using JSON. JSON is a popular way of storing information. Below is an example of how a sample data will look like.

{
    "author": "An_author_name", 
    "story": "A story that provokes the mind", 
    "timestamp": "When the story is posted?"
}

Note: – Through the tutorial, we will use both “data” and “transaction” interchangeably. If we say that we need to store transaction into the block, then it means “data” as well.

Block Code

The block code for the above-mentioned entities should be as simple as below.

class Block:
   def __init__(self, index, transactions, timestamp):
       self.index = []
       self.transactions = transactions
       self.timestamp = timestamp

Making The Block Immutable

As we already know that blockchain is immutable. To achieve immutability, we need to use hash functions in our blockchain app. So, how exactly a hash function work?

Hash functions takes data as an input and produce fixed size data as output. This way, it can be used to validate data. It compute the data and then comes out with a hash value. If the input data is manipulated, the hash value will change. Also, the hash function is easy to compute and is completely secured, it is not possible to guess the input using the hash value.

Let’s write the hash function for our blockchain application.

from hashlib import sha256
import json

def compute_hash(block):
       """
       The function will compute the block hash and make
       the block immutable
       """
       block_string = json.dumps(self.__dict__, sort_keys=True)
       return sha256(block_string.encode()).hexdigest()

Building the blockchain

The blockchain is composed of blocks and chain. Also, we need to store them and access them easily. To do so, we will be using Python list. A list is a data type and should work for solving the problem at hand. In later part of the tutorial, we will also write code to make blocks immutable, giving immutability to the whole blockchain.

Every blockchain has its first block which is known as genesis block. Without the genesis block, it is impossible to create the blockchain. A good analogous example to the genesis block is the seed. Without it, the tree just cannot grow.

To build the blockchain, we will create a new Blockchain class.

class Blockchain:
    def __init__(self):
        self.unconfirmed_transactions = [] # data yet to get into blockchain
        self.chain = []
        self.create_genesis_block()
 
    def create_genesis_block(self):
        """
       Genesis block is the seed of the chain. This block will
       always start from index 0 and two more parameters which are previous_hash
       and valid hash
       """
        genesis_block = Block(0, [], time.time(), "0")
        genesis_block.hash = genesis_block.compute_hash()
        self.chain.append(genesis_block)
 
    @property
    def last_block(self):
        return self.chain[-1]

Proof of Work algorithm

With our simple blockchain created, it’s now time to protect our genesis block. We don’t want anyone to alter it or start a new fresh blockchain by providing new hash information or altering the genesis block. 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 can add a nonce to our block field. This will ensure that our hash maintains the constraint. If you are still confused, read this amazing article on proof of work by Aleksandr Bulkin.

Now, let’s write the proof of work method. It should be within the Blockchain class.

def proof_of_work(self, block):
       """
       Function that sets difficulty criteria
       """
       block.nonce = 0
       computed_hash = block.compute_hash()
       while not computed_hash.startswith('0' * Blockchain.difficulty):
           block.nonce += 1
           computed_hash = block.compute_hash()
       return computed_hash

Adding Blocks to the Chain

After implementing Proof of Work, it’s now time to add blocks. Also, before we add, we need to verify if the POW (proff of work) is working or not. Let’s do it below.

Note: The below code will be added to Blockchain Class.

def add_block(self, block, proof):
       """
      	 Adding a block for verification purposes.
       """
       previous_hash = self.last_block.hash
       if previous_hash != block.previous_hash:
           return False
       if not self.is_valid_proof(block, proof):
           return False
       block.hash = proof
       self.chain.append(block)
       return True
   def is_valid_proof(self, block, block_hash):
       """
       Check if block_hash is valid hash of block and satisfies
       the difficulty criteria.
       """
       return (block_hash.startswith('0' * Blockchain.difficulty) and
               block_hash == block.compute_hash())

Last Step: Mining
Our last step is to set up mining method in our blockchain. As we are using Proof of Work algorithm, we need to do block mining. The mining method will also ensure that the miners get something in reward while validating transactions in the blockchain.

The below methods will be included in the Blockchain class.

def add_new_transaction(self, transaction):
           self.unconfirmed_transactions.append(transaction)
   def mine(self):
       """
       Mining method that takes pending transactions and add them
       to the blockchain
       """
       if not self.unconfirmed_transactions:
           return False
       last_block = self.last_block
       new_block = Block(index=last_block.index + 1,
                         transactions=self.unconfirmed_transactions,
                         timestamp=time.time(),
                         previous_hash=last_block.hash)
       proof = self.proof_of_work(new_block)
       self.add_block(new_block, proof)
       self.unconfirmed_transactions = []
       return new_block.index

Conclusion: –
That’s it. We have successfully created a blockchain application. To create the interface, you need to use the Flask framework. This aspect of the tutorial is beyond the scope, and that’s why we will not cover it here By going through the tutorial, you should be able to implement basic blockchain. From here you can do a lot of things and improve the application as much as you can.

LEAVE A REPLY

Please enter your comment!
Please enter your name here