python实现区块链

区块链可以看做是一个公共数据库,其中新数据存储在一个称为区块的容器中,然后被添加到一条不可更改的链上(也就是区块链),同时,链上保存着之前的数据记录。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import hashlib
import time

class Block:
'''
区块类
'''
def __init__(self, index, timestamp, data, pre_hash):
self.index = index # 区块序号
self.timestamp = timestamp # 时间戳
self.data = data # 待加密内容
self.pre_hash = pre_hash # 前一个区块的hash
self.hash = self.hash_block() # 当前区块的hash

def hash_block(self):
string = str(self.index) + str(self.timestamp) + str(self.data) + str(self.pre_hash)
sha = hashlib.sha256()
sha.update(string.encode("utf-8"))
return sha.hexdigest()

# 创建创始区块
def create_gensis_block():
return Block(0, time.time(), "first_block", "0000000")

# 创建其它区块
def next_block(last_block, data):
return Block(last_block.index + 1, time.time(), str(data), last_block.hash)

gensis_block = create_gensis_block()
# print(str(gensis_block.index) + "---" + str(gensis_block.timestamp) + "---" + str(gensis_block.data) + "---hash:" + gensis_block.hash)

#========================================================
# 组链
#========================================================

blockchain = [gensis_block]
previous_block = blockchain[0]

for i in range(10):
block_to_add = next_block(previous_block, str(i))
blockchain.append(block_to_add)
previous_block = block_to_add
print("Block #{} has been added to the blockchain!".format(previous_block.index))
print("Hash:{}\n".format(previous_block.hash))

拓展阅读

0%