[Python Study Notes]一个简单的区块链结构(python 2.7)
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
>>文件: csv文件操作.py
>>作者: liu yang
>>邮箱: liuyang0001@outlook.com
>>博客: www.cnblogs.com/liu66blog
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
# !/usr/bin/env python2.7
import hashlib as hasher
import datetime as date
class Block:
def __init__(self, index, data, time, previous_hash):
self.index = index
self.data = data
self.time = time
self.previous_hash = self.hash_block()
def hash_block(self):
sha = hasher.sha256()
sha.update(str(self.index) + str(date) + str(self.time) + str(self.previous_hash))
return sha.hexdigest()
'''区块链的起源块'''
def create_genesis_block():
# 初始化一个区块
return Block(index=0, time=date.datetime.now(), data='genesis block', previous_hash='0')
'''定义下一个区块'''
def next_block(last_block):
this_index = last_block+1
this_time = date.datetime.now()
this_data = '数据'+str(this_index)
this_previous_hash = last_block.hash
return Block(index=this_index, time=this_time, data=this_data, previous_hash=this_previous_hash)
if __name__ == '__main__':
block_chain = [create_genesis_block()]
previous_block = block_chain[0]
num_of_block = 20
# 添加区块到我们的链上
for i in range(0,num_of_block):
block_to_add=next_block(previous_block)
blockchain.append(block_to_add)
previous_block=block_to_add
print('Block #{} has been added to the chain'.format(block_to_add.index))
最有用的语言,除了English,其次可能是Python

浙公网安备 33010602011771号