區塊鏈入門

轉自https://zhuanlan.zhihu.com/p/31479937

源碼鏈接 https://github.com/xilibi2003/blockchain/blob/master/blockchain.py 

背景知識……

要知道區塊鏈是不可變的,有序的記錄的鏈,記錄也叫做區塊。區塊可以包含交易,文件或者任何你能想到的數據。不過至關重要的是,它們由哈希值鏈接在一起。

如果你不知道哈希是什麼,先看看 這篇文章

本文的目標讀者是誰? 你應該可以熟練讀寫基本的 Python 代碼,也要基本瞭解 HTTP 請求的工作原理,因爲本文將要實現的區塊鏈依賴 HTTP。

需要什麼環境? Python 版本不低於 3.6,裝有 pip。還需要安裝 Flask 和絕讚的 Requests 庫:

pip install Flask==0.12.2 requests==2.18.4

哦,你還得有個 HTTP 客戶端,比如 Postman 或者 cURL。隨便什麼都可以。

那代碼在哪裏? 源代碼在 這裏

第一步:創建 Blockchain 類

用你喜歡的編輯器或者 IDE,新建 blockchain.py 文件,我個人比較喜歡 PyCharm。本文全文都使用這一個文件,但是如果你搞丟了,可以參考源代碼

表示區塊鏈

創建 Blockchain 類,其構造函數會創建兩個初始爲空的列表,一個存儲區塊鏈,另一個存儲交易信息。類設計如下:

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 類的設計

Blockchain 類負責管理鏈。它用來存儲交易信息,也有一些幫助方法用來將新區塊添加到鏈中。我們接着來實現一些方法。

區塊長什麼樣?

每個區塊都有其索引時間戳(Unix 時間),交易列表證明(稍後解釋),以及前序區塊的哈希值

下面是一個單獨區塊:

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() 在列表中添加新交易之後,會返回該交易被加到的區塊的索引,也就是指向下一個要挖的區塊。稍後會講到這對於之後提交交易的用戶會有用。

創建新區塊

實例化 Blockchain 類之後,需要新建一個創始區塊,它沒有任何前序區塊。此外還要在創始區塊中加入證明,證明來自挖礦(或者工作量證明)。稍後再來討論挖礦這件事。

除了要在構造函數中創建創始區塊,我們還要實現 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()

上面的代碼還是比較直觀的,還有一些註釋和文檔字符串做進一步解釋。這樣就差不多可以表示區塊鏈了。但是到了這一步,你一定好奇新區塊是怎樣被創建,鍛造或者挖出來的。

理解工作量證明

工作量證明算法(PoW)表述了區塊鏈中的新區塊是如何創建或者挖出來的。PoW 的目的是尋找符合特定規則的數字。對網絡中的任何人來說,從計算的角度上看,該數字必須難以尋找,易於驗證。這是工作量證明算法背後的核心思想。

下面給出一個非常簡單的例子來幫助理解。

不妨規定某整數 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。它和上面給出例子非常類似。礦工們爭相求解這個算法以便創建新塊。總體而言,難度大小取決於要在字符串中找到多少特定字符。礦工給出答案的報酬就是在交易中得到比特幣。

而網絡可以輕鬆地驗證答案。

實現基本的工作量證明

接下來爲我們的區塊鏈實現一個類似的算法。規則和上面的例子類似:

尋找數字 p,當它和前一個區塊的證明一起求哈希時,該哈希開頭是四個 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"

要調整算法的難度,直接修改要求的零的個數就行了。不過 4 個零足夠了。你會發現哪怕多一個零都會讓求解難度倍增。

類寫得差不多了,可以用 HTTP 請求與之交互了。

第二步:將 Blockchain 用作 API

本文使用 Python Flask 框架。Flask 是一個微框架,易於將網絡端點映射到 Python 函數。由此可以輕易地藉助 HTTP 請求通過網絡和區塊鏈交互。

這裏需要創建三個方法:

  • /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)

稍微解釋一下:

  • 第 15 行: 初始化節點。更多信息請閱讀 Flask 文檔
  • 第 18 行: 隨機給節點起名。
  • 第 21 行: 初始化 Blockchain 類
  • 第 24–26 行: 創建 /mine 接口,使用 GET 方法。
  • 第 28–30 行: 創建 /transactions/new 接口,使用 POST 方法,因爲要給它發數據。
  • 第 32–38 行: 創建 /chain 接口,它會返回整個區塊鏈。
  • 第 40–41 行: 服務器運行在 5000 端口。

交易端

下面是交易請求的內容,也就是發給服務器的東西:

{
 "sender": "my address",
 "recipient": "someone else's address",
 "amount": 5
}

因爲已經有類方法將交易加到區塊中,剩下的就很簡單了。寫一個添加交易的函數:

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

創建交易的方法

挖礦端

挖礦端是見證奇蹟的地方。非常簡單,只需要做三件事:

  1. 計算工作量證明
  2. 獎勵礦工(這裏就是我們),新增一次交易就賺一個幣
  3. 將區塊加入鏈就可以構建新區塊
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

注意,挖出來區塊的接受方就是節點的地址。這裏做的事情基本上就是和 Blockchain 類的方法打交道。代碼寫到這裏就差不多搞定了,下面可以和區塊鏈進行交互了。

第三步:和 Blockchain 交互

可以用簡潔又古老的 cURL 或者 Postman 來通過網絡用 API 和區塊鏈交互。

啓動服務器:

$ python blockchain.py

* Running on [http://127.0.0.1:5000/](http://127.0.0.1:5000/) (Press CTRL+C to quit)

通過 GET 請求 http://localhost:5000/mine 嘗試挖一塊新區塊。

 

通過 POST 請求 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](http://localhost:5000/transactions/new)"

重啓服務器後,加上新挖出的兩個區塊,現在有了三個區塊。通過請求 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
}

第四步:共識

非常酷對不對?我們已經構建了基本的區塊鏈,不僅支持交易,還可以挖礦。但是區塊鏈的核心是去中心化。但是如果要去中心化,怎麼知道每個區塊都在同一個鏈中呢?這就是共識問題,如果網絡中不只這一個節點,必須實現共識算法。

註冊新節點

在實現共識算法之前:我們需要讓節點知道其所在的網絡存在鄰居節點。網絡中的每一個節點都應該保存網絡中其他節點的信息。所以要寫幾個新接口:

  1. /nodes/register 接受新節點的列表,形式是 URL。
  2. /nodes/resolve 來執行共識算法,解決所有衝突,確保節點的鏈是正確的

下面需要修改 Blockchain 類的構造函數,然後寫一下注冊節點的方法:

...
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:5000 和 http://localhost:5001

我在 2 號節點挖出了新區塊,保證 2 號節點的鏈更長。然後用 GET 調用 1 號節點的 /nodes/resolve,可以發現鏈被通過共識算法替換了:

這樣子就差不多完工了。 叫一些朋友來一起試試你的區塊鏈吧。

我希望這個教程可以激發你創建新東西的熱情。我迷戀數字加密貨幣,因爲我相信區塊鏈技術會快速改變我們思考經濟學,政府以及記錄信息的方式。

更新:我打算接着寫本文的第二部分,繼續拓展本文實現的區塊鏈以涵蓋交易驗證機制並討論如何讓區塊鏈產品化。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章