150 likes | 159 Views
How can we create blockchain in python language? To develop Blockchain in Python, you must have hands-on experience in programming. Here is a comprehensive guide for creating blockchain in Python.<br>
E N D
A Comprehensive Guide ToCreate Blockchain InPython Image Source:morioh.com Blockchain is getting staggering popular due to the robust architecturethat makes it highly compatible with data storage. Though, manydevelopers want to know today how they can develop Blockchain inPython. 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 currentmarketplace. Blockchain- Rising DevelopmentTrend When I learned first about blockchain technology, it straight struck me thatI will remember the core of the technology. If you know little aboutthis
technology, you must understand that the reign of this technologywas started with Bitcoin. And now it has become a significant trend due toits unbreakable architecture forsecurity. Before you learn to create Blockchain in Python, You need tounderstand its basic concept and what Blockchain is and how itworks. Source:researchgate.com Blockchain system relies on a unique concept of a growing list ofrecords (that is, blocks) linked together, which is known as theblockchain. Cryptocurrency- Bitcoin was the first successful implementation of this system, and shortly after its rise in popularity, other digital currencieshave 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 blockchainnetwork.
The data stored on the blockchain must have the followingcharacteristics: Immutable, Impenetrable, Continuous (no data loss), andDistributed. 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 blockchainin Python. For simplicity, I will assume that the data stored in the block is transaction data, as cryptocurrencies are currently the predominant blockchain usecase. Building Blockchain InPython To develop Blockchain in Python, you must have hands-on experiencein 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 ActiveStateaccount.
After getting started with ActiveState account pick Python 3.6 andyour operating system, moreover, we would need to add Flask to buildthe REST API, which allows you to expose to the blockchain andtest. If you are not a developer and want to create blockchain, you shouldhire python developers who have expertise in blockchaindevelopment. Building Your FirstBlock To create the first block, we will use a standard JSON format that willstore data in each block. The data for each block appears somethinglike: { "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 makeeach block unique we need to ensure that duplication doesn'toccur:
classBlock: 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 partof creating blockchain inPython. Above I have already mentioned that the data is each block of the blockchain is immutable and makes a chain through cryptographic hashto 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-sizevalue. With Python, you can use any standard cryptographic hash function,for example, SHA-2 functions, SHA-256 andmore.
from hashlib importsha256 importjson classBlock: 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 defcompute_hash(self): block_string = json.dumps(self.dict,sort_keys=True) returnsha256(block_string.encode()).hexdigest() With hashing each block, we ensure that the securitybecomes unbreakable for each block, and it gets impossible to penetrate thedata within the block. Now the creation of single blocks is done through the above code; it is time to chain themtogether.
Chaining The Blocks IntoBlockchain 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 witha 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'sintegrity. 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 createa chain ofblocks. importtime classBlockchain: def init(self): self.unconfirmed_transactions =[] self.chain =[]
self.create_genesis_block() defcreate_genesis_block(self): genesis_block = Block(0, [], time.time(), "0") genesis_block.hash =genesis_block.compute_hash() self.chain.append(genesis_block) @property deflast_block(self): returnself.chain[-1] Blockchain Proof Of WorkSystem The hash we've described so far is getting us part of the way there. As itis, 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 Worksystem.
The Proof of Work system progressively makes it challenging toperform 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 theblocks 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 ablock increases exponentially with the number of initial zero bits, and therefore, by increasing the problem with each new block, we can prevent usersfrom modifying previous blocks, since it is practically impossible to rewrite the following ones. Blocks and catching up withothers. For further implementation, we are adding proof_of_work method inthe blockchainclass: 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() returncomputed_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. Nowwhen 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 asmining. def add_block(self, block, proof): previous_hash =self.last_block.hash if previous_hash !=block.previous_hash: returnFalse if not self.is_valid_proof(block,proof): returnFalse
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) defmine(self): if notself.unconfirmed_transactions: returnFalse 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 = [] returnnew_block.index Till here, we have seen an explanation of fundamentals for creatinga blockchain: Creating a single block Building a blockchain Proof-of-work system Using a miningprocedure Now the time is to use it. For that, we need to create an interface thatcan enable multiple users, or nodes, supply interaction. To do this, wewill
utilize Flask to build a REST-API. What is Flask? It is a lightweightweb application framework developed for Python. In blockchaindevelopment service, Flask is an importantterm. from flask import Flask,request importrequests 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 enablessending queries to show up relevant information ofblockchain.
Now we would have to activate the blockchain application, which canbe • done through commandprompts. • python3Blockchain.py • You need to feed somethinglike: • Running on http://127.0.0.1:5000/ (Press CTRL+C toquit) • Restarting withstat • Debugger isactive! • Debugger PIN:105-118-129 • Then, in another shell, we can send a query with cURL byrunning: curlhttp://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"}]}
FinalText 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 andmake blockchain in python development a bliss foryou. 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’said. Source:https://www.codementor.io/@mariyajames/a-comprehensive-guide-to-create-blockchain-in-python-1cqiyrt3iz