A Comprehensive Guide To Create
Blockchain In Python
Image Source: morioh.com
Blockchain is getting staggering popular due to the robust architecture that
makes it highly compatible with data storage. Though, many developers
want to know today how they can develop Blockchain in Python.
Thus, in this article, we will learn about​ Blockchain in Python.​ However,
before that, we would take a look into the initial phase explaining how
significant Blockchain is in the current marketplace.
Blockchain- Rising Development Trend
When I learned first about blockchain technology, it straight struck me that I
will remember the core of the technology. If you know little about this
technology, you must understand that the reign of this technology was
started with Bitcoin. And now it has become a significant trend due to its
unbreakable architecture for security.
Before you learn to create Blockchain in Python, You need to understand
its basic concept and what Blockchain is and how it works.
Source: researchgate.com
Blockchain system relies on a unique concept of a growing list of records
(that is, blocks) linked together, which is known as the blockchain.
Cryptocurrency- Bitcoin was the first successful implementation of this
system, and shortly after its rise in popularity, other digital currencies have
found the same principles. However, this system is not limited to storing
financial information. Instead, the type of data stored is insignificant and
independent of the blockchain network.
The data stored on the blockchain must have the following characteristics:
Immutable, Impenetrable, Continuous (no data loss), and Distributed.
These qualities are essential to maintaining the integrity of the blockchain
and the security of the network in which transactions occur. To
comprehend the elegance of such a system, and to explain the finer
details, I'll walk you through the process of creating your own blockchain in
Python. For simplicity, I will assume that the data stored in the block is
transaction data, as cryptocurrencies are currently the predominant
blockchain use case.
Building Blockchain In Python
To develop Blockchain in Python, you must have hands-on experience in
programming. Here is a comprehensive guide for creating blockchain in
Python.
Before trying this, ensure you have Python installed in your system, and it
is recommended to install the pre-built blockchain runtime environment. To
create your custom python runtime, you would need this project that you
can get by creating a free ActiveState account.
After getting started with ActiveState account pick Python 3.6 and your
operating system, moreover, we would need to add Flask to build the
REST API, which allows you to expose to the blockchain and test.
If you are not a developer and want to create blockchain, you should ​hire
python developers​ who have expertise in blockchain development.
Building Your First Block
To create the first block, we will use a standard JSON format that will store
data in each block. The data for each block appears something like:
{
"author": "author_name",
"timestamp": "transaction_time",
"data": "transaction_data"
}
Now our work is to implement this block in python. For that first we will
create a block class with aforementioned attributes. In order to make each
block unique we need to ensure that duplication doesn't occur:
class Block:
def ​init​(self, Index1, Transactions1, Timestamp, previous_hash, nonce=0):
self.index = index
self.transactions = transactions
self.timestamp = timestamp
self.previous_hash = previous_hash
self.nonce = nonce
Here you don't need to stress more about the hash of previous block or
nonce variables as of now as we will take a look at them in the latter part of
creating blockchain in Python.
Above I have already mentioned that the data is each block of the
blockchain is immutable and makes a chain through cryptographic hash to
function. This is a one-way algorithm that accepts arbitrarily-sized input
data termed as key and creates a mapping system where each value is
bound with a fixed-size value.
With Python, you can use any standard cryptographic hash function, for
example, SHA-2 functions, SHA-256 and more.
from hashlib import sha256
import json
class Block:
def init(self, index1, transactions, timestamp, previous_hash, nonce=0):
self.index = index
self.transactions = transactions
self.timestamp = timestamp
self.previous_hash = previous_hash
self.nonce = nonce
def​ ​compute_hash​(​self​):
block_string = json.dumps(​self​.__dict_​_​, sort_keys=True)
​return​ sha256(block_string.encode()).hexdigest()
With hashing each block, we ensure that the security becomes
unbreakable for each block, and it gets impossible to penetrate the data
within the block. Now the creation of single blocks is done through the
above code; it is time to chain them together.
Chaining The Blocks Into Blockchain
Here we will create a new class that will define the blockchain. Altogether,
here we will have to ensure the immutability of the entire blockchain with a
smart solution "Hash" that connects every preceding block to the previous
block. It provides that each block is based on a mechanism for protecting
the entire chain's integrity.
This is the reason for including the previous-hash variable in block class.
Here we need to initialize the block. Thus, we will define the
create_genesis_blockmethod. It depicts an initial block having index value
O, and the previous hash value 0. Subsequently, we will be able to create a
chain of blocks.
import time
class Blockchain:
def init(self):
self.unconfirmed_transactions = []
self.chain = []
self.create_genesis_block()
def create_genesis_block(self):
genesis_block = Block(0, [], time.time(), "0")
genesis_block.hash = genesis_block.compute_hash()
self.chain.append(genesis_block)
@property
def last_block(self):
return self.chain[-1]
Blockchain Proof Of Work System
The hash we've described so far is getting us part of the way there. As it is,
it is possible for someone to modify a previous block in the chain and then
recalculate each of the following blocks to create another good chain. We
also want to implement a method that allows users to reach consensus on
a single chronological date for the chain in the correct order in which the
transactions were made. To solve this problem, Satoshi Nakamoto created
the Proof of Work system.
The Proof of Work system progressively makes it challenging to perform
the work required to create a new block. This means that a person who
modifies a previous block will have to rework the block and all the blocks
that follow. The proof-of-work system must have a value beginning with a
certain number of zero bits to be scanned when hashing. This value is
termed as a nonce value. The number of primary zero bits is clarified and
known as the difficulty. While, the average work needed to develop a block
increases exponentially with the number of initial zero bits, and therefore,
by increasing the problem with each new block, we can prevent users from
modifying previous blocks, since it is practically impossible to rewrite the
following ones. Blocks and catching up with others.
For further implementation, we are adding proof_of_work method in the
blockchain class:
difficulty = 2
def proof_of_work(self, block):
block.nonce =
computed_hash = block.compute_hash()
while not computed_hash.startswith('0' * Blockchain.difficulty):
block.nonce += 1
computed_hash = block.compute_hash()
return computed_hash
Now we have a system that ensures the security of the entire chain is in
place, we have added a few more methods to the blockchain category to
bundle everything together so that we can create a chain. Initially, we will
store the data for each transaction in unconfirmed_transactions. Now when
we confirm that the new block is valid evidence that meets the difficulty
criteria, we can add it to the series. The process of performing
computational work within this system is known as mining.
def add_block(self, block, proof):
previous_hash = self.last_block.hash
if previous_hash != block.previous_hash:
return False
if not self.is_valid_proof(block, proof):
return False
block.hash = proof
self.chain.append(block)
return True
def is_valid_proof(self, block, block_hash):
return (block_hash.startswith('0' * Blockchain.difficulty) and
block_hash == block.compute_hash())
def add_new_transaction(self, transaction):
self.unconfirmed_transactions.append(transaction)
def mine(self):
if not self.unconfirmed_transactions:
return False
last_block = self.last_block
new_block = Block(index=last_block.index + 1,
transactions=self.unconfirmed_transactions,
timestamp=time.time(),
previous_hash=last_block.hash)
proof = self.proof_of_work(new_block)
self.add_block(new_block, proof)
self.unconfirmed_transactions = []
return new_block.index
Till here, we have seen an explanation of fundamentals for creating a
blockchain:
Creating a single block
Building a blockchain
Proof-of-work system
Using a mining procedure
Now the time is to use it. For that, we need to create an interface that can
enable multiple users, or nodes, supply interaction. To do this, we will
utilize Flask to build a REST-API. What is Flask? It is a lightweight web
application framework developed for Python. In ​blockchain development
service​, Flask is an important term.
from flask import Flask, request
import requests
app = Flask(name)
blockchain = Blockchain()
Here we will define the web application and then will create a local
blockchain. Later on, we would create an endpoint that enables sending
queries to show up relevant information of blockchain.
Now we would have to activate the blockchain application, which can be
done through command prompts.
python3 Blockchain.py
You need to feed something like:
● Running on ​http://127.0.0.1:5000/​ (Press CTRL+C to quit)
● Restarting with stat
● Debugger is active!
● Debugger PIN: 105-118-129
Then, in another shell, we can send a query with cURL by running:
curl ​http://127.0.0.1:5000/chain
The output will contain information like :
{"length": 1, "chain": [{"index": 0, "transactions": [], "timestamp":
1576665446.403836, "previous_hash": "0", "nonce": 0, "hash":
"e2a1ec32fcf89d0388f3d0d8abcd914f941d056c080df1c765a3f6035626fc9
4"}]}
Final Text
Through the above code, we have created a blockchain with hash-based
proof of work. I am sure this article would serve you the purpose and make
blockchain in python development a bliss for you.
Creating blockchain systems requires expertise, software outsource
companies engaged in blockchain development can provide eight
assistance. Thus, if you are not a coder, it is better to take an expert’s aid.

A Comprehensive Guide To Create Blockchain In Python | Blockchain Development In Python

  • 1.
    A Comprehensive GuideTo Create Blockchain In Python Image Source: morioh.com Blockchain is getting staggering popular due to the robust architecture that makes it highly compatible with data storage. Though, many developers want to know today how they can develop Blockchain in Python. Thus, in this article, we will learn about​ Blockchain in Python.​ However, before that, we would take a look into the initial phase explaining how significant Blockchain is in the current marketplace. Blockchain- Rising Development Trend When I learned first about blockchain technology, it straight struck me that I will remember the core of the technology. If you know little about this
  • 2.
    technology, you mustunderstand that the reign of this technology was started with Bitcoin. And now it has become a significant trend due to its unbreakable architecture for security. Before you learn to create Blockchain in Python, You need to understand its basic concept and what Blockchain is and how it works. Source: researchgate.com Blockchain system relies on a unique concept of a growing list of records (that is, blocks) linked together, which is known as the blockchain. Cryptocurrency- Bitcoin was the first successful implementation of this system, and shortly after its rise in popularity, other digital currencies have found the same principles. However, this system is not limited to storing financial information. Instead, the type of data stored is insignificant and independent of the blockchain network.
  • 3.
    The data storedon the blockchain must have the following characteristics: Immutable, Impenetrable, Continuous (no data loss), and Distributed. These qualities are essential to maintaining the integrity of the blockchain and the security of the network in which transactions occur. To comprehend the elegance of such a system, and to explain the finer details, I'll walk you through the process of creating your own blockchain in Python. For simplicity, I will assume that the data stored in the block is transaction data, as cryptocurrencies are currently the predominant blockchain use case. Building Blockchain In Python To develop Blockchain in Python, you must have hands-on experience in programming. Here is a comprehensive guide for creating blockchain in Python. Before trying this, ensure you have Python installed in your system, and it is recommended to install the pre-built blockchain runtime environment. To create your custom python runtime, you would need this project that you can get by creating a free ActiveState account.
  • 4.
    After getting startedwith ActiveState account pick Python 3.6 and your operating system, moreover, we would need to add Flask to build the REST API, which allows you to expose to the blockchain and test. If you are not a developer and want to create blockchain, you should ​hire python developers​ who have expertise in blockchain development. Building Your First Block To create the first block, we will use a standard JSON format that will store data in each block. The data for each block appears something like: { "author": "author_name", "timestamp": "transaction_time", "data": "transaction_data" } Now our work is to implement this block in python. For that first we will create a block class with aforementioned attributes. In order to make each block unique we need to ensure that duplication doesn't occur:
  • 5.
    class Block: def ​init​(self,Index1, Transactions1, Timestamp, previous_hash, nonce=0): self.index = index self.transactions = transactions self.timestamp = timestamp self.previous_hash = previous_hash self.nonce = nonce Here you don't need to stress more about the hash of previous block or nonce variables as of now as we will take a look at them in the latter part of creating blockchain in Python. Above I have already mentioned that the data is each block of the blockchain is immutable and makes a chain through cryptographic hash to function. This is a one-way algorithm that accepts arbitrarily-sized input data termed as key and creates a mapping system where each value is bound with a fixed-size value. With Python, you can use any standard cryptographic hash function, for example, SHA-2 functions, SHA-256 and more.
  • 6.
    from hashlib importsha256 import json class Block: def init(self, index1, transactions, timestamp, previous_hash, nonce=0): self.index = index self.transactions = transactions self.timestamp = timestamp self.previous_hash = previous_hash self.nonce = nonce def​ ​compute_hash​(​self​): block_string = json.dumps(​self​.__dict_​_​, sort_keys=True) ​return​ sha256(block_string.encode()).hexdigest() With hashing each block, we ensure that the security becomes unbreakable for each block, and it gets impossible to penetrate the data within the block. Now the creation of single blocks is done through the above code; it is time to chain them together.
  • 7.
    Chaining The BlocksInto Blockchain Here we will create a new class that will define the blockchain. Altogether, here we will have to ensure the immutability of the entire blockchain with a smart solution "Hash" that connects every preceding block to the previous block. It provides that each block is based on a mechanism for protecting the entire chain's integrity. This is the reason for including the previous-hash variable in block class. Here we need to initialize the block. Thus, we will define the create_genesis_blockmethod. It depicts an initial block having index value O, and the previous hash value 0. Subsequently, we will be able to create a chain of blocks. import time class Blockchain: def init(self): self.unconfirmed_transactions = [] self.chain = []
  • 8.
    self.create_genesis_block() def create_genesis_block(self): genesis_block =Block(0, [], time.time(), "0") genesis_block.hash = genesis_block.compute_hash() self.chain.append(genesis_block) @property def last_block(self): return self.chain[-1] Blockchain Proof Of Work System The hash we've described so far is getting us part of the way there. As it is, it is possible for someone to modify a previous block in the chain and then recalculate each of the following blocks to create another good chain. We also want to implement a method that allows users to reach consensus on a single chronological date for the chain in the correct order in which the transactions were made. To solve this problem, Satoshi Nakamoto created the Proof of Work system.
  • 9.
    The Proof ofWork system progressively makes it challenging to perform the work required to create a new block. This means that a person who modifies a previous block will have to rework the block and all the blocks that follow. The proof-of-work system must have a value beginning with a certain number of zero bits to be scanned when hashing. This value is termed as a nonce value. The number of primary zero bits is clarified and known as the difficulty. While, the average work needed to develop a block increases exponentially with the number of initial zero bits, and therefore, by increasing the problem with each new block, we can prevent users from modifying previous blocks, since it is practically impossible to rewrite the following ones. Blocks and catching up with others. For further implementation, we are adding proof_of_work method in the blockchain class: difficulty = 2 def proof_of_work(self, block): block.nonce = computed_hash = block.compute_hash() while not computed_hash.startswith('0' * Blockchain.difficulty):
  • 10.
    block.nonce += 1 computed_hash= block.compute_hash() return computed_hash Now we have a system that ensures the security of the entire chain is in place, we have added a few more methods to the blockchain category to bundle everything together so that we can create a chain. Initially, we will store the data for each transaction in unconfirmed_transactions. Now when we confirm that the new block is valid evidence that meets the difficulty criteria, we can add it to the series. The process of performing computational work within this system is known as mining. def add_block(self, block, proof): previous_hash = self.last_block.hash if previous_hash != block.previous_hash: return False if not self.is_valid_proof(block, proof): return False
  • 11.
    block.hash = proof self.chain.append(block) returnTrue def is_valid_proof(self, block, block_hash): return (block_hash.startswith('0' * Blockchain.difficulty) and block_hash == block.compute_hash()) def add_new_transaction(self, transaction): self.unconfirmed_transactions.append(transaction) def mine(self): if not self.unconfirmed_transactions: return False last_block = self.last_block new_block = Block(index=last_block.index + 1, transactions=self.unconfirmed_transactions,
  • 12.
    timestamp=time.time(), previous_hash=last_block.hash) proof = self.proof_of_work(new_block) self.add_block(new_block,proof) self.unconfirmed_transactions = [] return new_block.index Till here, we have seen an explanation of fundamentals for creating a blockchain: Creating a single block Building a blockchain Proof-of-work system Using a mining procedure Now the time is to use it. For that, we need to create an interface that can enable multiple users, or nodes, supply interaction. To do this, we will
  • 13.
    utilize Flask tobuild a REST-API. What is Flask? It is a lightweight web application framework developed for Python. In ​blockchain development service​, Flask is an important term. from flask import Flask, request import requests app = Flask(name) blockchain = Blockchain() Here we will define the web application and then will create a local blockchain. Later on, we would create an endpoint that enables sending queries to show up relevant information of blockchain.
  • 14.
    Now we wouldhave to activate the blockchain application, which can be done through command prompts. python3 Blockchain.py You need to feed something like: ● Running on ​http://127.0.0.1:5000/​ (Press CTRL+C to quit) ● Restarting with stat ● Debugger is active! ● Debugger PIN: 105-118-129 Then, in another shell, we can send a query with cURL by running: curl ​http://127.0.0.1:5000/chain The output will contain information like : {"length": 1, "chain": [{"index": 0, "transactions": [], "timestamp": 1576665446.403836, "previous_hash": "0", "nonce": 0, "hash": "e2a1ec32fcf89d0388f3d0d8abcd914f941d056c080df1c765a3f6035626fc9 4"}]}
  • 15.
    Final Text Through theabove code, we have created a blockchain with hash-based proof of work. I am sure this article would serve you the purpose and make blockchain in python development a bliss for you. Creating blockchain systems requires expertise, software outsource companies engaged in blockchain development can provide eight assistance. Thus, if you are not a coder, it is better to take an expert’s aid.