-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBlockChain.py
80 lines (70 loc) · 2.79 KB
/
BlockChain.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import hashlib
import json
class BlockChain: # BlockChain class
blockchains = []
hashval = None
last_block_hash = None
length = 0
genesis_block = {
'block_id': None,
'prev_hash': None,
'block_hash': None,
'transactions': {
'tx1': 'generate genesis block.'
}
}
def spacer1(self):
print("*" * 80)
def spacer2(self):
print(" " * 80)
def details(self):
print("Block-chains Details")
for block in self.blockchains:
self.spacer2()
print("BlockID: {}\nBlock hash: {}\nPrev Hash: {}\nTransactions: {}".format(
block['block_id'], block['block_hash'], block['prev_hash'], block['transactions']))
self.spacer2()
# def BlockChain(self):
# self.generate_genesis_block()
def check(self):
count = 0
for block in self.blockchains:
_hash = block['block_hash']
block['block_hash'] = None
b = json.dumps(block, sort_keys=True).encode('utf-8')
block['block_hash'] = hashlib.sha256(b).hexdigest()
if _hash != block['block_hash']:
self.spacer1()
print("ALERT BLOCKCHAINS HAVE BEEN MODIFY AT BLOCK {}!".format(count))
print("Original hash: {}\nNew hash: {}".format(
_hash, block['block_hash']))
self.spacer1()
return
count += 1
print("Block chain is secured.")
def hack(self, n, val):
tmp_hash = self.blockchains[n]['block_hash']
self.blockchains[n]['transactions']['tx1'] = val
# self.check()
def alert(self, org, now):
print("old value: {}\nnow value: {}\n".format(org, now))
def generate_genesis_block(self):
self.genesis_block['block_id'] = self.length
self.length += 1
b = json.dumps(self.genesis_block, sort_keys=True).encode('utf-8')
self.genesis_block['prev_hash'] = hashlib.sha256(b).hexdigest()
b = json.dumps(self.genesis_block, sort_keys=True).encode('utf-8')
self.genesis_block['block_hash'] = hashlib.sha256(b).hexdigest()
self.blockchains.append(self.genesis_block)
self.last_block_hash = self.genesis_block['block_hash']
print("Generating Genesis Block..........OK\n")
def addblock(self, newblock):
newblock['prev_hash'] = self.last_block_hash
newblock['block_id'] = self.length
self.length += 1
b = json.dumps(newblock, sort_keys=True).encode('utf-8')
newblock['block_hash'] = hashlib.sha256(b).hexdigest()
self.blockchains.append(newblock)
self.last_block_hash = newblock['block_hash']
# print("Adding new Block: {}".format(newblock))
print("Adding new block..........OK\n")