這是一篇社區協同翻譯的文章,已完成翻譯,更多信息請點擊 協同翻譯介紹 。
你是否會和我同樣,對加密數字貨幣底層的區塊鏈技術很是感興趣,特別想了解他們的運行機制。node
可是學習區塊鏈技術並不是一路順風,我看多了大量的視頻教程還有各類課程,最終的感受就是真正可用的實戰課程太少。python
我喜歡在實踐中學習,尤爲喜歡一代碼爲基礎去了解整個工做機制。若是你我同樣喜歡這種學習方式,當你學完本教程時,你將會知道區塊鏈技術是如何工做的。git
記住,區塊鏈是一個 不可變的、有序的 被稱爲塊的記錄鏈。它們能夠包含交易、文件或任何您喜歡的數據。但重要的是,他們用哈希 一塊兒被連接在一塊兒。github
若是你不熟悉哈希, 這裏是一個解釋.web
該指南的目的是什麼? 你能夠舒服地閱讀和編寫基礎的Python,由於咱們將經過HTTP與區塊鏈進行討論,因此你也要了解HTTP的工做原理。算法
我須要準備什麼? 肯定安裝了 Python 3.6+ (還有 pip
) ,你還須要安裝 Flask、 Requests 庫:json
`pip install Flask==0.12.2 requests==2.18.4`
複製代碼
對了, 你還須要一個支持HTTP的客戶端, 好比 Postman 或者 cURL,其餘也能夠。
源碼在哪兒? 能夠點擊這裏flask
打開你最喜歡的文本編輯器或者IDE, 我我的比較喜歡 PyCharm. 新建一個名爲blockchain.py
的文件。 咱們將只用這一個文件就能夠。可是若是你仍是不太清楚, 你也能夠參考 源碼.bash
咱們要建立一個 Blockchain
類 ,他的構造函數建立了一個初始化的空列表(要存儲咱們的區塊鏈),而且另外一個存儲交易。下面是咱們這個類的實例:服務器
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
類負責管理鏈式數據,它會存儲交易而且還有添加新的區塊到鏈式數據的Method。讓咱們開始擴充更多Method
每一個塊都有一個 索引
,一個 時間戳(Unix時間戳)
,一個事務列表
, 一個 校驗
(稍後詳述) 和 前一個塊的散列
。
下面是一個Block的例子 :
blockchain.py
block = {
'index': 1,
'timestamp': 1506057125.900785,
'transactions': [
{
'sender': "8527147fe1f5426f9dd545de4b27ee00",
'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
'amount': 5,
}
],
'proof': 324984774000,
'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}
複製代碼
在這一點上,一個 區塊鏈
的概念應該是明顯的 - 每一個新塊都包含在其內的前一個塊的 散列
。 這是相當重要的,由於這是 區塊鏈
不可改變的緣由:若是攻擊者損壞 區塊鏈
中較早的塊,則全部後續塊將包含不正確的哈希值。
這有道理嗎? 若是你尚未想通,花點時間仔細思考一下 - 這是區塊鏈背後的核心理念。
咱們將須要一個添加交易到區塊的方式。咱們的 new_transaction()
方法的責任就是這個, 而且它很是的簡單:
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()
方法添加了交易到列表,它返回了交易將被添加到的區塊的索引---講開採下一個這對稍後對提交交易的用戶有用。
當咱們的 Blockchain
被實例化後,咱們須要將 創世 區塊(一個沒有前導區塊的區塊)添加進去進去。咱們還須要向咱們的起源塊添加一個 證實,這是挖礦的結果(或工做證實)。 咱們稍後會詳細討論挖礦。
除了在構造函數中建立 創世 區塊外,咱們還會補全 new_block()
、new_transaction()
和 hash()
函數:
blockchain.py
import hashlib
import json
from time import time
class Blockchain(object):
def __init__(self):
self.current_transactions = []
self.chain = []
# 建立創世區塊
self.new_block(previous_hash=1, proof=100)
def new_block(self, proof, previous_hash=None):
""" 建立一個新的區塊到區塊鏈中 :param proof: <int> 由工做證實算法生成的證實 :param previous_hash: (Optional) <str> 前一個區塊的 hash 值 :return: <dict> 新區塊 """
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.chain[-1]),
}
# 重置當前交易記錄
self.current_transactions = []
self.chain.append(block)
return block
def new_transaction(self, sender, recipient, amount):
""" 建立一筆新的交易到下一個被挖掘的區塊中 :param sender: <str> 發送人的地址 :param recipient: <str> 接收人的地址 :param amount: <int> 金額 :return: <int> 持有本次交易的區塊索引 """
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):
""" 給一個區塊生成 SHA-256 值 :param block: <dict> Block :return: <str> """
# 咱們必須確保這個字典(區塊)是通過排序的,不然咱們將會獲得不一致的散列
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
複製代碼
上面的代碼應該是直白的 --- 爲了讓代碼清晰,我添加了一些註釋和文檔說明。 咱們差很少完成了咱們的區塊鏈。 但在這個時候你必定很疑惑新的塊是怎麼被建立、鍛造或挖掘的。
使用工做量證實(PoW)算法,來證實是如何在區塊鏈上建立或挖掘新的區塊。PoW 的目標是計算出一個符合特定條件的數字,這個數字對於全部人而言必須在計算上很是困難,但易於驗證。這是工做證實背後的核心思想。
咱們將看到一個簡單的例子幫助你理解:
假設一個整數 x 乘以另外一個整數 y 的積的 Hash 值必須以 0 結尾,即 hash(x * y) = ac23dc...0。設 x = 5,求 y ?用 Python 實現:
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}')
複製代碼
結果是: y = 21。由於,生成的 Hash 值結尾必須爲 0。
hash(5 * 21) = 1253e9373e...5e3600155e860
複製代碼
在比特幣中,工做量證實算法被稱爲 Hashcash ,它和上面的問題很類似,只不過計算難度很是大。這就是礦工們爲了爭奪建立區塊的權利而爭相計算的問題。 一般,計算難度與目標字符串須要知足的特定字符的數量成正比,礦工算出結果後,就會得到必定數量的比特幣獎勵(經過交易)。
驗證結果,固然很是容易。
實現工做量證實
讓咱們來實現一個類似 PoW 算法。規則相似上面的例子:
找到一個數字 P ,使得它與前一個區塊的 proof 拼接成的字符串的 Hash 值以 4 個零開頭。
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"
複製代碼
衡量算法複雜度的辦法是修改零開頭的個數。使用 4 個來用於演示,你會發現多一個零都會大大增長計算出結果所需的時間。
如今 Blockchain 類基本已經完成了,接下來使用 HTTP requests 來進行交互。
咱們將使用 Python Flask 框架,這是一個輕量 Web 應用框架,它方便將網絡請求映射到 Python 函數,如今咱們來讓 Blockchain 運行在基於 Flask web 上。
咱們將建立三個接口:
/transactions/new
建立一個交易並添加到區塊/mine
告訴服務器去挖掘新的區塊/chain
返回整個區塊鏈咱們的「Flask 服務器」將扮演區塊鏈網絡中的一個節點。咱們先添加一些框架代碼:
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
app = Flask(__name__)
# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')
# Instantiate the 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)
複製代碼
簡單的說明一下以上代碼:
發送到節點的交易數據結構以下:
{
"sender": "my address",
"recipient": "someone else's address",
"amount": 5
}
複製代碼
由於咱們已經有了添加交易的方法,因此基於接口來添加交易就很簡單了。讓咱們爲添加事務寫函數:
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
複製代碼
挖礦正是神奇所在,它很簡單,作了一下三件事:
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
複製代碼
注意交易的接收者是咱們本身的服務器節點,咱們作的大部分工做都只是圍繞 Blockchain 類方法進行交互。到此,咱們的區塊鏈就算完成了,咱們來實際運行下.
你可使用 cURL 或 Postman 去和 API 進行交互
啓動 Server:
$ python blockchain.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
複製代碼
讓咱們經過請求 http://localhost:5000/mine ( GET )來進行挖礦:
用 Postman 發起一個 GET 請求.
建立一個交易請求,請求 http://localhost:5000/transactions/new (POST),如圖
若是不是使用 Postman,則用一下的 cURL 語句也是同樣的:
$ curl -X POST -H "Content-Type: application/json" -d '{ "sender": "d4ee26eee15148ee92c6cd394edd974e", "recipient": "someone-other-address", "amount": 5 }' "http://localhost:5000/transactions/new"
複製代碼
在挖了兩次礦以後,就有 3 個塊了,經過請求 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
}
複製代碼
咱們已經有了一個基本的區塊鏈能夠接受交易和挖礦。可是區塊鏈系統應該是分佈式的。既然是分佈式的,那麼咱們究竟拿什麼保證全部節點有一樣的鏈呢?這就是一致性問題,咱們要想在網絡上有多個節點,就必須實現一個一致性的算法
在實現一致性算法以前,咱們須要找到一種方式讓一個節點知道它相鄰的節點。每一個節點都須要保存一份包含網絡中其它節點的記錄。所以讓咱們新增幾個接口:
/nodes/register
接收 URL 形式的新節點列表./nodes/resolve
執行一致性算法,解決任何衝突,確保節點擁有正確的鏈.咱們修改下 Blockchain 的 init 函數並提供一個註冊節點方法:
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 來儲存節點,這是一種避免重複添加節點的簡單方法.
就像先前講的那樣,當一個節點與另外一個節點有不一樣的鏈時,就會產生衝突。 爲了解決這個問題,咱們將制定最長的有效鏈條是最權威的規則。換句話說就是:在這個網絡裏最長的鏈就是最權威的。 咱們將使用這個算法,在網絡中的節點之間達成共識。
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("\n-----------\n")
# 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
複製代碼
第一個方法 valid_chain()
負責檢查一個鏈是否有效,方法是遍歷每一個塊並驗證散列和證實。
resolve_conflicts()
是一個遍歷咱們全部鄰居節點的方法,下載它們的鏈並使用上面的方法驗證它們。 若是找到一個長度大於咱們的有效鏈條,咱們就取代咱們的鏈條。
咱們將兩個端點註冊到咱們的API中,一個用於添加相鄰節點,另外一個用於解決衝突:
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
複製代碼
在這一點上,若是你喜歡,你可使用一臺不一樣的機器,並在你的網絡上啓動不一樣的節點。 或者使用同一臺機器上的不一樣端口啓動進程。 我在個人機器上,不一樣的端口上建立了另外一個節點,並將其註冊到當前節點。 所以,我有兩個節點:http://localhost:5000
和 http://localhost:5001
。 註冊一個新節點:
而後我在節點 2 上挖掘了一些新的塊,以確保鏈條更長。 以後,我在節點1上調用 GET /nodes/resolve
,其中鏈由一致性算法取代:
這是一個包,去找一些朋友一塊兒,以幫助測試你的區塊鏈。
我但願本文能激勵你創造更多新東西。我之因此對數字貨幣入迷,是由於我相信區塊鏈會很快改變咱們看待事物的方式,包括經濟、政府、檔案管理等。
更新:我計劃在接下來的第2部分中繼續討論區塊鏈交易驗證機制,並討論一些可讓區塊鏈進行生產的方法。
討論請前往: 使用 Python 一步步搭建本身的區塊鏈