A Simple Blockchain in Python

  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.
  2. The Miners: miners are used for creating new blocks and adding it to the chain. The job of mining is not a simple one specially if the chain is giant. The miners have the task to find a valid nonce and hash combination, considering the nonce is 32 bit, hash is 256 bits, there are about four billion combinations to check for the right combination. On hitting the “golden nonce” the block is added to the chain. Imagine making change to a block in the chain and creating a domino where you need to make changes to every block after that block, running the miner for all those block. Well let’s just accept the fact it’s too much and hence the changes to a block , already in the chain is really hard.
  3. The Nodes: nodes are the devices that maintain the copies of the block chain. The decentralization of the block chain is what makes it so attractive for bitcoin users. No one organization is in control, infact the chain is distributed to the node — connected parties. This is why block chains are also called distributed ledgers. The nodes maintain their own copy of the blockchain and verify mining of any new blocks. The cahanges to the chain are easily accessible and can be read. This maintains trust and transparency between users.
class block:
def __init__(self,data,prevHash=None):
self._data=data
self._hash=hashlib.sha256(str(_data).encode())
self._prevHash=prevHash
self._next=None
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.

--

--

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