How to create a simple blockchain using python ? Part 1

This is the first part of the blockchain with python series.

In this this article we will see how we can create a simple blockchain using python. We will focus on the basic programming around it. We will be using simple modules in order to do so.

And before diving into the step by step procedure, you must have a basic knowledge about blockchains. Check out my blockchain explained series which is just a series of 3 articles. It will give the basic idea about it.

So without further ado, lets begin.

Data files

We will be making 2 files in our working directory. One will have the code which will used to add and validate new blocks that are wanted to be added (i.e. a .py file), and other will be having the blockchain data itself. For which we will be using a csv file.

Lets say we call our blockchain RoxxCoin, hence, rc.csv. And the python file will be

python implementation of blockchain
Ignore the static and template directory and other .py files. (those are personal)

Every time we will be fetching the csv file into the .py file in order to do all the adding and validating process. And of course each time, we will upgrade the csv file too. We will see how.

Remember this article only focusses on how we program the interface which one will use in the network to do transaction. i.e. add a block. In the next part, I will be showing how we will be making our own blockchain/cryptocurrency for a small LAN.

You can get all the code from my github too.

Importing packages

import hashlib
import pandas as pd

We will need only 2 packages for now. Hashlib for hashing purposes and pandas to manage our data.

Data storage

In the csv file, I want you to copy the exact following text.

0,1,0,"('10 rc from alice to ben ', '69 rc from tobey to gwen')",whatever,694f79a78fb00c7782fa464214e178d0e4f9c2a15130432918c7000ebdc581f0

What is this? well this is the entire list of transactions ever happened, in the csv format. We are not bothering about how we get this first block, or we can say the genesis block.

Notice how we have the as 1, nonce as 0, txn(transactions) as “(’10 rc from alice to ben ‘, ’69 rc from tobey to gwen’)”, ph (previous hash) as ‘whatever’ and h (hash) as ‘whatever’,694f79a78fb00c7782fa464214e178d0e4f9c2a15130432918c7000ebdc581f0.

Importing the blockchain

chain = pd.read_csv('rc.csv', index_col=[0])

Notice how the csv file has an unnamed column, I did it because it was giving me trouble during the whole import and saving process. And using this import syntax helped. But don’t bother about that.

Validating and adding class

difficulty = 0
class adder:
    def __init__(self, prev_hash, nonce, *transactions):
        self.prev_hash = prev_hash
        self.nonce = nonce
        self.transactions = transactions
        self.nt = ''
        for i in transactions:
            self.nt += i
        self.hasin = prev_hash + self.nt + str(nonce)
        self.hash = hashlib.sha256(self.hasin.encode()).hexdigest()

        #validating and preparing the block IF is found valid

        if prev_hash == chain.iloc[-1, -1] and self.hash.startswith('0' * difficulty):
            uh = {'': [len(chain) + 1],
                  'nonce': [nonce],
                  'txn': [transactions],
                  'ph': [prev_hash],
                  'h': [self.hash]}
            self.newblock = pd.DataFrame(uh)

            print('sorry your request has been declined')
    def generate(self):
        a = pd.concat([chain, self.newblock], ignore_index=True) # adding it to the chain
        return a

t1 = '35 rc from tony to steve'
t2 = '20 rc from may to steve'

newchain = adder('694f79a78fb00c7782fa464214e178d0e4f9c2a15130432918c7000ebdc581f0', 3, t1, t2).generate()

Alright, lets try to understand what we just did here. We made a class which will basically takes the request of transactions made by a person to validate it, and if comes out to be valid, add it to the main data storage.

We are taking the its prev_hash, nonce and a list of transaction that are to be made. As you can see, we are using prev_hash, string of all transactions and the nonce to create a hash.

Also as the proof of work(could be different), we want the requester to know the prev_hash or you can say, the last hash of the chain, and to choose a nonce which creates a hash starting with a certain amount of zeroes. As you increase the ‘difficulty’ variable, the difficulty will increase(we have selected it as zero so that the difficulty becomes zero, hence any nonce would work). And if the criterias are met, we prepare the new block in the form of a pandas dataframe and add it to the csv file using the generate function. We also return the new generated chain to the requester.

And if any one of the criteria is not met, we tell the requester, that the request was declined and quit the program.

Now lets check out if the changes we made are there in the csv file.

0,1,0,"('10 rc from alice to ben ', '69 rc from tobey to gwen')",whatever,694f79a78fb00c7782fa464214e178d0e4f9c2a15130432918c7000ebdc581f0
1, 2, 3, "('35 rc from tony to steve', '20 rc from may to steve')", 694f79a78fb00c7782fa464214e178d0e4f9c2a15130432918c7000ebdc581f0,

And we are done, we successfully programmed a blockchain. You can add more transactions like this.

But of course the real life implementation of this technology has a lot more stuff. We make it so that it can be used in a network, which we simply did not do here. But the thing we just made is the most important thing, and if you understood it, that’s great because that’s almost the only programming part.

In the next part I will try to cover how we implement it in a small LAN, or you can say, make a way so that different people can interact with it in a LAN.