Using Python Tools and Libraries for Blockchain Programming

0
10543
Python tools for blockchain programming
Python tools for blockchain programming

With the ever increasing popularity of blockchain technology, it is inevitable that Python, with its powerful libraries, would find a place in blockchain programming. Python has several specific tools and libraries for dApps and blockchain implementation. While blockchain technology is finding new uses in various fields, the use of Python makes it more powerful.

Blockchain is a state-of-art technology that is always associated with security and a higher degree of privacy in assorted applications. Nowadays, blockchain technology is not limited to just cryptocurrencies but is being implemented in various social and corporate segments.

These include e-governance, social networking, e-commerce, transportation, logistics, professional communications and many others.

The blockchain refers to the high-performance and security-aware technology in which a digital ledger is maintained. The digital ledger is quite transparent and there is no scope for any manipulation in the records by intermediaries or any administrator. The records of all the transactions are logged in the blockchain ledger, and the operations are committed finally with different protocols and algorithms that cannot be hacked by third party intrusions.

Listed below are some examples of how blockchain is implemented.

  • Entertainment: KickCity, B2Expand, Spotify, Guts, Veredictum, etc.
  • Social networks: Matchpool, Minds, MeWe, Steepshot, Dtube, Mastodon, Sola, etc.
  • Cryptocurrency: Bitcoin, Litecoin, Namecoin, Dogecoin, Primecoin, Nxt, Ripple, Ethereum, etc.
  • Retail: Warranteer, Blockpoint, Loyyal, Fluz Fluz, Shopin, Spl.yt, Opskins, Ecoinmerce.io, Every.Shop, Portion, Buying.com, etc.
Figure 1: Number of blockchain wallet users worldwide (2016-2019)
Figure 2: Genration of hash values using blockchain implementation

In a blockchain network, there exist blocks of different data elements and records. Each block participates in the blockchain network and is immutable. The term ‘immutable’ here means that it is secured and non-breakable. Hence, it forms the blockchain of a secured chain of blocks without any probabilities of intentional or accidental tampering and leakage of data.

The first block in the chain of networks is known as the Genesis Block from where the blockchain initiates the transactions. The chain grows by inserting different blocks. Every block is encrypted with the previous block, and hence becomes secure. It is difficult to crack the previous states because of so many encryptions.

For information on frameworks like Etherlime, Dot-Abi-cli, Web3JS, PyEthereum, Nethereum, Cava, Solidity, CPP Ethereum, Liquidity, Infura, Lamden, MyThril, Coq, etc, do go online.

Python tools for blockchain programming

Python is a key programming language that is used in almost every area of high performance computing. It provides the tools and libraries that can be used for blockchain development including decentralised applications. As in blockchain technology, there are secured protocols and algorithms, Python has numerous toolkits available on its official repository https://pypi.org/. The specific libraries for decentralised applications and blockchain implementations are available at the following URLs:

  • https://pypi.org/search/?q=blockchain
  • https://pypi.org/search/?q=dapp
Figure 3: Execuing the web based blockchain code

Installation of libraries and Python tools for blockchain programming

The additional libraries and toolkits can be installed with existing Python using the Pip installer, as follows:

$ pip install <packagename>

In the Windows operating system, the following instruction is used:

WindowsDrive:\Python Installation Directory>python -m pip install <packagename>

The blockchain technology is highly dependent on and makes use of integration with dynamic cryptography and encryption. For this, the Hashlib library can be installed using the above instruction.

Building blockchain applications

The following scenario is of a secured blockchain that is generating hash values so that overall transactions and records are highly secured. In the following code blockchainhash.py, the dynamic hash value is generated. This is the base of any blockchain with different transactions in a chain, which makes the overall blockchain.

blockchainhash.py
import datetime as date
import hashlib as hasher
class Block:
def __init__(self, idx, ts, mydata, backhash):
self.idx = idx
self.ts = ts
self.mydata = mydata
self.backhash = backhash
self.hash = self.hashop()
def hashop(self):
shahash = hasher.sha256()
shahash.update(str(self.idx) + str(self.ts) + str(self.mydata) + str(self.backhash))
return shahash.hexdigest()
def genesis():
return Block(0, date.datetime.now(), “Genesis Block”, “0”)
def next_block(last_block):
this_idx = last_block.idx + 1
this_ts = date.datetime.now()
this_mydata = “Block” + str(this_idx)
this_hash = last_block.hash
return Block(this_idx, this_ts, this_mydata, this_hash)
blockchain = [genesis()]
back_block = blockchain[0]
maxblocks = 20
for i in range(0, maxblocks):
block_to_add = next_block(back_block)
blockchain.append(block_to_add)
back_block = block_to_add
print “Block #{} inserted in Blockchain”.format(block_to_add.idx)
print “Hash Value: {}\n”.format(block_to_add.hash)

With the execution of the code, the outcome shown in Figure 2 is obtained with different hash values, and it provides a higher degree of security using cryptography functions. Using these hash values, hacking or sniffing the transaction is almost impossible.

Figure 4: Performing the transaction using cURL
Figure 5: Mining the records and transactions

Deployment of network based distributed blockchains

As in the earlier example, the implementation of the hash function with the blocks is done on a standalone system. In case of the actual blockchain, it is required to be distributed so that different users can initiate their transactions and blocks.

For distributed and Web based implementations, there are different frameworks in Python. Flask is one of the prominent and popular Web frameworks used with Python programming.

$ pip install flask

In the Windows OS, the following instruction is used to install Flask with an existing Python installation:

WindowsDrive:\Python Installation Directory>python -m pip install flask

In blockchain programming, the Proof-of-Work (PoW) is one of the very important algorithms. It is used to confirm and validate the transactions so that the new blocks are added in the blockchain. It is referred to as the key consensus algorithm for the verification and authenticity of the transactions. In the blockchain network, different miners participate for validation and to complete their transactions. For successful validation, the miners are rewarded with digital cryptocurrencies as their remuneration.

This process also avoids the double spending problem so that the digital currency or transaction is implemented in a secure way. For example, when A transmits a file or digital currency to B, that specific file or currency value in the records of A must be deleted and then should be reflected in the records of B. Traditionally, this is the role performed by the bank as an intermediary. In the case of a blockchain network, it is implemented without any intermediary and is validated automatically using specialised algorithms. If there are instances of the transaction from a sender not getting deleted, it will de-evaluate the currency, whatever is the type of currency used.

miner_address = “***************************”
myblockchain = []
myblockchain.append(create_genesis_block())
this_nodes_transactions = []
peer_nodes = []
mining = True
@node.route(‘/myblockchain’, methods=[‘POST’])
def transaction():
new_myblockchain = request.get_json()
this_nodes_transactions.append(new_myblockchain)
print “New transaction”
print “Sender: {}”.format(new_myblockchain[‘from’].encode(‘ascii’,’replace’))
print “Receiver: {}”.format(new_myblockchain[‘to’].encode(‘ascii’,’replace’))
print “Amount: {}\n”.format(new_myblockchain[‘amount’])
return “Transaction Successful\n”
@node.route(‘/blocks’, methods=[‘GET’])
def get_blocks():
chain_to_send = myblockchain
for i in range(len(chain_to_send)):
block = chain_to_send[i]
block_idx = str(block.idx)
block_timestamp = str(block.timestamp)
block_data = str(block.data)
block_hash = block.hash
chain_to_send[i] = {
“idx”: block_idx,
“timestamp”: block_timestamp,
“data”: block_data,
“hash”: block_hash
}

Figure 3 depicts the Web based implementation of the blockchain using a Web server so that there is distributed deployment.

$ curl “http://localhost:5000/myblockchain” -d “{\”from\”:\”ss\”,\”to\”:\”fsd\”, \”amount\”:3}” -H “Content-Type:application/json”

Using cURL, the transaction can be implemented and its impact on the blockchain can be visualised. The cURL library for the Windows OS can be installed from https://curl.haxx.se/windows/.

As depicted in Figure 6, the execution of the code and the overall implementation with all the records and transactions can be analysed so that there is transparency in the operations, preventing any hacking attempts. Using Proof of Work (PoW), the integrity of transactions is logged and committed.

Figure 6: Recording all transactions on the server

Scope for research and development

In the current scenario, governments as well as corporate organisations are striving towards implementing blockchain technology for secured applications. For such integrations, there is a need to associate the secured algorithms of Proof of Work (PoW) to ensure the privacy and integrity in the implementations. Research scholars and forensic scientists can make use of blockchain technologies to make accurate predictions about specific identities, for forensic as well as law enforcement scenarios.

LEAVE A REPLY

Please enter your comment!
Please enter your name here