通过构建一个模块来学习区块链

了解区块链如何工作的最快方式就是构建一个区块链

记住,区块链是一个不可变的、顺序的记录链,称为块。它们可以包含事务、文件或任何您喜欢的数据。但重要的是它们用散列(哈希)链在一起。

如果您不确定什么是哈希,这里有一个解释

先验知识

  • 阅读这篇文章需要了解一些python编程以及HTTPS的基础知识,因为将会通过HTTP与区块链对话。
  • 确保安装了Python 3.6+(以及pip)。同时还需要安装Flask与Requests库。
 pip install Flask==0.12.2 requests==2.18.4 

步骤1:构建区块链。

打开您最喜欢的文本编辑器或IDE,创建一个名为blockchain.py的新文件。文件源代码点击这里。

表示一个区块链

我们将创建一个区块链类,它的构造函数创建一个初始空列表(用于存储区块链),另一个用于存储事务。

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

我们的区块链类负责管理链。它将存储事务,并有一些辅助方法来为链添加新的块。

区块是什么样子的

每个块都有一个索引(index)、一个时间戳(timestamp)(在Unix时间内)、一个事务列表(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"
}

在这一点上,链的概念应该是显式的——每个新的块都包含在其自身内,即前面块的哈希。这是至关重要的,因为它使区块链不会受到下面影响:如果攻击者破坏了链中较早的块,那么随后所有的块都将包含不正确的哈希。

将事务添加到块中

我们需要一种将事务添加到块中的方法。我们的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()将事务添加到列表之后,它将返回事务将被添加到下一个将要被挖掘的块的索引。这将在稍后对提交事务的用户有用。

创建一个新块(new block)

当我们的区块链被实例化时,我们需要将它与种子区块联系起来(一个没有前辈的块)。我们还需要为我们的起源块添加一个“证明”,这是挖掘(或工作证明)的结果。

除了在构造函数中创建生成块外,我们还将创建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()

以上内容应该很简单, 代码中添加了一些评论和文档以帮助理解含义。现在几乎完成了区块链的表示。

理解作业验证

作业验证算法(Proof of Work algorithm–PoW)的一个证明是在区块链上创建或挖掘新的块。PoW的目标是发现一个解决问题的数字。这个数字一定很难找到,但在网络上任何人都可以通过计算来实现。这是作业验证背后的核心思想。

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

让我们确定某个整数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

在比特币中,PoW的证明被称为Hashcash。它和上面的基本例子没有太大区别。就是为了创建一个新的区块,矿商竞相解决的算法。一般来说,实现的主要困难是由字符串中搜索的字符数决定的。然后,矿工们通过接受一笔交易来获得解决方案。

该网络能够很容易地验证他们的解决方案。

PoW实施

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值