Python Blockchain – How to create Genesis Block and Creating Blockchain

Python Blockchain - How to create Genesis Block and Creating Blockchain

How to create Genesis Block and Creating Blockchain

The blockchain is the fundamental building block behind the world’s most popular digital currency Bitcoin.

The tutorial deeply dealt with the intricacies of Bitcoin explaining fully the blockchain architecture. The next step is to build our own blockchain.

Satoshi Nakamoto created the first virtual currency in the world called Bitcoin. Looking at the success of Bitcoin, many others created their own virtual currencies. To name a few − Litecoin, Zcash, and so on.

Now, you may also like to launch your own currency. Let us call this as TPCoin (TutorialsPoint Coin). You will write a blockchain to record all transactions that deal with TPCoin.

The TPCoin can be used for buying Pizzas, Burgers, Salads, etc.

There may be other service providers who would join your network and start accepting TPCoin as the currency for giving out their services. The possibilities are endless.

In this tutorial, let us understand how to construct such a system, – How to create Genesis Block and Creating Blockchain and launch your own digital currency in the market.

Components Involved in creating Blockchain Project Development

The entire blockchain project development consists of three major components −

  • Client
  • Miners
  • Blockchain

Client

The Client is the one who will buy goods from other vendors. The client himself may become a vendor and will accept money from others against the goods he supplies.

We assume here that the client can both be a supplier and a recipient of TPCoins. Thus, we will create a client class in our code that has the ability to send and receive money.

Miner

The Miner is the one who picks up the transactions from a transaction pool and assembles them in a block.

The miner has to provide a valid proof-of-work to get the mining reward. All the money that miner collects as a fee will be for him to keep.

He may spend that money on buying goods or services from other registered vendors on the network, just the way a Client described above does.

Creating Blockchain

Finally, a Blockchain is a data structure that chains all the mined blocks in a chronological order. This chain is immutable and thus temper-proof.

Now, Let’s start procedure making a genesis block.

We assume that the originator of TPCoins initially gives out 500 TPCoins to a known client Dinesh. For this, he first creates a Dinesh instance −

Dinesh = Client()

We then create a genesis transaction and send 500 TPCoins to Dinesh’s public address.

t0 = Transaction (
   "Genesis",
   Dinesh.identity,
   500.0
)

Now, we create an instance of Block class and call it block0.

block0 = Block()

We initialize the previous_block_hash and Nonce instance variables to None, as this is the very first transaction to be stored in our blockchain.

block0.previous_block_hash = None
Nonce = None

Next, we will add the above t0 transaction to the verified_transactions list maintained within the block −

block0.verified_transactions.append (t0)

At this point, the block is completely initialized and is ready to be added to our blockchain. We will be creating the blockchain for this purpose.

Before we add the block to the blockchain, we will hash the block and store its value in the global variable called last_block_hash that we declared previously. This value will be used by the next miner in his block.

We use the following two lines of coding for hashing the block and storing the digest value.

digest = hash (block0)
last_block_hash = digest

Python Creating Blockchain

A blockchain contains a list of blocks chained to each other. To store the entire list, we will create a list variable called TPCoins −

TPCoins = []

We will also write a utility method called dump_blockchain for dumping the contents of the entire blockchain.

We first print the length of the blockchain so that we know how many blocks are currently present in the blockchain.

def dump_blockchain (self):
   print ("Number of blocks in the chain: " + str(len (self)))

Note that as the time passes, the number of blocks in the blockchain would be extraordinarily high for printing.

Thus, when you print the contents of the blockchain you may have to decide on the range that you would like to examine.

In the code below, we have printed the entire blockchain as we would not be adding too many blocks in the current demo.

To iterate through the chain, we set up a for loop as follows −

for x in range (len(TPCoins)):
   block_temp = TPCoins[x] 

Each referenced block is copied to a temporary variable called block_temp.

We print the block number as a heading for each block. Note that the numbers would start with zero, the first block is a genesis block that is numbered zero.

print ("block # " + str(x))

Within each block, we have stored a list of three transactions (except for the genesis block) in a variable called verified_transactions.

We iterate this list in a for loop and for each retrieved item, we call display_transaction function to display the transaction details.

for transaction in block_temp.verified_transactions:
   display_transaction (transaction)

The entire function definition is shown below −

def dump_blockchain (self):
   print ("Number of blocks in the chain: " + str(len (self)))
   for x in range (len(TPCoins)):
      block_temp = TPCoins[x]
      print ("block # " + str(x))
      for transaction in block_temp.verified_transactions:
         display_transaction (transaction)
         print ('--------------')
      print ('=====================================')

Note that here we have inserted the separators at appropriate points in the code to demarcate the blocks and transactions within it.

As we have now created a blockchain for storing blocks, our next task is to create blocks and start adding it to the blockchain.

For this purpose, we will add a genesis block that you have already created in the earlier step.

Adding Genesis Block for Creating Blockchain

Adding a block to the blockchain involves appending the created block to our TPCoins list.

TPCoins.append (block0)

Note that unlike the rest of the blocks in the system, the genesis block contains only one transaction which is initiated by the originator of the TPCoins system.

Now, you will dump the contents of the blockchain by calling our global function dump_blockchain −

dump_blockchain(TPCoins)

When you execute this function, you will see the following output −

Number of blocks in the chain: 1
block # 0
sender: Genesis
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100ed272b52ccb539
e2cd779c6cc10ed1dfadf5d97c6ab6de90ed0372b2655626fb79f62d0e01081c163b0864
cc68d426bbe9438e8566303bb77414d4bfcaa3468ab7febac099294de10273a816f7047d
4087b4bafa11f141544d48e2f10b842cab91faf33153900c7bf6c08c9e47a7df8aa7e60d
c9e0798fb2ba3484bbdad2e4430203010001
-----
value: 500.0
-----
time: 2019-01-14 16:18:02.042739
-----
--------------
=====================================

At this point the blockchain system is ready to use. We will now enable the interested clients to become miners by providing them a mining functionality!

React Redux Firebase Authentication with CRUD Application

Video

React Redux Firebase Authentication With CRUD Application

55 Lectures 4 hours

   

Data Science with Python (beginner to expert)

Video

Data Science With Python (Beginner To Expert)

51 Lectures 40 hours

   Uplatz4.7★★★★★

Advanced Unsupervised Machine Learning With Python By Spotle.ai

Video

Advanced Unsupervised Machine Learning With Python By Spotle.Ai

16 Lectures 1.5 hours

   

Agile project management Artificial Intelligence aws blockchain cloud computing coding interview coding interviews Collaboration Coursera css cybersecurity cyber threats data analysis data breaches data science data visualization devops django docker finance flask hacking html It Certification java javascript ketan kk Kubernetes machine learning machine learning engineer mongoDB Network & Security network protocol nodejs online courses online learning Operating Systems Other It & Software python Software Engineering Terraform Udemy courses VLAN web development

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.