Python Program to Create Blockchain and Mining

| | ,

Home » Python Program to Create Blockchain and Mining

Blockchain technology is one of the most talked-about topics in the world today. It is revolutionizing the way we do things. Businesses should take note and explore what can be done using blockchain. This tutorial explains a Python program to create Blockchain and mining.

What is Blockchain?

Before we actually look at the code, let’s understand what blockchain is. Imagine you have a spreadsheet on your computer – you can edit them and do anything you want with it. Blockchain is similar to the spreadsheet and it can be used to store just about anything. Anything that is stored on the blockchain is public and if you have a copy of the blockchain, you have all the information that is stored on it. In our case, we are going to create the blockchain using Python.

Prerequisites:

Hashlib: A hashlib is a collection of hash functions to manipulate strings. Hashlib is used to create hash values from a string. To install haslib use the following command:

pip install hashlib

Step -1: Importing the dependencies and Creating a block

In this Python program to create Blockchain, we first have to import some pre-installed libraries:

import datetime
import hashlib

Creating a block

A blockchain has two classes, a block class and a blockchain class. When we mine a block, we add it to the blockchain which is an object that holds information about all of our blocks. A blockchain object is therefore a collection of all of our blocks so far and each one is called an instance of the block class.

class Block:
    blockNo = 0
    data = None
    next = None
    hash = None
    nonce = 0
    previous_hash = 0x0
    timestamp = datetime.datetime.now()

Every block has some type of info

1. Every block has a number 

2. Has data we want to store

3. A pointer to the next block

4. A hash id

5. Every block also has a previous block hash id 

6. Timestamp (it’s not really important to this blockchain, but if it is on a blockchain network then it is important because it synchronizes them together)

Note: The blockchain is immutable because to change any block in blockchain it requires you to change every subsequent block because of the previous hash, the previous hash is what ties them together

Note: A nonce is just a number that we increment every single time we validate a guess and by changing that one number we are getting a completely different hash.

Here we created a block to store data

def __init__(self, data):
        self.data = data

Step -2: Calculating the hash of the block 

so calculating the block required a few things 

1. the nonce

2. the data

3. previous_hash

4. timestamp

5. and block no

We added all of these features up into one single string and we then run this through the SHA-256 hashing function and that gives us our block hash. This is the structure of a block.

def hash(self):
        h = hashlib.sha256()
        h.update(
        str(self.nonce).encode('utf-8') +
        str(self.data).encode('utf-8') +
        str(self.previous_hash).encode('utf-8') +
        str(self.timestamp).encode('utf-8') +
        str(self.blockNo).encode('utf-8')
        )
        return h.hexdigest()

this function simply formats the block to appear nice and easy to read.

def __str__(self):
     return "Block Hash: " + str(self.hash()) + "\nBlockNo: " + str(self.blockNo) + "\nBlock Data: " + str(self.data) + "\nHashes: " + str(self.nonce) + "\n--------------"

Step -3: Creating the blockchain

So a blockchain is a linked list that accepts all the items. It can be seen when we calculate the hash of the block that includes a hash of the previous block. Here the first block that we created is a genesis block

class Blockchain:

    diff = 20
    maxNonce = 2**32
    target = 2 ** (256-diff)

    block = Block("Genesis")
    dummy = head = block

The blockchain is just like a linked list, and to add something to the list all we need here is a few lines of code. And because it’s a blockchain, we are creating an endless rope from one block to the next. To do this, we are going to set the previous has equal to the current block at the top of the list, and we will set the new block equal to that of the current block + 1.

Also, If you remember every block has a pointer to the next block so we added the next pointer equal to whatever block we wanted to add and that adds the block to the end of the list  

def add(self, block):

        # self.block refers to the block that is at the top of our link list
        block.previous_hash = self.block.hash()
        # we are setting the new block equal to current block plus 1
        block.blockNo = self.block.blockNo + 1

        self.block.next = block
        # this sign just moves the next pointer up so that it can keep adding new block
        self.block = self.block.next

Mining:

The hash of a block is calculated by taking all the data of the block and hashing it with a hashing algorithm such as SHA-256. This is exactly how bitcoin does it.

so this for loop just guesses pretty much from zero to the maximum nonce and every time we loop through what we’re doing is checking the current block’s hash value. It’s less than or equal to the target. 

  def mine(self, block):
        for n in range(self.maxNonce):
            if int(block.hash(), 16) <= self.target:
                self.add(block)
                print(block)
                break
            else:
                block.nonce += 1

we have a blockchain class here after that a formula is used to create a for loop and the for loop continues the mining process unless it mines 10 blocks.

blockchain = Blockchain()

for n in range(10):
    blockchain.mine(Block("Block " + str(n+1)))

all we are doing here is printing out each block in a blockchain

while blockchain.head != None:
    print(blockchain.head)
    blockchain.head = blockchain.head.next

All the code in one section:

import datetime
import hashlib

class Block:
    blockNo = 0
    data = None
    next = None
    hash = None
    nonce = 0
    previous_hash = 0x0
    timestamp = datetime.datetime.now()

    def __init__(self, data):
        self.data = data

    def hash(self):
        h = hashlib.sha256()
        h.update(
        str(self.nonce).encode('utf-8') +
        str(self.data).encode('utf-8') +
        str(self.previous_hash).encode('utf-8') +
        str(self.timestamp).encode('utf-8') +
        str(self.blockNo).encode('utf-8')
        )
        return h.hexdigest()

    def __str__(self):
        return "Block Hash: " + str(self.hash()) + "\nBlockNo: " + str(self.blockNo) + "\nBlock Data: " + str(self.data) + "\nHashes: " + str(self.nonce) + "\n--------------"

class Blockchain:

    diff = 20
    maxNonce = 2**32
    target = 2 ** (256-diff)

    block = Block("Genesis")
    dummy = head = block

    def add(self, block):

        block.previous_hash = self.block.hash()
        block.blockNo = self.block.blockNo + 1

        self.block.next = block
        self.block = self.block.next

    def mine(self, block):
        for n in range(self.maxNonce):
            if int(block.hash(), 16) <= self.target:
                self.add(block)
                print(block)
                break
            else:
                block.nonce += 1

blockchain = Blockchain()

for n in range(10):
    blockchain.mine(Block("Block " + str(n+1)))

while blockchain.head != None:
    print(blockchain.head)
    blockchain.head = blockchain.head.next

Output

Final Words

We hope you enjoyed this blog post on how to build a blockchain. This is just a basic example of a Python program to create Blockchain, but with these fundamentals in mind, you can now start creating your own blockchain for whatever purpose you dream up! That’s it for this post and we’d love to hear from you if you have any questions about the process.

Here are some useful tutorials that you can read:

Spread the love
 
   
Previous

Create Websocket Server using Python and Tornado

RDF Processing in Python with RDFLib

Next

Leave a Comment