Building a Simple, Local, Python Blockchain – Part 2__Python

來源:互聯網
上載者:User
Introduction – Mining Local Blocks in Python

In this guide, we will implement a local proof-of-work mining algorithm in python to illustrate how blocks are mined on a network like Bitcoin. This is a continuation of the original Building a Simple, Local, Python Blockchain – Part 1.

Note: A few tweaks from the Part 1 code will 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 of our simple blockchain.

If you just want to see the code, it’s hosted here on Github. Setup & Recap from Part 1

I am running the code on macOS Sierra, using Python 3.X.X. We will be 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.

import hashlibimport timeimport csvimport random

We will also use several (modified) functions from the code in part 1. The detailed explanations can be found there.

class Block:    #A basic block contains, index (blockheight), the previous hash, a timestamp, tx information, a nonce, and 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.currentHash = currentHash        self.proof = proofdef getGenesisBlock():    return Block(0, '0', '1496518102.896031', "My very first block :)", 0, '02d779570304667b4c28ba1dbfd4428844a7cab89023205c66858a40937557f8')#We can calculate the hash for a block providing all informationdef calculateHash(index, previousHash, timestamp, data, proof):    value = str(index) + str(previousHash) + str(timestamp) + str(data) + str(proof)    sha = hashlib.sha256(value.encode('utf-8'))    return str(sha.hexdigest())#Makes it simpler to put a block in a function to calculate hashdef calculateHashForBlock(block):    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 = getLatestBlock(blockchain)    nextIndex = int(previousBlock.index) + 1    nextTimestamp = timestamp    nextHash = calculateHash(nextIndex, previousBlock.currentHash, nextTimestamp, proof, blockData)    return Block(nextIndex, previousBlock.currentHash, 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 transactions 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.randrange(0, 1000), random.randrange(0, 100)        transaction = 'User ' + str(txFrom) + " sent " + str(amount) + ' tokens to user ' + str(txTo) + ". "        txData += transaction    return txData

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(blockchain, txData, timestamp, proof)        if newBlockAttempt.currentHash[0:difficulty] == '0'*difficulty:            stopTime = 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(blockchain)

Notice that mineNewBlock takes in a difficultly level and a file path for your blockchain .csv, which both are set to defaults. Difficulty is the number of leading 0’s in the hash you are trying to find. (e.g. a difficulty of 5 would have a hash like 00000b4JA7…). Essentially the mining algorithm starts with an attempt to get this hash with proof = 0. If the concatenation of this proof at the end of the block creates a hash with the desired amount of 0’s, this is appended to the end of the blockchain. A message is printed out and a nonce is returned. Let’s run this function several times using a simple ‘mine’ function:

def mine(blocksToMine = 5):    for _ in range(blocksToMine):        mineNewBlock()

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 that introduces randomly generated transactions, while mining for hashes of a chosen difficulty. Please feel free to post any comments or questions below!

http://blockxchain.org/2017/12/31/simple-local-python-blockchain-pt2/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.