使用python搭建简易区块链

欢迎点击参观我的 ——> 个人学习网站

前言

   了解了区块链一些基本理论后,现在代码实战一个简单的区块链,从代码角度了解它是如何工作的。

    区块链是一些不可改变的、有序的区块,区块的内容可以是文件、交易等等所有你喜欢放进去的数据。事实上,最重要的是将他们连接到一块的 哈希

   这里使用的是 Python3.6 ,需要一个支持 HTTP 的客户端,如 Postnam 或者 cURL , 同时还需要 Flask、Request 库:

sudo pip3 install flask request

    源码参考

Step1:创建区块链

    新建 blockchain.py ,所有的代码都将写进这一个文件中。

描述

    新建 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

区块

   每个块都包括一个索引、一个时间戳、 一系列交易、校验和前一个块的 hash (哈希值)。下面是区块代码示例:

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

    很明显,每一个区块都包含前一个区块的 hash这是区块链不可改变性的关键。如果有人篡改了很早之前的区块,那么这个区块之后的那些块的 hash 都会报错。这便是区块链的核心思想。

添加交易到区块

   定义 new_transaction() 方法来负责向区块中添加交易。

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

   该方法将交易添加到列表中,并返回交易将会被加入的那个区块索引,这个区块将会由”挖矿“生成。

创建新区块

   当 Blockchain 被实例化后,我们需要将 创世区块 (第一个区块,没有前驱)添加到列表中。同时还需要向创世区块中添加一个”证明“,这个证明可以理解为挖矿(或者工作量证明)。我们将在后面讨论挖矿。除了在构造函数中生成创世区块,还需要添加 new_block()new_transaction()hash() 三个方法:

import hashlib
import json
from time import time

class Blockchain(object):
    def __init__(self):
        self.chain = []
        self.current_transactions = []

        # 创建创世区块
        self.new_block(previous_hash=1, proof=100)

    def new_block(self, proof, previous_hash=None):
        """
        创建一个新的区块到区块链中
        :param proof: <int> 由工作证明算法生成的证明
        :param previous_hash: (Optional) <str> 前一个区块的 hash 值
        :return: <dict> 新区块
        """

        block = {
            'index': len(self.chain) + 1,
            'tinestamp': time(),
            'transactions': self.current_transactions,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.chain[-1]),
        }

        # 重置当前交易信息
        self.current_transactions = []

        self.chain.append(block)
        return block

    def new_transactions(self, sender, recipient, amount):
        """
        创建一笔新的交易到下一个被挖掘的区块中
        :param sender: <str> 发送人的地址
        :param recipient: <str> 接收人的地址
        :param amount: <int> 金额
        :return: <int> 持有本次交易的区块索引
        """

        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):
        """
        给一个区块生成 SHA-256 值
        :param block: <dict> Block
        :return: <str>
        """

        # 我们必须确保这个字典(区块)是经过排序的,否则我们将会得到不一致的散列
        block_string = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()

   到现在,我们基本上已经完成了区块链基本结构。但是你也许会疑惑新的区块是怎样创建和挖掘的。

工作量证明算法(PoW)

   在区块链上创建或者挖掘新的区块使用 PoW 算法。该算法的目标是计算出一个符合特定特定条件的数字,这个数字必须很难计算出来但是却很容易验证的。这个就是 PoW 的核心思想。

   举个例子,用以0结尾的 hash 表示整数 x 乘以整数 y 的积,即 hash(x * y) = ac23dc...0 ,设 x = 5y ?用Python实现:

from hashlib import sha256

x = 5
y = 0 # 现在我们还不知道y的值

while sha256(f'{x*y}'.encode()).hexdigest()[-1] != "0":
    y += 1

print(f'The sloution is y = {y}')

    结果是 y = 21 ,因为生成的 hash 以0结尾:

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

   在比特币中, PoW 算法又被称为 Hashcash 。和上面的例子相似,PoW 是“矿工”们争相抢夺谁先创建区块问题的算法。通常计算难度取决于目标字符串的长度。计算出来的”矿工“将会得到一定数量的比特币奖励。

工作量证明实现

   现在实现PoW算法,其规则类似上面的例子:找到一个数字p,使得当与前一个区块的hash值进行 hash 操作后,生成4个0开头的哈希值,类似下图:
这里写图片描述

import hashlib
import json

from time inport 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的个数就可以,其实四个0足够了。现在 Blockchain 类基本已经完成,接下来使用 HTTP requests 进行交互。

Step 2:将 Blockchain 作为接口

   我们使用 Python Flask 框架,它是一个轻量级 Web 框架并且很容易将网络请求映射到 Python 函数,这使得我们可以使用HTTP请求通过Web访问我们的区块链。

   首先创建三个方法:

  • /transactions/new :创建一个新交易并添加到区块中
  • /mine :告诉服务器去”挖掘“新的区块
  • /chain :返回整个区块链

配置Flask

    我们的”服务器“将会在整个区块链网络中作为一个节点。

import hashlib
import json
form 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_transacton():
    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', post=5000)

第8行:实例化节点。更多关于 Flask

第9行:为节点创建一个随机名称。

第10行:实例化 Blockchain 类。

第11-13行:创建 /mine 接口,请求方式为 GET。

第14-16行:创建 /transactions/new 接口,请求方式为 POST,我们向它发送数据。

第17-23行:创建 /chain 接口,返回整个区块链。

第25行:服务器运行端口 5000。

交易

    用户发送到服务器的数据是这种形式的:

{
    "serder": "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_transacton():
    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_transactions(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
       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:运行

   可以使用 cURL 或者 Postman 与我们的 API 进行交互。

   启动服务器:

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

   让我们通过请求 http://localhost:5000/mine 进行挖矿:
使用Postman发送GET请求

   通过向 http://localhost:5000/transactions/new 发起 POST 请求来创建一个新的交易:
使用Postman发送POST请求

   换用 cURL 代替 Postman 也是一样的:

$ 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/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
}

Step 4:一致性(共识算法)

   现在已经有了一个基本的区块链,我们可以接受交易,还可以挖掘新的区块。但是整个区块链应该是分布式(去中心化)的。但是,如果是分布式的,我们如何确保所有的区块都在同一条链上呢?这就是 一致性问题

注册新节点

   在实现共识算法之前,我们需要一种可以让一个节点知道它周围节点的方法。网络中的每一个节点都应该保存一份同一网络中其他节点的记录,所以,我们需要几个接口:

  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() :通过遍历每一个区块并验证 hash 和 PoW 来检查链是否有效。

   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

Registering a new Node

   在第二个节点挖掘一些新的区块来保证链足够长。然后在第一个节点上调用 GET /nodes/resolve ,链中节点都遵从共识算法:

Consensus Algorithm at Work


更新

   接下来在 Part 2 我们将实现 交易验证机制 ,并讨论一下将区块链实际应用的问题。

参考

原文地址:https://hackernoon.com/learn-blockchains-by-building-one-117428612f46

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值