introduction–mining local Blocks in Python
In this guide, we'll implement a local proof-of-work mining algorithm into Python to illustrate how blocks are Network like Bitcoin. This is a continuation to the original building a simple, local, Python Blockchain–part 1.
Note:a few tweaks from the "Part 1 code would be necessary to implement" the local mining functionality we desire. We won ' t be as concerned with testing the validity of the blockchain, in order to focus on the new features Blockchain.
If you just want to the code, it's hosted here in Github. Setup & Recap from Part 1
I am running the code on MacOS Sierra, using Python 3.x.x. We are using 4 modules for this tutorial. Hashlib installation is covered in Part 1. Time, CSV, and random are all native to Python, which require no additional installation.
We'll also use several (modified) functions from the "code in" Part 1. The detailed explanations can be found there.
Class Block: #A basic blocks contains, index (blockheight), the previous hash, a timestamp, TX information, a nonce, an D The current hash def __init__ (self, index, Previoushash, timestamp, data, proof, Currenthash): Self.index = Index Self.previoushash = Previoushash Self.timestamp = Timestamp Self.data = Data self.cu Rrenthash = Currenthash Self.proof = Proof def getgenesisblock (): return block (0, ' 0 ', ' 1496518102.896031 ', " My very:) ", 0, ' 02d779570304667b4c28ba1dbfd4428844a7cab89023205c66858a40937557f8 ') #We can calculate the has H for a blocks providing all information def calculatehash (index, Previoushash, timestamp, data, proof): value = str (in DEX) + str (previoushash) + str (timestamp) + str (data) + str (proof) sha = hashlib.sha256 (Value.encode (' Utf-8 ')) ret Urn Str (sha.hexdigest ()) #Makes it simpler to put a blocks in a function to calculate hash def calculatehashforblock ): Return CalculatehAsh (Block.index, Block.previoushash, Block.timestamp, Block.data, Block.proof) def getlatestblock (blockchain): return Blockchain[len (Blockchain)-1] def generatenextblock (blockchain, blockdata, timestamp, proof): Previousblock = Getlat Estblock (blockchain) nextindex = Int (previousblock.index) + 1 Nexttimestamp = Timestamp Nexthash = Calculateha SH (nextindex, Previousblock.currenthash, Nexttimestamp, proof, Blockdata) return blocks (Nextindex, Previousblock.curre Nthash, Nexttimestamp, Blockdata, proof, Nexthash)
Basic Proof of Work implementation
Our mining function leverages a simple generator that creates 5 mock transactions–mimicking the process of taking Transa Ctions from a mempool. These randomly generated transactions act as the Blockdata. We Call this function Gettxdata:
Def gettxdata ():
txdata = '
for _ in range (5):
txto, txfrom, amount = Random.randrange (0, 1000), Random.randr Ange (0, 1000), Random.randrange (0, MB)
transaction = ' User ' + str (txfrom) + "sent" + str (amount) + ' tokens to use R ' + str (txto) + "."
TxData + + transaction return
This simply creates a long string of 5 transactions with the format: "User <random number> sent <random number > Tokens to User <random Number>:. "All concatenated Together. our function Minenewblock calls this Gettxdata function and assigns the string to the variable TxData:
def Minenewblock (difficulty = 5, Blockchainpath = ' blockchain.csv '): Blockchain = Readblockchain (BlockchainPath)
TxData = Gettxdata () timestamp = Time.time () proof = 0 Newblockfound = False print (' Mining a block ... ') While not newblockfound: #print ("trying new block proof ...") Newblockattempt = Generatenextblock (blo Ckchain, TxData, timestamp, proof) if newblockattempt.currenthash[0:difficulty] = = ' 0 ' *difficulty:sto Ptime = Time.time () timer = stoptime-timestamp Print (' New block found with proof ', proof, ' in ',
Round (timer, 2), ' seconds. ') Newblockfound = True Else:proof = 1 blockchain.append (newblockattempt) writeblockchain (block Chain)
Notice that Minenewblock takes in a difficultly level and a file path for your blockchain. csv, which both are set to DEFA Ults. Difficulty is the number of leading 0 ' s in the hash of your are trying to find. (e.g. a difficulty of 5 would have a hash like 00000b4ja7 ...). Essentially the mining algorithm starts with a attempt to get this hash with proof = 0. If the concatenation of this proof in the "end of" the creates a hash with the desired amount of 0 ", this is appended To the "end of the" blockchain. A printed out and a nonce is returned. Let's run this function several the times using a simple ' mine ' function:
Def mine (blockstomine = 5): For
_ in range (blockstomine):
We run this function and get the following output:
With the. csv blockchain here:Blockchain.csv. Conclusion
There you have it! A simple, local, functioning blockchain this introduces randomly generated transactions, while mining for hashes of a chos En difficulty. Please feel free to post any comments or questions below!