区块链大学区块链研习社

通过构建区块链来学习区块链-3-Consensus共识

2019-09-15  本文已影响0人  空乱木

原文链接:https://medium.com/@vanflymen/learn-blockchains-by-building-one-117428612f46

步骤4:共识

这很酷。我们有一个基本的区块链,它接受事务并允许我们挖掘新的块。但区块链的全部意义在于它们应该去中心化。如果它们是去中心化的,我们究竟如何确保它们都反映了同一条链呢?这被称为共识问题,如果我们想要网络中有多个节点,就必须实现一个共识算法。

注册新节点

在实现共识算法之前,我们需要一种方法让节点知道网络上的邻近节点。我们网络上的每个节点都应该保存网络上其他节点的注册表。因此,我们需要更多的端点:

我们需要修改我们的区块链的构造函数,并提供一个注册节点的方法:

…
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()来保存节点列表。这是确保新节点的添加是idempott的一种廉价方法,这意味着无论我们添加特定节点多少次,它都只出现一次。

实现共识算法

如前所述,冲突是指一个节点与另一个节点具有不同的链。为了解决这个问题,我们将制定规则,即最长有效链是权威的。换句话说,网络上最长的链实际上是一个。使用这种算法,我们可以在网络节点之间达成一致。

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

image.png

然后我在节点2上挖掘了一些新的块,以确保链更长。然后调用节点1上的GET /nodes/resolve,将链替换为共识算法:

image.png

这就结束了…找一些朋友一起来测试你的区块链。

我希望这启发了你去创造一些新的东西。我对加密货币欣喜若狂,因为我相信区块链将迅速改变我们对经济、政府和记录保存的看法。

更新:我计划继续第2部分的内容,在第2部分中,我们将扩展我们的区块链,使其具有事务验证机制,并讨论一些可以生成区块链的方法。

上一篇下一篇

猜你喜欢

热点阅读