-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockChain.py
More file actions
59 lines (52 loc) · 1.79 KB
/
Copy pathBlockChain.py
File metadata and controls
59 lines (52 loc) · 1.79 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#BlockChain.py
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
class someClass:
string = None
num = 328965
def __init__(self, mystring):
self.string = mystring
def __repr__(self):
return self.string + "^^^" + str(self.num)
class CBlock:
data = None
previousHash = None
previousBlock = None
def __init__(self, data, previousBlock):
self.data = data
self.previousBlock = previousBlock
if previousBlock != None:
self.previousHash = previousBlock.computeHash()
def computeHash(self):
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.update(bytes(str(self.data),'utf8'))
digest.update(bytes(str(self.previousHash),'utf8'))
return digest.finalize()
def is_valid(self):
if self.previousBlock == None:
return True
return self.previousBlock.computeHash() == self.previousHash
if __name__ == '__main__':
root = CBlock('I am root', None)
B1 = CBlock(b'I am a child.', root)
B2 = CBlock('I am B1s brother', root)
B3 = CBlock(12354, B1)
B4 = CBlock(someClass('Hi there!'), B3)
B5 = CBlock("Top block", B4)
for b in [B1, B2, B3, B4, B5]:
if b.is_valid():
print ("Success! Hash is good.")
else:
print ("ERROR! Hash is no good.")
B3.data=12345
if B4.is_valid():
print ("ERROR! Couldn't detect tampering.")
else:
print ("Success! Tampering detected.")
print(B4.data)
B4.data.num = 99999
print(B4.data)
if B5.is_valid():
print ("ERROR! Couldn't detect tampering.")
else:
print ("Success! Tampering detected.")