接着上篇的内容,这里实现一个交易记录链,废话不多说,先看图:
跟之前的逻辑类似,但也有少许不同,这里多了一个payloadhash,以及对payloadhash和prehash的hash,下面看代码实现:
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
|
import hashlib
import datetime
# 交易记录类
class DaDaMessage:
def __init__( self , data):
self . hash = None # 自身hash
self .preHash = None # 上一个区块hash
self .data = data # 交易信息
self .timestamp = datetime.datetime.now() # 交易时间
self .payloadHash = self .payload_hash() # 交易后的哈希,防止篡改
#对交易信息进行hash
def payload_hash( self ):
sha = hashlib.md5()
datastr = ( str ( self .data) + str ( self .timestamp)).encode( "utf-8" )
sha.update(datastr)
return sha.hexdigest()
#密封,锁定交易信息
def seal( self ):
self . hash = self .hash_message()
#将交易信息和上一个区块密封
def hash_message( self ):
sha = hashlib.md5()
datastr = ( str ( self .preHash) + str ( self .payloadHash)).encode( "utf-8" )
sha.update(datastr)
return sha.hexdigest()
#校验区块信息
def validate( self ):
if self . hash ! = self .hash_message():
raise InvalidateMessage( "交易哈希鏈接唄修改" )
if self .payloadHash ! = self .payload_hash():
raise InvalidateMessage( "交易時間與數據被修改" )
#鏈接區塊
def link( self ,Message):
self .preHash = Message. hash
def __repr__( self ):
return "hash:{},preHash:{},data:{}" . format ( self . hash , self .preHash, self .data)
|
自定义异常类:
1
2
3
|
class InvalidateMessage(Exception):
def __init__( self , * args, * * kwargs):
super (Exception, self ).__init__( * args, * * kwargs)
|
编写测试模块:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
if __name__ = = "__main__" :
m1 = DaDaMessage( "I love coins 12" )
m2 = DaDaMessage( "I love coins 13" )
m3 = DaDaMessage( "I love coins 14" )
try :
m1.seal()
m2.link(m1)
m2.seal()
m3.link(m2)
m3.seal()
m1. hash = "0xaaaajjjjj"
m1.data = "I don't love "
m1.validate()
m2.validate()
m3.validate()
print (m1)
print (m2)
print (m3)
except InvalidateMessage as e:
print (e)
|
查看打印结果:
跟上面的逻辑完美契合,然后我们在测试下篡改数据的结果:
当然,你也可以尝试不用try…except 看下结果。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/baidu_17508977/article/details/80525007