python从零开始实现区块链(区块链数据结构、挖矿、交易、分布性一致性解决方案源码)

参考链接:https://hackernoon.com/learn-blockchains-by-building-one-117428612f46
参考链接:https://xiaozhuanlan.com/topic/1547608293

1区块链数据结构(BlockChain.py)

一个区块主要结构如下:

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

具体说也就是当前区块的索引。
创建区块时间戳
区块里面包含的交易
知识证明
前一个区块的hash值

1.1 区块链初始化:

    def __init__(self):
        self.chain = []
        self.currentTransaction = []

        #Create the genesis block
        self.newBlock(proof=100, previousHash=1)

有一个区块链的数组
以及需要区块链里面的交易的数组
一个一个创世区块

1.2. 创建新区块

    def newBlock(self, proof, previousHash = None):
        # Creates a new Block and adds it to the chain
        """
        生成新块
        :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.currentTransaction,
            'proof' : proof,
            'previousHash' : previousHash or self.hash(self.chain[-1])
        }

        # Reset the current list of transactions
        self.currentTransaction = []

        self.chain.append(block)
        return block

前面的交易需要加入到新生成的区块中
因此新生成的区块包含前面的交易,生成之后,当前交易数组清空,最后返回当前区块

1.3. 创建新的交易

    def newTransaction(self, sender, recipient, amount):
        # Adds a new transaction to the list of transactions
        """
        生成新交易信息,信息将加入到下一个待挖的区块中
        :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.currentTransaction.append({
   
            'sender' : sender,
            'recipient' : recipient,
            'amount' : amount,
        })

        #下一个待挖的区块中
        return self.lastBlock['index'] + 1

交易有三个属性

  1. 发送方
  2. 接收方
  3. 数量

返回值的意思是,需要将交易记录在下一个区块中

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值