# 导入hashlib包
import hashlib
# 定义区块类
class Block:
# 构造函数,包含4大属性
def __init__(self,index,timestamp,data,previous_hash):
# 前一个区块的哈希值
self.previous_hash = previous_hash
# 本区块所包含的数据
self.data = data
# 本区块所持有的时间戳
self.timestamp = timestamp
# 本区块的索引
self.index = index
# 本区块的哈希值
self.hash = self.hash_block()
# 求区块的哈希值
def hash_block(self):
sha = hashlib.sha256()
sha.update((
str(self.index)+
str(self.timestamp)+
str(self.data)+
str(self.previous_hash)).encode("utf8")
)
return sha.hexdigest()
# 制作创世区块
import datetime
def create_genesis_block():
return Block(0,datetime.datetime.now(),"Genesis Block","0")
# 制作下一个区块,last_block是上一个区块
def next_block(last_block):
this_index = last_block.index+1
this_timestamp = datetime.datetime.now()
this_data = "Hey!I am block"+str(this_index)
this_hash = last_block.hash
return Block(this_index,this_timestamp,this_data,this_hash)
# 制作区块链
blockChain = [create_genesis_block()]
previous_block = blockChain[0]
# 创世区块之后,我们应该添加多少区块
num_of_blocks_to_add = 20
# 在区块链中添加区块
for i in range(num_of_blocks_to_add):
block_to_add = next_block(previous_block)
blockChain.append(block_to_add)
previous_block = block_to_add
# 打印区块链
print("Block #{} has been added to the blockchain!".format(block_to_add.index))
print("Hash:{}\n".format(block_to_add.hash))