一、开发环境搭建
1、安装pipenv
pipenv可以帮助我们管理Python和第三方库的版本。**pip3 install pipenv**
在项目文件夹中生成Pipfile文件**pipenv --python=python3.10 **
此时生成Pipfile文件
2、 在pipenv环境下安装flask、requests**pipenv install flask==0.12.2****pipenv install requests==2.18.4**
二、确定区块的结构
{"index": 0, #块的索引"timestamp": "", #时间戳"transactions": [ #交易的信息{"sender":"", #交易的发送者"recipient":"", #交易的接收者"amount": 5 #交易的金额}],"proof": "", #工作量证明"previous_hash":"" #上一个区块的哈希值}
三、定义类进行区块的封装
class Blockchain:def __init__(self):self.chain = [] #包含每一个区块self.current_transactions = [] #保存当前的交易信息def new_block(self): #建立新区块passdef new_transactions(self, sender, recipient, amount) -> int: #建立新交易self.current_transactions.append({"sender": sender, #交易的发送者"recipient": recipient, #交易的接收者"amount": amount #交易的金额})return self.last_block['index'] + 1@staticmethoddef hash(block): #计算区块的哈希值pass@propertydef last_block(self): #获取当前区块链里最后一个块pass
