【相關(guān)學(xué)習(xí)推薦:python教程】
你是否會(huì)和我一樣,對(duì)加密數(shù)字貨幣底層的區(qū)塊鏈技術(shù)非常感興趣,特別想了解他們的運(yùn)行機(jī)制。
但是學(xué)習(xí)區(qū)塊鏈技術(shù)并非一帆風(fēng)順,我看多了大量的視頻教程還有各種課程,最終的感覺(jué)就是真正可用的實(shí)戰(zhàn)課程太少。
我喜歡在實(shí)踐中學(xué)習(xí),尤其喜歡一代碼為基礎(chǔ)去了解整個(gè)工作機(jī)制。如果你我一樣喜歡這種學(xué)習(xí)方式,當(dāng)你學(xué)完本教程時(shí),你將會(huì)知道區(qū)塊鏈技術(shù)是如何工作的。
記住,區(qū)塊鏈?zhǔn)且粋€(gè) 不可變的、有序的 被稱為塊的記錄鏈。它們可以包含交易、文件或任何您喜歡的數(shù)據(jù)。但重要的是,他們用哈希 一起被鏈接在一起。
如果你不熟悉哈希,這里是一個(gè)解釋。
該指南的目的是什么?
你可以舒服地閱讀和編寫基礎(chǔ)的 Python,因?yàn)槲覀儗⑼ㄟ^(guò) HTTP 與區(qū)塊鏈進(jìn)行討論,所以你也要了解 HTTP 的工作原理。
我需要準(zhǔn)備什么?
確定安裝了 Python 3.6 + (還有 pip
) ,你還需要安裝 Flask、 Requests 庫(kù):
pip install Flask==0.12.2 requests==2.18.4
對(duì)了, 你還需要一個(gè)支持HTTP的客戶端, 比如 Postman 或者 cURL,其他也可以。
源碼在哪兒?
可以點(diǎn)擊這里
打開(kāi)你最喜歡的文本編輯器或者IDE, 我個(gè)人比較喜歡 PyCharm. 新建一個(gè)名為blockchain.py
的文件。 我們將只用這一個(gè)文件就可以。但是如果你還是不太清楚, 你也可以參考 源碼.
我們要?jiǎng)?chuàng)建一個(gè) Blockchain
類 ,他的構(gòu)造函數(shù)創(chuàng)建了一個(gè)初始化的空列表(要存儲(chǔ)我們的區(qū)塊鏈),并且另一個(gè)存儲(chǔ)交易。下面是我們這個(gè)類的實(shí)例:
blockchain.py
class Blockchain(object): def __init__(self): self.chain = [] self.current_transactions = [] def new_block(self): # Creates a new Block and adds it to the chain pass def new_transaction(self): # Adds a new transaction to the list of transactions pass @staticmethod def hash(block): # Hashes a Block pass @property def last_block(self): # Returns the last Block in the chain pass
我們的 Blockchain
類負(fù)責(zé)管理鏈?zhǔn)綌?shù)據(jù),它會(huì)存儲(chǔ)交易并且還有添加新的區(qū)塊到鏈?zhǔn)綌?shù)據(jù)的Method。讓我們開(kāi)始擴(kuò)充更多Method。
每個(gè)塊都有一個(gè) 索引
,一個(gè) 時(shí)間戳(Unix時(shí)間戳)
,一個(gè)事務(wù)列表
, 一個(gè) 校驗(yàn)
(稍后詳述) 和 前一個(gè)塊的散列
。
下面是一個(gè)Block的例子 :
blockchain.py
block = { 'index': 1, 'timestamp': 1506057125.900785, 'transactions': [ { 'sender': "8527147fe1f5426f9dd545de4b27ee00", 'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f", 'amount': 5, } ], 'proof': 324984774000, 'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" }
在這一點(diǎn)上,一個(gè) 區(qū)塊鏈
的概念應(yīng)該是明顯的 - 每個(gè)新塊都包含在其內(nèi)的前一個(gè)塊的 散列
。 這是至關(guān)重要的,因?yàn)檫@是 區(qū)塊鏈
不可改變的原因:如果攻擊者損壞 區(qū)塊鏈
中較早的塊,則所有后續(xù)塊將包含不正確的哈希值。
這有道理嗎? 如果你還沒(méi)有想通,花點(diǎn)時(shí)間仔細(xì)思考一下 - 這是區(qū)塊鏈背后的核心理念。
我們將需要一個(gè)添加交易到區(qū)塊的方式。我們的 new_transaction()
方法的責(zé)任就是這個(gè), 并且它非常的簡(jiǎn)單:
blockchain.py
class Blockchain(object): ... def new_transaction(self, sender, recipient, amount): """ Creates a new transaction to go into the next mined Block :param sender: <str> Address of the Sender :param recipient: <str> Address of the Recipient :param amount: <int> Amount :return: <int> The index of the Block that will hold this transaction """ self.current_transactions.append({ 'sender': sender, 'recipient': recipient, 'amount': amount, }) return self.last_block['index'] + 1
new_transaction()
方法添加了交易到列表,它返回了交易將被添加到的區(qū)塊的索引---講開(kāi)采下一個(gè)這對(duì)稍后對(duì)提交交易的用戶有用。
當(dāng)我們的 Blockchain
被實(shí)例化后,我們需要將 創(chuàng)世 區(qū)塊(一個(gè)沒(méi)有前導(dǎo)區(qū)塊的區(qū)塊)添加進(jìn)去進(jìn)去。我們還需要向我們的起源塊添加一個(gè) 證明,這是挖礦的結(jié)果(或工作證明)。 我們稍后會(huì)詳細(xì)討論挖礦。
除了在構(gòu)造函數(shù)中創(chuàng)建 創(chuàng)世 區(qū)塊外,我們還會(huì)補(bǔ)全 new_block()
、 new_transaction()
和 hash()
函數(shù):
blockchain.py
import hashlib import json from time import time class Blockchain(object): def __init__(self): self.current_transactions = [] self.chain = [] # 創(chuàng)建創(chuàng)世區(qū)塊 self.new_block(previous_hash=1, proof=100) def new_block(self, proof, previous_hash=None): """ 創(chuàng)建一個(gè)新的區(qū)塊到區(qū)塊鏈中 :param proof: <int> 由工作證明算法生成的證明 :param previous_hash: (Optional) <str> 前一個(gè)區(qū)塊的 hash 值 :return: <dict> 新區(qū)塊 """ block = { 'index': len(self.chain) + 1, 'timestamp': time(), 'transactions': self.current_transactions, 'proof': proof, 'previous_hash': previous_hash or self.hash(self.chain[-1]), } # 重置當(dāng)前交易記錄 self.current_transactions = [] self.chain.append(block) return block def new_transaction(self, sender, recipient, amount): """ 創(chuàng)建一筆新的交易到下一個(gè)被挖掘的區(qū)塊中 :param sender: <str> 發(fā)送人的地址 :param recipient: <str> 接收人的地址 :param amount: <int> 金額 :return: <int> 持有本次交易的區(qū)塊索引 """ self.current_transactions.append({ 'sender': sender, 'recipient': recipient, 'amount': amount, }) return self.last_block['index'] + 1 @property def last_block(self): return self.chain[-1] @staticmethod def hash(block): """ 給一個(gè)區(qū)塊生成 SHA-256 值 :param block: <dict> Block :return: <str> """ # 我們必須確保這個(gè)字典(區(qū)塊)是經(jīng)過(guò)排序的,否則我們將會(huì)得到不一致的散列 block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string).hexdigest()
上面的代碼應(yīng)該是直白的 --- 為了讓代碼清晰,我添加了一些注釋和文檔說(shuō)明。 我們差不多完成了我們的區(qū)塊鏈。 但在這個(gè)時(shí)候你一定很疑惑新的塊是怎么被創(chuàng)建、鍛造或挖掘的。
使用工作量證明(PoW)算法,來(lái)證明是如何在區(qū)塊鏈上創(chuàng)建或挖掘新的區(qū)塊。PoW 的目標(biāo)是計(jì)算出一個(gè)符合特定條件的數(shù)字,這個(gè)數(shù)字對(duì)于所有人而言必須在計(jì)算上非常困難,但易于驗(yàn)證。這是工作證明背后的核心思想。
我們將看到一個(gè)簡(jiǎn)單的例子幫助你理解:
假設(shè)一個(gè)整數(shù) x
乘以另一個(gè)整數(shù) y
的積的 Hash 值必須以 0 結(jié)尾,即 hash(x * y) = ac23dc...0
。設(shè) x = 5
,求y
。
用 Python 實(shí)現(xiàn):
from hashlib import sha256 x = 5 y = 0 # We don't know what y should be yet... while sha256(f'{x*y}'.encode()).hexdigest()[-1] != "0": y += 1 print(f'The solution is y = {y}')
結(jié)果是:y = 21
。因?yàn)椋傻?Hash 值結(jié)尾必須為 0
。
hash(5 * 21) = 1253e9373e...5e3600155e860
在比特幣中,工作量證明算法被稱為 Hashcash ,它和上面的問(wèn)題很相似,只不過(guò)計(jì)算難度非常大。這就是礦工們?yōu)榱藸?zhēng)奪創(chuàng)建區(qū)塊的權(quán)利而爭(zhēng)相計(jì)算的問(wèn)題。 通常,計(jì)算難度與目標(biāo)字符串需要滿足的特定字符的數(shù)量成正比,礦工算出結(jié)果后,就會(huì)獲得一定數(shù)量的比特幣獎(jiǎng)勵(lì)(通過(guò)交易)。
驗(yàn)證結(jié)果,當(dāng)然非常容易。
實(shí)現(xiàn)工作量證明
讓我們來(lái)實(shí)現(xiàn)一個(gè)相似 PoW 算法。規(guī)則類似上面的例子:
找到一個(gè)數(shù)字 P ,使得它與前一個(gè)區(qū)塊的 Proof 拼接成的字符串的 Hash 值以 4 個(gè)零開(kāi)頭。
blockchain.py
import hashlib import json from time import time from uuid import uuid4 class Blockchain(object): ... def proof_of_work(self, last_proof): """ Simple Proof of Work Algorithm: - Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p' - p is the previous proof, and p' is the new proof :param last_proof: <int> :return: <int> """ proof = 0 while self.valid_proof(last_proof, proof) is False: proof += 1 return proof @staticmethod def valid_proof(last_proof, proof): """ Validates the Proof: Does hash(last_proof, proof) contain 4 leading zeroes? :param last_proof: <int> Previous Proof :param proof: <int> Current Proof :return: <bool> True if correct, False if not. """ guess = f'{last_proof}{proof}'.encode() guess_hash = hashlib.sha256(guess).hexdigest() return guess_hash[:4] == "0000"
衡量算法復(fù)雜度的辦法是修改零開(kāi)頭的個(gè)數(shù)。使用 4 個(gè)來(lái)用于演示,你會(huì)發(fā)現(xiàn)多一個(gè)零都會(huì)大大增加計(jì)算出結(jié)果所需的時(shí)間。
現(xiàn)在 Blockchain 類基本已經(jīng)完成了,接下來(lái)使用 HTTP Requests 來(lái)進(jìn)行交互。
我們將使用 Python Flask 框架,這是一個(gè)輕量 Web 應(yīng)用框架,它方便將網(wǎng)絡(luò)請(qǐng)求映射到 Python 函數(shù),現(xiàn)在我們來(lái)讓 Blockchain 運(yùn)行在基于 Flask web 上。
我們將創(chuàng)建三個(gè)接口:
/transactions/new
創(chuàng)建一個(gè)交易并添加到區(qū)塊/mine
告訴服務(wù)器去挖掘新的區(qū)塊/chain
返回整個(gè)區(qū)塊鏈我們的 Flask 服務(wù)器 將扮演區(qū)塊鏈網(wǎng)絡(luò)中的一個(gè)節(jié)點(diǎn)。我們先添加一些框架代碼:
blockchain.py
import hashlib import json from textwrap import dedent from time import time from uuid import uuid4 from flask import Flask class Blockchain(object): ... # Instantiate our Node(實(shí)例化我們的節(jié)點(diǎn)) app = Flask(__name__) # Generate a globally unique address for this node(為這個(gè)節(jié)點(diǎn)生成一個(gè)全球唯一的地址) node_identifier = str(uuid4()).replace('-', '') # Instantiate the Blockchain(實(shí)例化 Blockchain類) blockchain = Blockchain() @app.route('/mine', methods=['GET']) def mine(): return "We'll mine a new Block" @app.route('/transactions/new', methods=['POST']) def new_transaction(): return "We'll add a new transaction" @app.route('/chain', methods=['GET']) def full_chain(): response = { 'chain': blockchain.chain, 'length': len(blockchain.chain), } return jsonify(response), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
簡(jiǎn)單的說(shuō)明一下以上代碼:
發(fā)送到節(jié)點(diǎn)的交易數(shù)據(jù)結(jié)構(gòu)如下:
{ "sender": "my address", "recipient": "someone else's address", "amount": 5 }
因?yàn)槲覀円呀?jīng)有了添加交易的方法,所以基于接口來(lái)添加交易就很簡(jiǎn)單了。讓我們?yōu)樘砑邮聞?wù)寫函數(shù):
blockchain.py
import hashlib import json from textwrap import dedent from time import time from uuid import uuid4 from flask import Flask, jsonify, request ... @app.route('/transactions/new', methods=['POST']) def new_transaction(): values = request.get_json() # Check that the required fields are in the POST'ed data required = ['sender', 'recipient', 'amount'] if not all(k in values for k in required): return 'Missing values', 400 # Create a new Transaction index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) response = {'message': f'Transaction will be added to Block {index}'} return jsonify(response), 201
挖礦正是神奇所在,它很簡(jiǎn)單,做了一下三件事:
blockchain.py
import hashlib import json from time import time from uuid import uuid4 from flask import Flask, jsonify, request ... @app.route('/mine', methods=['GET']) def mine(): # We run the proof of work algorithm to get the next proof... last_block = blockchain.last_block last_proof = last_block['proof'] proof = blockchain.proof_of_work(last_proof) # We must receive a reward for finding the proof. # The sender is "0" to signify that this node has mined a new coin. blockchain.new_transaction( sender="0", recipient=node_identifier, amount=1, ) # Forge the new Block by adding it to the chain previous_hash = blockchain.hash(last_block) block = blockchain.new_block(proof, previous_hash) response = { 'message': "New Block Forged", 'index': block['index'], 'transactions': block['transactions'], 'proof': block['proof'], 'previous_hash': block['previous_hash'], } return jsonify(response), 200
注意交易的接收者是我們自己的服務(wù)器節(jié)點(diǎn),我們做的大部分工作都只是圍繞 Blockchain 類方法進(jìn)行交互。到此,我們的區(qū)塊鏈就算完成了,我們來(lái)實(shí)際運(yùn)行下。
你可以使用 cURL 或 Postman 去和 API 進(jìn)行交互
啟動(dòng) Server:
$ python blockchain.py * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
讓我們通過(guò)請(qǐng)求 http://localhost:5000/mine ( GET )來(lái)進(jìn)行挖礦:
用 Postman 發(fā)起一個(gè) GET 請(qǐng)求.
創(chuàng)建一個(gè)交易請(qǐng)求,請(qǐng)求 http://localhost:5000/transactions/new (POST),如圖
如果不是使用 Postman,則用一下的 cURL 語(yǔ)句也是一樣的:
$ curl -X POST -H "Content-Type: application/json" -d '{ "sender": "d4ee26eee15148ee92c6cd394edd974e", "recipient": "someone-other-address", "amount": 5 }' "http://localhost:5000/transactions/new"
在挖了兩次礦之后,就有 3 個(gè)塊了,通過(guò)請(qǐng)求 http://localhost:5000/chain 可以得到所有的塊信息
{ "chain": [ { "index": 1, "previous_hash": 1, "proof": 100, "timestamp": 1506280650.770839, "transactions": [] }, { "index": 2, "previous_hash": "c099bc...bfb7", "proof": 35293, "timestamp": 1506280664.717925, "transactions": [ { "amount": 1, "recipient": "8bbcb347e0634905b0cac7955bae152b", "sender": "0" } ] }, { "index": 3, "previous_hash": "eff91a...10f2", "proof": 35089, "timestamp": 1506280666.1086972, "transactions": [ { "amount": 1, "recipient": "8bbcb347e0634905b0cac7955bae152b", "sender": "0" } ] } ], "length": 3 }
我們已經(jīng)有了一個(gè)基本的區(qū)塊鏈可以接受交易和挖礦。但是區(qū)塊鏈系統(tǒng)應(yīng)該是分布式的。既然是分布式的,那么我們究竟拿什么保證所有節(jié)點(diǎn)有同樣的鏈呢?這就是一致性問(wèn)題,我們要想在網(wǎng)絡(luò)上有多個(gè)節(jié)點(diǎn),就必須實(shí)現(xiàn)一個(gè)一致性的算法。
在實(shí)現(xiàn)一致性算法之前,我們需要找到一種方式讓一個(gè)節(jié)點(diǎn)知道它相鄰的節(jié)點(diǎn)。每個(gè)節(jié)點(diǎn)都需要保存一份包含網(wǎng)絡(luò)中其它節(jié)點(diǎn)的記錄。因此讓我們新增幾個(gè)接口:
/nodes/register
接收 URL 形式的新節(jié)點(diǎn)列表./nodes/resolve
執(zhí)行一致性算法,解決任何沖突,確保節(jié)點(diǎn)擁有正確的鏈.我們修改下 Blockchain 的 init 函數(shù)并提供一個(gè)注冊(cè)節(jié)點(diǎn)方法:
blockchain.py
... from urllib.parse import urlparse ... class Blockchain(object): def __init__(self): ... self.nodes = set() ... def register_node(self, address): """ Add a new node to the list of nodes :param address: <str> Address of node. Eg. 'http://192.168.0.5:5000' :return: None """ parsed_url = urlparse(address) self.nodes.add(parsed_url.netloc)
我們用 set 來(lái)儲(chǔ)存節(jié)點(diǎn),這是一種避免重復(fù)添加節(jié)點(diǎn)的簡(jiǎn)單方法.
就像先前講的那樣,當(dāng)一個(gè)節(jié)點(diǎn)與另一個(gè)節(jié)點(diǎn)有不同的鏈時(shí),就會(huì)產(chǎn)生沖突。 為了解決這個(gè)問(wèn)題,我們將制定最長(zhǎng)的有效鏈條是最權(quán)威的規(guī)則。換句話說(shuō)就是:在這個(gè)網(wǎng)絡(luò)里最長(zhǎng)的鏈就是最權(quán)威的。 我們將使用這個(gè)算法,在網(wǎng)絡(luò)中的節(jié)點(diǎn)之間達(dá)成共識(shí)。
blockchain.py
... import requests class Blockchain(object) ... def valid_chain(self, chain): """ Determine if a given blockchain is valid :param chain: <list> A blockchain :return: <bool> True if valid, False if not """ last_block = chain[0] current_index = 1 while current_index < len(chain): block = chain[current_index] print(f'{last_block}') print(f'{block}') print(" ----------- ") # Check that the hash of the block is correct if block['previous_hash'] != self.hash(last_block): return False # Check that the Proof of Work is correct if not self.valid_proof(last_block['proof'], block['proof']): return False last_block = block current_index += 1 return True def resolve_conflicts(self): """ This is our Consensus Algorithm, it resolves conflicts by replacing our chain with the longest one in the network. :return: <bool> True if our chain was replaced, False if not """ neighbours = self.nodes new_chain = None # We're only looking for chains longer than ours max_length = len(self.chain) # Grab and verify the chains from all the nodes in our network for node in neighbours: response = requests.get(f'http://{node}/chain') if response.status_code == 200: length = response.json()['length'] chain = response.json()['chain'] # Check if the length is longer and the chain is valid if length > max_length and self.valid_chain(chain): max_length = length new_chain = chain # Replace our chain if we discovered a new, valid chain longer than ours if new_chain: self.chain = new_chain return True return False
第一個(gè)方法 valid_chain()
負(fù)責(zé)檢查一個(gè)鏈?zhǔn)欠裼行?,方法是遍歷每個(gè)塊并驗(yàn)證散列和證明。
resolve_conflicts()
是一個(gè)遍歷我們所有鄰居節(jié)點(diǎn)的方法,下載它們的鏈并使用上面的方法驗(yàn)證它們。 如果找到一個(gè)長(zhǎng)度大于我們的有效鏈條,我們就取代我們的鏈條。
我們將兩個(gè)端點(diǎn)注冊(cè)到我們的API中,一個(gè)用于添加相鄰節(jié)點(diǎn),另一個(gè)用于解決沖突:
blockchain.py
@app.route('/nodes/register', methods=['POST']) def register_nodes(): values = request.get_json() nodes = values.get('nodes') if nodes is None: return "Error: Please supply a valid list of nodes", 400 for node in nodes: blockchain.register_node(node) response = { 'message': 'New nodes have been added', 'total_nodes': list(blockchain.nodes), } return jsonify(response), 201 @app.route('/nodes/resolve', methods=['GET']) def consensus(): replaced = blockchain.resolve_conflicts() if replaced: response = { 'message': 'Our chain was replaced', 'new_chain': blockchain.chain } else: response = { 'message': 'Our chain is authoritative', 'chain': blockchain.chain } return jsonify(response), 200
在這一點(diǎn)上,如果你喜歡,你可以使用一臺(tái)不同的機(jī)器,并在你的網(wǎng)絡(luò)上啟動(dòng)不同的節(jié)點(diǎn)。 或者使用同一臺(tái)機(jī)器上的不同端口啟動(dòng)進(jìn)程。 我在我的機(jī)器上,不同的端口上創(chuàng)建了另一個(gè)節(jié)點(diǎn),并將其注冊(cè)到當(dāng)前節(jié)點(diǎn)。 因此,我有兩個(gè)節(jié)點(diǎn):http://localhost:5000
和 http://localhost:5001
。 注冊(cè)一個(gè)新節(jié)點(diǎn):
然后我在節(jié)點(diǎn) 2 上挖掘了一些新的塊,以確保鏈條更長(zhǎng)。 之后,我在節(jié)點(diǎn)1上調(diào)用 GET /nodes/resolve
,其中鏈由一致性算法取代:
這是一個(gè)包,去找一些朋友一起,以幫助測(cè)試你的區(qū)塊鏈。
我希望本文能激勵(lì)你創(chuàng)造更多新東西。我之所以對(duì)數(shù)字貨幣入迷,是因?yàn)槲蚁嘈艆^(qū)塊鏈會(huì)很快改變我們看待事物的方式,包括經(jīng)濟(jì)、政府、檔案管理等。
更新:我計(jì)劃在接下來(lái)的第2部分中繼續(xù)討論區(qū)塊鏈交易驗(yàn)證機(jī)制,并討論一些可以讓區(qū)塊鏈進(jìn)行生產(chǎn)的方法。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com