【区块链新手快速入门】如何构建一个区块链

本文翻译自《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:5000

http://localhost:5001

 

(注册新节点)

 

然后我在节点2上挖出一些新的区块,以确保链更长。之后,我在节点1上调用GET /nodes/resolve,其中链被共识算法替代。

 

(共识算法在工作中)

 

到这里,一个完整的公有区块链差不多就成型了,你可以找一些你的朋友帮你测试一下。

 

万向区块链从2015年开始涉足区块链,如果你对区块链感兴趣,欢迎加入我们!

原创文章 29 获赞 2 访问量 8005

猜你喜欢

转载自blog.csdn.net/WXblockchain1/article/details/105365054