本文翻譯自《Learn Blockchains by Building One》,作者@dvf,原文鏈接:https://hackernoon.com/learn-blockchains-by-building-one-117428612f46
去年10月24日,區塊鏈被提升至國家戰略地位,包括傳統大企業、央企等在內的公司紛紛佈局區塊鏈。社會上掀起了一陣學習區塊鏈的熱潮,而區塊鏈人才也成了“搶手貨”。
對於我們這種寫程序的工匠來說,學習區塊鏈最快的方法不外乎自己創建一個區塊鏈。下文,將帶領大家建立一個簡單的區塊鏈,在實踐中學習,既能加深對區塊鏈的理解,又能獲得技能。
區塊鏈是由一個個不可變的、連續的記錄信息的區塊連接在一起的鏈。區塊包含交易信息、文件或任何你想要記錄的數據。最重要的是,各個區塊由“哈希”鏈接在一起。
在開始前,你需要安裝Python3.6+(以及pip)、Flask、Requests library:
pip install Flask==0.12.2 requests==2.18.4
另外,還需要一個HTTP客戶端,Postman或cURL均可。
接下來可以開始了。
Step 1:創建一個區塊鏈
打開文本編輯器或IDE,這裏推薦PyCharm。
創建一個新文件,命名爲blockchain.py。整個過程只會用一個文件,如果你弄丟了,可以在這裏找到源文件:https://github.com/dvf/blockchain
呈現區塊鏈
創建一個 blockchain class,在這個class中,constructor會創建一個原始的空白列表用以存儲區塊鏈,另一個用來存儲交易。以下是class的藍圖:
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 class負責管理鏈,能夠存儲交易,並能輔助添加新塊到鏈上。
區塊是什麼樣的?
每個區塊都有一個index、一個時間戳、一個交易列表、一個證明,以及前一個塊的哈希值。下面是一個示例:
block = {
'index': 1,
'timestamp': 1506057125.900785,
'transactions': [
{
'sender': "8527147fe1f5426f9dd545de4b27ee00",
'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
'amount': 5,
}
],
'proof': 324984774000,
'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}
從這個示例可以看出,“鏈”的思想還是非常明顯的——每個新塊都包含前一個塊的哈希值。這點很關鍵,因爲它使區塊鏈具有了“不可變性”:如果攻擊者損毀了鏈上的早期塊,則所有後續塊都將包含不正確的哈希值。
往塊中添加交易
使用new_transaction():
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()將一個交易添加到列表中後,它將返回下一個將被挖出的塊的index。這對提交交易的用戶很有用。
創建新塊
當Blockchain被具現化後,我們就需要創建“創世區塊”了。首先需要在創世區塊鏈中添加一個證明(proof),這個證明就是挖礦的結果(工作量證明)。關於挖礦,我們稍後再說。
除了在constructor裏添加創世區塊,還需要填充new_block()、new_transaction()、hash():
import hashlib
import json
from time import time
class Blockchain(object):
def __init__(self):
self.current_transactions = []
self.chain = []
# Create the genesis block
self.new_block(previous_hash=1, proof=100)
def new_block(self, proof, previous_hash=None):
"""
Create a new Block in the Blockchain
:param proof: <int> The proof given by the Proof of Work algorithm
:param previous_hash: (Optional) <str> Hash of previous Block
:return: <dict> New Block
"""
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.chain[-1]),
}
# Reset the current list of transactions
self.current_transactions = []
self.chain.append(block)
return block
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
@property
def last_block(self):
return self.chain[-1]
@staticmethod
def hash(block):
"""
Creates a SHA-256 hash of a Block
:param block: <dict> Block
:return: <str>
"""
# We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
上面的示例應該很清晰了,爲了幫助大家理解,我也添加了一些註釋和docstrings。我們已經幾乎完成了區塊鏈的展示。接下來,我們來看看一個新塊是怎麼被挖出來的。
工作量證明(Proof of Work)
工作量證明算法就是區塊如何被創建或者如何被挖出的方法。工作量證明的目標是發現一個解決謎題的“數字”,這個數字很難找到但是很容易被網絡中的人通過計算來驗證。
來看一個非常簡單的例子,進一步理解這個問題。
首先定義:某個整數X乘以Y的哈希值必須以0結尾,所以hash(x*y)=ac23dc……0,其中X=5。在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,因爲生成的哈希以0結尾:
hash(5 * 21) = 1253e9373e...5e3600155e860
在比特幣區塊鏈中,工作量證明算法被稱爲Hashcash,和上面的例子沒有太大區別。這是礦工們爲了創建一個新的區塊而競相求解的算法,難度取決於在字符串中搜索的字符數。然後,成功挖出塊的礦工將會收到比特幣作爲獎勵。
網絡能夠很容易地驗證他們的解決方案。
部署基本工作量證明
接下來,爲我們的區塊鏈部署一個類似的算法,規則和上面的示例類似。
當我們用前一個塊的哈希值4進行哈希運算時,找到一個數字P,輸出“0s”:
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就足夠了,你會發現加上一個前導零會使找到解決方案所需的時間產生巨大的差異。
到這裏,class差不多完成了,接下來準備開始使用HTTP請求與它交互。
Step 2:Blockchain作爲一個API
使用Python Flask Framework,創建三個路徑:
/transactions/new添加新的交易到塊中
/mine告訴服務器挖出一個新塊
/chain返回整個區塊鏈
設置Flask
我們的服務器在區塊鏈網絡中就是一個節點,接下來創建一些樣板代碼:
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)
對上面添加的內容做個簡單解釋:
Line15:具現化節點
Line18:爲節點創建一個隨機的名字
Line21:具現化Blockchain class
Line24-26:創建/mine端點,這是一個GET請求。
Line28-30:創建/transactions/new端點,這是一個POST請求,因爲我們要向它發送數據。
Line32-38:創建/chain端點,返回整個區塊鏈。
Line40-41:在端口5000上運行服務器。
交易端點
這是交易請求的示例。下面是用戶發送給服務器的內容:
{
"sender": "my address",
"recipient": "someone else's address",
"amount": 5
}
有了添加交易到塊的class路徑後,剩下的就很簡單了。編寫添加交易的函數:
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
挖礦端點
挖礦端點是展現奇蹟的地方,主要做三件事:
計算工作量證明
獎勵添加塊成功的曠工一個幣
把新的塊添加到鏈上
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 class裏的路徑進行交互,現在可以和blockchain進行交互了。
Step3:和Blockchain進行交互
你可以使用普通的cURL或Postman通過網絡與API交互。
啓動服務器:
$ python blockchain.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
讓我們嘗試通過GET請求到 http://localhost:5000/mine: 挖一個區塊。
(用Postman創建GET請求)
通過POST請求到http://localhost:5000/transactions/new創建一筆交易。
(用Postman創建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
}
Step4:共識
現在,我們已經有了一個最基本的區塊鏈,能夠實現接收交易、挖出區塊。但區塊鏈最核心的點時“去中心化”。另外,如果它們是去中心化的,又該如何確保它們映射的是整條鏈呢?這就涉及到共識問題。如果我們想要做到去中心化,就要確保網絡中有多個節點,有了多個節點,就需要有共識算法。
註冊新節點
在部署共識算法之前,我們需要找到一個方法讓節點知道網絡上的相鄰節點。網絡上的每個節點都應該保存其它節點的註冊表。因此,我們需要更多的端點:
/nodes/register接收URL形式的新節點列表
/nodes/resolve部署共識算法,解決衝突,確保所有節點都在正確的鏈上。
我們需要修改區塊鏈的constructor,並提供註冊節點的方法:
...
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()來保存節點列表。這可以確保新節點的添加是冪等的,也就是同一個節點無論添加多少次,都只出現一次。
部署共識算法
節點衝突是指一個節點與另一個節點產生分歧,有了不同的鏈。爲了解決這個問題,我們制定一個規則,即最長的鏈是正確的鏈。使用這個算法,網絡中的節點之間達成共識。
...
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中,一個用於添加相鄰節點,另一個用於解決衝突:
@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:5001
(註冊新節點)
然後我在節點2上挖出一些新的區塊,以確保鏈更長。之後,我在節點1上調用GET /nodes/resolve,其中鏈被共識算法替代。
(共識算法在工作中)
到這裏,一個完整的公有區塊鏈差不多就成型了,你可以找一些你的朋友幫你測試一下。
萬向區塊鏈從2015年開始涉足區塊鏈,如果你對區塊鏈感興趣,歡迎加入我們!