A Simple Blockchain in Python

Introduction To BlockChain

BlockChain, an unalterable record system which is the backbone of cryptocurrency exchanges. Bitcoin being one of the most famous ones. A blockchain can be visualized as a database in which data can only be added, neither altered nor removed. The addition of a new block is also not something easy. The block chain is also not saved on one location but rather a copy of it is present to all the connected peers. This improves the availability and protects the data loss due to a single point failure. Block chains provides transparency and reduces the risk of frauds and is scalable.

Block chain uses three concepts:

  1. The Block: the block constitutes the chain (duh!..) and contains of the data, a self hash. We generate a random 32 bit number when the block is created(this is called a nonce). The 256 bit number combined with the nonce creates a hash for the block. The data in the block is signed by the nonce and the hash. along with data and self hash the block also contains the hash of the previous block in the chain.

As by now you might have gotten an idea how how complex it is to design and develop a blockchain at it’s full glory. So we will try to build a very simple blockchain where the block will have data, and the data itself is hashed to create a self hash(basically I am going to skip the whole nonce and then hashing thing as it is just a demo. Maybe in a future post).

The main motive of this post is to visualize a problem and try to make a software solution for the problem, which for us is to create a very basic form of the blockchian.

Creating a basic blockchain

The first thing that comes to the mind as soon as you hear a chain of blocks connected to the previous block, is a linked list. The linked list would be easier to visualize as a chain and it is a scaleable data structure. Okay, so we have a data structure to work on. Now the major question is, How will we create the hash. Well thanks to the huge python community we have a python module that will provide us with the hashing methods. I will be using hashlib and can be installed by a simple pip install hashlib.

We now create a basic structure for the block to be put in the linked list we will use as our blockchain.

class block:
def __init__(self,data,prevHash=None):
self._data=data
self._hash=hashlib.sha256(str(_data).encode())
self._prevHash=prevHash
self._next=None

For creating a new block we just create a new object of the block class(makes sense right!).

Next we create the chain class and give it a validation function and a function to add a new block. Basically it will check the chain is still un-tampered before adding the new block.

class Blockchain:
def __init__(self):
self.head=None #initialize the chain head

def validate_chain(self):
temp=self.head
previousHash=None
while temp!=None:
if temp._prevHash!=previousHash:
return False #can also have it raise an error
previousHash=temp._prevHash
temp=temp._next
return True #valid chain so far
#the function to insert a new block to the chain. Kind of like a miner function
def add_block(self,data):
if self.validate_chain():
#if the chain is valid
if self.head==None:
self.head=block(data)#if chain is empty, new node is head
else:
temp=self.head
while temp._next!=None:
temp=temp._next # while not last block goto next block
temp._next= block(data,prevHash=temp._hash) #added a new block to the end with data=data and a previous hash.

The above code can be used to create a simple blockchain with the basic characteristics. Blockchain is an awesome tech and can have a number of applications. We could even have a branched blockchain using a graph data structure and changing the hash connection rule.

Please comment any suggestions. I will try to post some more projects soon.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store