如何用Python创建一个区块链网络

学习区块链最好的办法就是创建一个区块链网络。

本文讲述用Python语言创建一个简单的区块链网络,源代码在这里。

安装Python 3.6+以及Flask和Requests库:

pip install Flask==0.12.2 requests==2.18.4

还需要HTTP客户端,例如Postman或cURL。

第一步:创建区块链

打开Python IDE或编辑器,推荐PyCharm,创建一个新文件 blockchain.py

创建一个 Blockchain 类(class),使用其构造器创建一个初始空列表用于存储区块链,再创建一个空列表存储交易。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

类负责管理区块链。它将存储交易,并使用一些方法向区块链中添加新的区块。

区块详解

每一个区块都包含一个索引、时间戳(Unix格式时间)、交易列表、证明、前一个区块的哈希值。

举例说明:

block = {
    'index': 1,
    'timestamp': 1506057125.900785,
    'transactions': [
        {
            'sender': "8527147fe1f5426f9dd545de4b27ee00",
            'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
            'amount': 5,
        }
    ],
    'proof': 324984774000,
    'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}

这就是区块链的概念,每一个区块都包含之前一个区块的哈希值。这是实现区块链不可篡改的核心:如果攻击者修改之前区块的数据,那么后续所有的区块都将包含错误的哈希值。

向区块中添加交易

需要一种方式来向区块添加交易。方法就是负责实现该目的,而且非常直观:

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

添加交易后,它返回接收添加交易的区块的索引,即下一个被挖矿出来的区块的索引。

创建区块

实例化时,我们需要添加创始区块 – 不包含之前区块信息的第一个区块。我们还需要向创始区块添加一个证明,它就是挖矿或工作量证明(PoW)。

除了在构造器中创建创始区块,我们还需要具体化 及方法。

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的目的是为了找到一个解决问题的数字。该数字必须很难找到,但是又很容易验证 – 网络中的任何人都可以验证。这是PoW背后的核心思想。

举例说明。

假定我们定义整数x 乘以整数y 的哈希值必须要以 0 结尾。因此 。简化期间,我们取。并在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}')

此时计算结果为 。因为此时它们乘积的哈希值是以 结尾。

hash(5 * 21) = 1253e9373e...5e3600155e860

比特币中PoW算法为Hashcash。与我们上面所举例的本质上是一样的。通常,其难度是由字符串中搜索的字符数决定。

部署基本的工作量证明

在我们的区块链中,规则与上面举例的类似:

找到一个数字p,当它与之前区块的哈希再次哈希后的数值前4位都是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"

为了调整该机制的难度,我们可以修改哈希值开头的数字0的个数。但是4个0已经足够难了。再添加一个0将会极大地增加找到解决方案的时间。

第二步:通过HTTP请求与区块链交互

通过使用Python Flask 框架,可以在网络中使用HTTP请求与我们上面创建的区块链进行交互。

创建3个方法:

  •  向区块中创建一个新的交易;
  •  让服务器挖矿一个新的区块;
  •  返回整个区块链。

设置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)

解释如下:

  • Line 15: 实例化节点。更多有关Flask的内容,请移步这里
  • Line 18: 为节点创建一个随机名称;
  • Line 21: 实例化  类;
  • Line 24–26: 创建  端点,它是一个  请求;
  • Line 28–30: 创建  端点,它是  请求,因为需要将数据发给它;
  • Line 32–38: 创建  端点,返回整个区块链;
  • Line 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

创建交易的方法

挖矿端点

挖矿端点要完成3件事情:

  1. 计算工作量证明;
  2. 添加一笔包含1个币的奖励矿工的交易;
  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
    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

注意,挖出来的区块的接收者是我们节点的地址。目前所完成的只是与我们区块链类中的方法进行交互。

第三步:与区块链交互

可以使用可普通的cURL或Postman与API进行交互。

启动服务器:

$ python blockchain.py* Running on http://127.0.0.1:5000/ (按下 CTRL+C 退出)

通过向http://localhost:5000/mine发送 请求尝试挖矿一个区块:

使用Postman进行 GET 请求

通过向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"

我重启服务器,挖了2个区块,一共3个区块。通过请求 检查整个区块链:

{
  "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.  用来以URLs格式接受新的节点列表;
  2.  用来部署共识机制,解决冲突,确保每一个节点都获得正确的链。

接下来需要修改区块链构造器,并添加注册节点的方法:

...
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)
向网络添加相邻节点的方法

注意此处使用了  来保存节点列表。这是一种很低廉却能确保新添加的节点是幂等处理的方法 – 即无论我们对某个特定的节点添加了多少次,它只出现一次。

部署共识机制

当一个节点和其它节点拥有不同链时,就会产生冲突,为了解决这个问题,我们采用了最长有效链的原则。换句话,网络中的最长链就是实际的区块链。使用该机制,网络中的节点就能够达成一致。

...
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

第一个方法  通过遍历每个区块并验证哈希值和证明来确认该区块链是否有效。

 方法遍历所有的相邻节点,下载它们的链,并使用上述的方法进行验证。如果找到了一个有效链,其长度超过了我们的链,我们就用它替代。

将这两个端点注册到我们的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

此时,你可以使用不同的机器,并在网络中添加不同的节点。或者在同一台机器上使用不同的端口来添加启动进程。我在机器上用不同的端口启动了另外一个节点,并使用现在的节点注册。因此有两个节点:  和

注册一个新的节点

然后我在node2上挖了一些新的区块,以确保该链更长。之后,我在节点1上调用  ,节点1上的链已经被共识机制下的新链所替代:

运行中的共识机制

至此,一条区块链就创建完成。