-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockchain.py
More file actions
83 lines (59 loc) · 2.43 KB
/
blockchain.py
File metadata and controls
83 lines (59 loc) · 2.43 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import hashlib
import time
import json
class Block(object):
def __init__(self, difficulty, index, data, previous_hash=''):
self.difficulty = difficulty
self.nonce = 0
self.index = index
self.previous_hash = previous_hash
self.data = data
self.timestamp = time.time()
self.hash = self.hash_calculation()
def hash_calculation(self):
return hashlib.sha256(str(self.index).encode() + str(self.data).encode() + str(self.timestamp).encode() +
str(self.nonce).encode()).hexdigest()
def block_mining(self):
while self.hash[0:self.difficulty] != "0" * self.difficulty:
self.nonce += 1
self.hash = self.hash_calculation()
# print("Block mined:" + self.hash + " nonce:" + str(self.nonce))
class BlockChain(object):
def __init__(self, difficulty):
self.chain = [self.genesis_block()]
self.difficulty = difficulty
def genesis_block(self):
return Block(2, 0, "GENESIS", "xxx")
def get_prev_block(self):
return self.chain[len(self.chain)-1]
def add_block(self, new_block):
new_block.previous_hash = self.get_prev_block().hash
new_block.block_mining()
self.chain.append(new_block)
@property
def chain_validation(self):
for k, block in enumerate(self.chain):
if k > 0:
prev_block = self.chain[k-1]
if block.hash != block.hash_calculation():
return False
if block.previous_hash != prev_block.hash:
return False
else:
pass
return True
diff = 3
data1 = json.dumps({'username': 'Pippo', 'amount': 1.00}, sort_keys=True, indent=4)
data2 = json.dumps({'username': 'Baudo', 'amount': 5.00}, sort_keys=True, indent=4)
data3 = json.dumps({'username': 'Pippo', 'amount': 1.00}, sort_keys=True, indent=4)
data4 = json.dumps({'username': 'Pippo', 'amount': 1.00}, sort_keys=True, indent=4)
b = BlockChain(diff)
b.add_block(Block(diff, 1, data1))
b.add_block(Block(diff, 2, data2))
b.add_block(Block(diff, 3, data3))
# uncomment line below to invalidate the chain by tampering 1st block with new data (PoW)
# b.chain[1].hash = "test" #PoW
b.add_block(Block(diff, 4, data4))
print("Chain is valid?: " + str(b.chain_validation) + "\r\n")
# for elements in b.chain:
# print("data: " + elements.data + " hash: " + elements.hash)