import hashlib
# 定义区块
class Block(object):
def __init__(self, prev_hash, data):
self.data = data
self.prev_hash = prev_hash
def hash(self):
massage = hashlib.sha256()
massage.update(self.data.encode('utf8'))
return massage.hexdigest()
# 创建第一个区块
def create_first_block():
"""
生成第一个区块 - 创世区块, 没有父区块哈希
"""
return Block('', "创世区块")
# f_block = create_first_block()
# print(f_block.hash())
# 创建区块链
class BlockChain(object):
"""
区块链结构
"""
def __init__(self):
self.blocks = [create_first_block()]
def add_block(self, data):
last_block = self.blocks[-1].hash()
new_block = Block(last_block, data)
self.blocks.append(new_block)
return new_block
block_chain = BlockChain()
b2 = block_chain.add_block("第二个区块内容")
b3 = block_chain.add_block("第三个区块内容")
b4 = block_chain.add_block("第四个区块内容")
b5 = block_chain.add_block("第五个区块内容")
b6 = block_chain.add_block("第六个区块内容")
# print(block_chain.blocks)
for i in block_chain.blocks:
print(i.prev_hash)
print(i.data)
print(i.hash())
print('\r\n')
打印结果:
创世区块
e58c2569124746d14eba0e79fcee0302ea39f93462a408bed5afd379b9084847
e58c2569124746d14eba0e79fcee0302ea39f93462a408bed5afd379b9084847
第二个区块内容
f71a6fd7df0b283ac992eca64f8c281392945d4326f692696cfe3bebbc23c99f
f71a6fd7df0b283ac992eca64f8c281392945d4326f692696cfe3bebbc23c99f
第三个区块内容
9375c4960bc255eea8b4bc8f61c1be9f3ac75cec0427ac7ec5b8daaa42e77ac8
9375c4960bc255eea8b4bc8f61c1be9f3ac75cec0427ac7ec5b8daaa42e77ac8
第四个区块内容
63382dd19f5763c9b4287aba4a32d6717944370d0f828dc2daeae5e3fc1da6cd
63382dd19f5763c9b4287aba4a32d6717944370d0f828dc2daeae5e3fc1da6cd
第五个区块内容
f653c98a556a8460b3759ce6c037efba72103f50d917cb8d811e64cb6cac5d8d
f653c98a556a8460b3759ce6c037efba72103f50d917cb8d811e64cb6cac5d8d
第六个区块内容
5a861da1d8474eaccd7a3954ea0a357243e6d89bf6b46b1d1d9d8c198ad85981
|