1+ import hashlib as hasher
2+ import datetime as date
3+
4+ class Block :
5+ def __init__ (self , index , timestamp , data , previous_hash ):
6+ self .index = index
7+ self .timestamp = timestamp
8+ self .data = data
9+ self .previous_hash = previous_hash
10+ self .hash = self .hash_block ()
11+
12+ def hash_block (self ):
13+ sha = hasher .sha256 ()
14+ sha .update ((str (self .index ) + str (self .timestamp ) + str (self .data ) + str (self .previous_hash )).encode ("utf-8" ))
15+ return sha .hexdigest ()
16+
17+ def create_genesis_block ():
18+ # 手工创建第一个区块,其索引为 0,且随意取给紧前特征值 '0'
19+ return Block (0 , date .datetime .now (), "Genesis Block" , "0" )
20+
21+ def next_block (last_block ):
22+ this_index = last_block .index + 1
23+ this_timestamp = date .datetime .now ()
24+ this_data = "Hey! I'm block " + str (this_index )
25+ this_hash = last_block .hash
26+ return Block (this_index , this_timestamp , this_data , this_hash )
27+
28+ # 创建一个区块链,并将第一个区块加入
29+ blockchain = [create_genesis_block ()]
30+
31+ # 设置产生区块的个数
32+ num_of_blocks_to_add = 20
33+
34+ # 产生区块并加入区块链
35+ for i in range (0 , num_of_blocks_to_add ):
36+ previous_block = blockchain [- 1 ]
37+ block_to_add = next_block (previous_block )
38+ blockchain .append (block_to_add )
39+ # 发布当前区块的信息
40+ print ("Block #{} has been added to the blockchain!" .format (block_to_add .index ))
41+ print ("Hash: {}\n " .format (block_to_add .hash ))
0 commit comments