
如果你看到這篇文章,那么你一定也為數(shù)字加密貨幣的崛起而感到激動(dòng)。與此同時(shí)你也想了解其工作原理——區(qū)塊鏈。
但是理解區(qū)塊鏈并不容易——至少我這么覺(jué)得。我看了許多晦澀的視頻,學(xué)了很多漏洞百出的教程,并且嘗試試了些例子,效果不容樂(lè)觀。
我樂(lè)于通過(guò)實(shí)踐來(lái)學(xué)習(xí)知識(shí),這使我一定要深入代碼來(lái)解決這個(gè)問(wèn)題,那才是最棘手的問(wèn)題。如果你和我一樣,那么讀完這篇文章,你便可以在認(rèn)識(shí)到原理的基礎(chǔ)上,實(shí)現(xiàn)一個(gè)區(qū)塊鏈。
準(zhǔn)備工作…
要知道,區(qū)塊鏈?zhǔn)?strong>不可變的,有序的記錄的鏈,記錄也稱為區(qū)塊。它可以包含交易、文件或任何你想要的數(shù)據(jù)。其中,最重要的是它們是由hash值鏈在一起的。
如果你對(duì)hash有疑問(wèn),可參考此文章。
本文目標(biāo)讀者是誰(shuí)?你應(yīng)該能熟練地讀寫(xiě)Python代碼,并且對(duì)HTTP請(qǐng)求有一定理解,因?yàn)槲覀儗?shí)現(xiàn)區(qū)塊鏈需要以HTTP請(qǐng)求為基礎(chǔ)。
還需做什么?確保安裝了Python 3.6+環(huán)境(包括pip)。還需安裝Flask及Requests庫(kù):
pip install Flask==0.12.2 requests==2.18.4
對(duì)了,你還得準(zhǔn)備個(gè)HTTP客戶端,比如 Postman 或 cURL。
完整代碼在哪?源代碼在這。
第一步:創(chuàng)建Blockchain類
打開(kāi)你最愛(ài)的編輯器或IDE,個(gè)人而言我喜歡PyCharm.新建一個(gè)文件,命名為blockchain.py。
表示出一個(gè)區(qū)塊鏈
我們將創(chuàng)建一個(gè)Blockchain類,它的構(gòu)造函數(shù)包括兩個(gè)空的list(分別用來(lái)存儲(chǔ)區(qū)塊鏈和交易記錄 )。如下:
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é)管理鏈。將用來(lái)存儲(chǔ)交易記錄和添加新的區(qū)塊到區(qū)塊鏈。接下來(lái)讓我們來(lái)實(shí)現(xiàn)這些方法。
區(qū)塊是什么樣的?
每個(gè)區(qū)塊都包含索引,時(shí)間戳(Unix),交易記錄列表,憑證(后續(xù)解釋),和前一個(gè)區(qū)塊的hash值。
這是一個(gè)區(qū)塊的樣例:
block = {
'index': 1,
'timestamp': 1506057125.900785,
'transactions': [
{
'sender': "8527147fe1f5426f9dd545de4b27ee00",
'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
'amount': 5,
}
],
'proof': 324984774000,
'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}
此時(shí),鏈的概念應(yīng)該已經(jīng)很清晰了——每個(gè)新的區(qū)塊包含它自身以及前一個(gè)區(qū)塊的hash值。這是至關(guān)重要的,因?yàn)檫@決定了區(qū)塊鏈的不可變性:如果攻擊者篡改了鏈中的一個(gè)區(qū)塊,那么所有之后的區(qū)塊都會(huì)包含錯(cuò)誤的hash值。
理解了嗎?如果沒(méi)有,花些時(shí)間在上面——那是區(qū)塊鏈的核心概念。
向區(qū)塊中添加交易記錄
我們需要一個(gè)方法來(lái)向區(qū)塊中添加交易記錄。new_transaction()方法就是負(fù)責(zé)這個(gè)的,這很直觀。
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()添加一條交易記錄到list中后,會(huì)返回下一個(gè)區(qū)塊的索引—也就是下一個(gè)要被“挖”的。這在用戶提交交易時(shí)很有用。
創(chuàng)建一個(gè)新區(qū)塊
當(dāng)Blockchain類實(shí)例化時(shí),需要新建一個(gè)初始區(qū)塊——一個(gè)沒(méi)有前序值的區(qū)塊。同時(shí),還要向初始區(qū)塊中加入“憑證”來(lái)證明這是挖礦產(chǎn)生的(或工作量的憑證)。之后我們將談到更多挖礦的事情。
除了要在構(gòu)造函數(shù)中創(chuàng)建初始區(qū)塊外,還需要實(shí)現(xiàn)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()
以上的代碼相當(dāng)直觀——我添加了注釋和docstrings來(lái)使其條理清晰?,F(xiàn)在,我們差不多已經(jīng)可以表示區(qū)塊鏈了。但是,你一定好奇新的區(qū)塊如何被創(chuàng)建、打造和挖的。
理解工作量證明
新的區(qū)塊通過(guò)工作量證明算法 (PoW)來(lái)創(chuàng)建或挖。PoW 的目的是尋找一個(gè)符合特定條件的數(shù)值。對(duì)于網(wǎng)絡(luò)中的任何一個(gè)人,這個(gè)數(shù)值都是很難計(jì)算得到但易于驗(yàn)證的。這是工作量證明的核心理念。
我們來(lái)通過(guò)一個(gè)很簡(jiǎn)單的例子來(lái)輔助理解。
規(guī)定某個(gè)整數(shù)x和另一個(gè)整數(shù)y的乘積的hash值必須以0結(jié)尾。那么hash(x * y) = ac23dc...0。就此例而言,設(shè)x=5。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。這樣得到的hash末尾為0。
hash(5 * 21) = 1253e9373e...5e3600155e860
在比特幣中,使用的工作量證明算法是 Hashcash。它和上面的例子區(qū)別不大。礦工為了得到新的區(qū)塊爭(zhēng)相求解結(jié)果??傮w上來(lái)說(shuō),難度取決于目標(biāo)字符串需要滿足的特定字符的數(shù)量。求出結(jié)果就會(huì)在交易中獲得比特幣獎(jiǎng)勵(lì)。
實(shí)現(xiàn)工作量證明
讓我們來(lái)給區(qū)塊鏈實(shí)現(xiàn)一個(gè)相似的算法吧。規(guī)則與前文類似:
找出數(shù)字p,它和前一個(gè)區(qū)塊的憑證求得的hash開(kāi)頭是四個(gè)0。
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"
我們可以通過(guò)修改開(kāi)頭0的個(gè)數(shù)來(lái)調(diào)整算法的難度。4個(gè)0是合適的。因?yàn)槟銜?huì)發(fā)現(xiàn)哪怕是增加一個(gè)0,計(jì)算結(jié)果的復(fù)雜程度都會(huì)大大地增加。
我們的區(qū)塊鏈基本已經(jīng)實(shí)現(xiàn)完成了,那么我們就開(kāi)始實(shí)現(xiàn)HTTP交互層了。
第二步:實(shí)現(xiàn)Blockchain API
我們將使用Flask框架,這是一個(gè)微型框架并且易于將網(wǎng)絡(luò)節(jié)點(diǎn)映射到Python函數(shù),它使我們可以通過(guò)HTTP請(qǐng)求操作區(qū)塊鏈。
需要?jiǎng)?chuàng)建三種方法:
-
/transactions/new添加交易記錄到一個(gè)區(qū)塊 -
/mine通知服務(wù)器開(kāi)始挖新的區(qū)塊 -
/chain返回完整的區(qū)塊鏈
Flask配置
我們的“服務(wù)器”會(huì)變成區(qū)塊鏈中的一個(gè)節(jié)點(diǎn)。代碼樣板如下:
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)
簡(jiǎn)要說(shuō)明上述代碼:
- Line 15:初始化節(jié)點(diǎn)。了解Flask。
- Line 18:給節(jié)點(diǎn)隨機(jī)命名。
-
Line 21:實(shí)例化
Blockchain類。 -
Line 24–26:創(chuàng)建
/mine接口,GET方法。 -
Line 32–38:創(chuàng)建
/transactions/new接口,POST方法。 - Line 40–41:服務(wù)器運(yùn)行于5000端口。
交易接口
這是用戶發(fā)給服務(wù)器的交易請(qǐng)求的內(nèi)容。
{
"sender": "my address",
"recipient": "someone else's address",
"amount": 5
}
既然我們已經(jīng)有了添加交易至區(qū)塊的方法,剩下的就很簡(jiǎn)單了。讓我們完成添加交易的函數(shù):
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)單的。它必須做下面三件事:
- 計(jì)算工作量證明
- 分發(fā)比特幣獎(jiǎng)勵(lì)
- 將區(qū)塊加入鏈構(gòu)建新區(qū)塊。
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
block = blockchain.new_block(proof)
response = {
'message': "New Block Forged",
'index': block['index'],
'transactions': block['transactions'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
}
return jsonify(response), 200
需要注意的是,挖出的區(qū)塊的接受者是我們自己節(jié)點(diǎn)的地址。我們所做的大部分工作就是和 Blockchain進(jìn)行交互?,F(xiàn)在,代碼基本完成 了,接下來(lái)可以開(kāi)始使用我們的區(qū)塊鏈了。
第三步:與區(qū)塊鏈交互
你可以使用簡(jiǎn)樸古老的cURL或者Postman在局域網(wǎng)內(nèi)來(lái)和我們的API交互。
啟動(dòng)服務(wù)器:
$ python blockchain.py
* Running on [http://127.0.0.1:5000/](http://127.0.0.1:5000/) (Press CTRL+C to quit)
讓我們通過(guò)向http://localhost:5000/mine發(fā)送GET請(qǐng)求來(lái)挖區(qū)塊:

向http://localhost:5000/transactions/new發(fā)送POST請(qǐng)求來(lái)創(chuàng)建新交易,內(nèi)容包含如下交易數(shù)據(jù):

如果你不用Postman,那你可以用等價(jià)的cURL命令:
$ curl -X POST -H "Content-Type: application/json" -d '{
"sender": "d4ee26eee15148ee92c6cd394edd974e",
"recipient": "someone-other-address",
"amount": 5
}' "http://localhost:5000/transactions/new"
重啟服務(wù)器后,初始區(qū)塊加上挖出的兩個(gè)區(qū)塊,總共三個(gè)區(qū)塊。向 http://localhost:5000/chain發(fā)送GET請(qǐng)求獲取所有區(qū)塊:
{
"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
}
第四節(jié):一致性
這很酷。我們已經(jīng)可以交易和挖區(qū)塊鏈了。但是區(qū)塊鏈的核心是去中心化。那么如果去中心化,怎么保證每個(gè)區(qū)塊都在一個(gè)鏈上呢?這就是一致性的問(wèn)題,如果網(wǎng)絡(luò)中不僅僅只有一個(gè)節(jié)點(diǎn)的話,必須實(shí)現(xiàn)一種一致性算法。
注冊(cè)新節(jié)點(diǎn)
在實(shí)現(xiàn)一致性算法前,需要用一種方法來(lái)讓每個(gè)節(jié)點(diǎn)發(fā)現(xiàn)它在網(wǎng)絡(luò)中的相鄰節(jié)點(diǎn)——網(wǎng)絡(luò)中每個(gè)節(jié)點(diǎn)都維護(hù)一個(gè)其他節(jié)點(diǎn)的注冊(cè)信息。這里就需要設(shè)計(jì)更多的接口:
-
/nodes/register接受新節(jié)點(diǎn)的list,形式為URL。 -
/nodes/resolve實(shí)現(xiàn)一致性算法,確保每一個(gè)節(jié)點(diǎn)上的鏈?zhǔn)钦_的。
修改Blockchain類的構(gòu)造函數(shù)并提供一個(gè)注冊(cè)節(jié)點(diǎn)的方法:
...
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)保存節(jié)點(diǎn)list。這是避免重復(fù)添加同一個(gè)節(jié)點(diǎn)最方便的辦法。
實(shí)現(xiàn)一致性算法
上面提到的沖突,其含義是一個(gè)節(jié)點(diǎn)的鏈和其他節(jié)點(diǎn)上的鏈不同。為了解決這個(gè)問(wèn)題,我們制定一個(gè)規(guī)則:網(wǎng)絡(luò)中最長(zhǎng)鏈有效。換句話說(shuō),網(wǎng)絡(luò)中的最長(zhǎng)鏈才是實(shí)際上的鏈。通過(guò)運(yùn)用這個(gè)算法,網(wǎng)絡(luò)中的節(jié)點(diǎn)可以實(shí)現(xiàn)一致性。
...
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
第一個(gè)方法valid_chain()負(fù)責(zé)通過(guò)遍歷每個(gè)鏈并驗(yàn)證hash值和憑證來(lái)檢查鏈?zhǔn)欠裼行А?/p>
resolve_conflicts()方法會(huì)遍歷所有相鄰節(jié)點(diǎn),下載它們的鏈,用上面的方法來(lái)驗(yàn)證。
將這兩個(gè)方法加入到API中,一個(gè)用來(lái)添加相鄰節(jié)點(diǎn),另一個(gè)來(lái)解決沖突。
@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
至此,如果你樂(lè)意,你可以用另一臺(tái)電腦在網(wǎng)絡(luò)中啟動(dòng)不同的節(jié)點(diǎn)。或者用同一臺(tái)電腦的不同端口來(lái)模擬多節(jié)點(diǎn)的場(chǎng)景。我啟動(dòng)了同一臺(tái)電腦上的不同端口來(lái)注冊(cè)新節(jié)點(diǎn)。這樣,就有了兩個(gè)節(jié)點(diǎn)http://localhost:5000 和 http://localhost:5001。

然后我在節(jié)點(diǎn)2上挖出了一些區(qū)塊,保證它是最長(zhǎng)鏈。之后,用GET請(qǐng)求節(jié)點(diǎn)1的 /nodes/resolve接口,發(fā)現(xiàn)節(jié)點(diǎn)1的鏈由于一致性算法被替換了:

好的,大功告成啦!找些朋友來(lái)一起測(cè)試一下你的區(qū)塊鏈吧!
希望本文可以激發(fā)你的創(chuàng)造力。我是個(gè)數(shù)字加密貨幣狂熱愛(ài)好者,因?yàn)槲蚁嘈艆^(qū)塊鏈將快速改變我們對(duì)經(jīng)濟(jì),政府和信息記錄的認(rèn)識(shí)。
更新:我計(jì)劃推出第二部分,拓展我們實(shí)現(xiàn)的區(qū)塊鏈來(lái)包含交易驗(yàn)證機(jī)制并探討區(qū)塊鏈的產(chǎn)品落地。
如果喜歡這個(gè)教程或者有建議或疑問(wèn),歡迎評(píng)論。如果發(fā)現(xiàn)了任何錯(cuò)誤,歡迎在這里貢獻(xiàn)代碼!