理解区块链——从搭建一个区块链入手

本文介绍了如何在Python环境中搭建一个简单的区块链,包括创建Blockchain类,定义交易信息,创建创世区块,并实现工作量证明(Proof of Work)机制。通过这个过程,读者可以深入理解区块链的基本原理和运作方式。
摘要由CSDN通过智能技术生成

背景

  • 目前区块链的各种教程很容易让人似懂非懂,真正想理解,不如直接敲一遍,把每一步的逻辑理解清楚才是最实在的。

环境

  • 测试环境:Google Colab

1. 先定义好需要的工具有

#flask 提供了一个基本的Web功能
#requests 做接口测试可以用
!pip install Flask==0.12.2 requests==2.18.4
#API接口测试工具
!pip install cURL

2. 开始书写Blockchain类代码

  • 我们要明确blockchain它有的功能。
    • 首先在开始创建的时候,我们必须要有一个chain来完成链里面所有区块的记录。
    • 那么链里面的区块是怎么来的,当然是通过new_block这样的函数新建而来。
    • new_block这样的函数新建出来的区块需要包含哪些基本信息呢?
      • 实际上需要有的是index,timestamp,transcations,proof以及previous_hash这样的一些信息。
      • 但如果搭建过以太坊的就会很困惑,因为以太坊里的创始区块不止有这几个字段,这是因为它新增了很多和安全与应用相关的功能。
    • 那么transcations中记录了什么呢?
      • 它记录了一份包含着sender,recipientamount的字段。
      • 需要注意的是它记录的是一个交易的列表,而并非一次的交易,所以每一个区块都会有这个链过往交易的所有列表。
  • 这边我们列举一个区块
block = {
    'index': 1,
    'timestamp': 1506057125.900785,
    'transactions': [
        {
            'sender': "8527147fe1f5426f9dd545de4b27ee00",
            'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
            'amount': 5,
        }
    ],
    'proof': 324984774000,
    'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}
  • 直观的理解,indextimestamp以及transcations都好懂,但是proof的原理是什么呢?
    • 首先,对于区块链有基础了解,就很容易理解记账的人会获得奖励的概念,所以大家就会用自己的节点拼命的记账。
    • 而谁才能够算记账成功并且获得奖励呢,他们设计了一套机制。
    • 首先,给定一个整数x,其次是要求记账的节点生成另一个整数y,这个整数y会使得hash(x*y)的末尾出现k0。例如,当k=1时,就只需要hash(x*y)=xxx...xxx0即完成记账了。
    • 当然,如果要求的是开始的部分出现k个0,那么检查的时候就会更加方便,所以我们现在就可以为我们接下来的Blockchain提一个需求,即寻找数字p,要求哈希开头是4个0。

2.1. 定义基础的数据结构

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

2.2. 在区块中添加交易信息

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
  • 注意,在列表中添加新交易之后,会返回该交易被加到的区块的索引,也就是指向下一个要挖的区块

2.3. 创世区块和工作量证明

  • 实例化Blockchain类之后,还需要新建一个创始区块。此外还要加入证明。
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()

2.4. 完成工作量证明的书写

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值