亲自动手学习区块链 Learn Blockchains by Building One

原文链接

https://hackernoon.com/learn-blockchains-by-building-one-117428612f46

本文为节选翻译。

 

你想了解区块链是如何工作的,区块链背后的根本技术是什么?

不过理解区块链并不容易,至少对我来说。在大量的视频,各种教程以及缺乏实例的挫折中我历尽艰辛。

我喜欢通过动手编码来学习。这迫使我在代码级别上来处理这个事情,也就是说粘在一起。如果你也这样做的话,在本指导结束的时候,你会有一个正常运转的区块链,以及深刻理解他们是如何工作的。

 开始之前:

记住,区块链是一个不可更改的,顺序的,由称为块的记录组成的链。可以包括交易,文件,甚至任何数据。 最重要的是他们通过HASHES链接在一起。

如果你要了解hash是什么,可以参考以下链接或自己搜索:

https://learncryptography.com/hash-functions/what-are-hash-functions

本指导面向谁?  你应该掌握基本的Python, 同时也理解HTTP,因为我们将通过HTTP来讲述区块链。

你需要什么?     安装Python 3.6+ (以及PIP) , Flask, Requests library:

pip install Flask==0.12.2 requests==2.18.4 

还需要一个HTTP Client, 譬如 Postman 或 cURL. 

最终代码?       源码链接    https://github.com/dvf/blockchain

 

Step 1: Building a Blockchain 建造一个区块链

打开你的编辑器或 IDE,我个人 ❤️ PyCharm. 创建一个文件,命名如下

blockchain.py

. 我们将使用一个文件。如果中途有麻烦,你可以参考源码  https://github.com/dvf/blockchain

代表一个区块链

我们将创建一个 

Blockchain

 类,它的构造器 constructor 创建一个初始空列表(用来储存区块链),另外一个来存储交易。以下是类的蓝本blueprint

 

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 类是用来管理链的。它将存储交易以及一些助手方式用来添加新块到链中。下面来详细来谈一下。

 块看起来是什么样子?

每个块有索引 (index), 时间戳 (timestamp) , 交易列表(list of transactions),  证据( proof)和前一个块的哈希( hash of the previous Block).

单个块看起来如下:

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

此时,链的概念应该很明显—每一个新块,它自身都保护前一个块的hash. 这至关重要,因为此区块链才具有不可更改性:

如果攻击者链中早期的块,那么此后的所有块都包含了不正确的hash。

这合理吗?如果还不理解,花点时间消化--这是区块链的核心概念。

将交易添加到块  Adding Transactions to a Block

我们需要一种将交易添加到块的方式.  

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()将交易添加到列表后,将返回交易所添加到列表的索引值 --也就是下一个将被挖的索引值。这以后有用,尤其对提交交易的用户。

创建新的块 Creating new Blocks

当Blockchain被实例化的时候我们需要给它种一个创世块(genesis block)—在它前没有其它块.我们还需要对创世块添加证据,以证明创世块是通过挖矿得到的(p.o.W)稍后将进一步讲解挖矿。

除了在构造器创建创世块,我们还将进一步完善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()

 

以上代码很直观。有备注及文档。区块链类几乎完成了。不过此时,你会奇怪新块是如何被创建,制造或挖矿的。

 

理解工作证据   Understanding Proof of Work

工作证据算法Proof of Work algorithm (PoW)是关于如何砸区块链上创建或挖矿新块的 。PoW的目的就是寻找一个解决问题的数字。这个数字必须难以发现但易于验证--对于网络上的任何人,就计算难度而言。这是Proof of Work 背后的核心。

我们看一个非常简单的例子来帮助理解。 

确定x*y的hash以0结束。

hash(x * y) = ac23dc...0

. 对此简单例子,让我们固定x 

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

. 因为得到的hash以0结束:

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

比特币中Bitcoin,工作量证据算法称为Hashcash.它与我们以上的简单例子并没有多大不同。矿工就是用以上算法竞赛去寻找以便能够创建新块。总之,难度取决于要寻找字符串中的字符个数。矿工通过他们的挖掘答案在交易中获取货币得以奖励。  

网络可以很容易验证他们的结果。

实现基本的PoW Implementing basic Proof of Work

为本例的区块链实现一个类似的算法。规则和上面的例子类似:

寻找一个数字 p ,当它和前一个块的答案hash的结果4个0开头
0000
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,将导致发现答案时间的巨大的差异。

我们的区块链类几乎完成了,下面通过http requests 来交互。

Step 2: Our Blockchain as an API 将区块链当做API

我们用 Python Flask Framework. Flask 是一个微框架,很容易将结束点endpoints映射到Python 函数。这样我们可以使用HTTP requests通过web访问区块链。

创建三个方法: 

  • /transactions/new
     用来在块上创建新的交易 
  • /mine
     告诉服务器挖一新块  
  • /chain
     返回整个区块链 

Setting up Flask    设置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:  实例化节点
  • Line 18:  为节点创建随机名字 
  • Line 21: 实例化Blockchain类 class.
  • Line 24–26: 创建/mine endpoint ,是一个GET request  
  • Line 28–30: 创建 /transactions/new endpoint,  POST request,因为我们将给它发送数据。
  • Line 32–38: 创建/mine endpoint , 返回整个区块链
  • Line 40–41:  在5000端口运行服务器。

The Transactions Endpoint  交易结束点

以下是交易请求的数据样式。 它是用户发送给服务器的。 

{
 "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

The Mining Endpoint 挖矿结束点

挖矿端点是有魔力的地方,并且很容易。要做三样事情:

  • Calculate the Proof of Work   计算PoW 
  • Reward the miner (us) by adding a transaction granting us 1 coin  给添加交易的矿工一个币作为奖励
  • Forge the new Block by adding it to the chain 将新块添加到链来制造新块
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

注意,挖矿得到的块的接收者是节点地址。我们在此所做的大部分是与区块链类的方法交互。到此,结束了,可以去区块链交互了。

Step 3: Interacting with our Blockchain 与区块链交互

可以使用老式的cURL或Postman工具通过网络与我们的API交互。

启动服务器:

$ python blockchain.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

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

 

下面通过向 http://localhost:5000/transactions/new 发送POST request 来创建一个新的交易, 其中 body包含以下交易结构: 

{
 "sender": "d4ee26eee15148ee92c6cd394edd974e",
 "recipient": "someone-other-address",
 "amount": 5
}

 

 

如果你没有使用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/mine多发送几次请求,多挖几个区块。然后向 http://localhost:500/chain发送请求,可以查看整个链。

 

Step 4: Consensus 共识

这很棒。我们得到了一个基本的区块链,它接受交易,并且允许我们挖掘新的区块。但是区块链的本意是去中心化。如果是去中心化,我们如何保证他们反映的是同一个链?这就是被称为共识Consensus的问题。如果我们想要网络中有多个节点,我们就需要实现共识算法。

Registering new Nodes 注册新的节点

在我们实现共识算法 Consensus Algorithm前,我们一个让节点知道网上邻居节点的方法。网络上的每个节点应该保证网上其它节点的登记。 因此,我们需要更多的端点endpoints:  

  • /nodes/register
     接受URLs格式的节点列表 
  • /nodes/resolve
     实现共识算法,以解决冲突,确保节点有正确的链。

我们需要修改我们的区块链构造器,提供注册登记节点的方式:

...
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()来容纳节点列表。这是一种简便的方法来确保新添加的节点是一次idempotent,就是无论添加某个节点多市场,它只出现一次。  

Implementing the Consensus Algorithm  实现共识算法

正如所述,冲突是当一个节点与其它节点有不同的链。 要解决冲突,我们需要制定规则,最长的有效链是授权的。也就是说,网上的最长链是事实授权的。使用此算法,网络中的节点达成共识。

...
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()方法负责检查一个链是否有效,通过遍历每一个块,验证hash和proof。

 

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

  

 

在节点2(http://127.0.0.1:5001)挖矿,多挖数次,确保它的链比节点1(http://localhost:5000)的链长。然后在节点1调用

GET  /nodes/resolve, 节点1上的链,通过和网上的其它节点,节点2上的链对比,根据共识算法进行更新,因为节点2的链长。

 

 

 

完工了。。。。。。 邀请几个朋友帮着测试一下你的区块链。 

希望这可以激发你创建新东西。我对加密货币很狂爱,因为我坚信区块链将快速改变我们对于经济,政府和保持记录的看法。I  

Update: part 2 将后续开发。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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