-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockchain.py
66 lines (57 loc) · 2.45 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
from block import Block
import json
class Blockchain:
def __init__(self):
self.chain = []
self.unconfirmed_transactions = []
self.genesis_block()
def genesis_block(self):
transactions = []
genesis_block = Block(transactions, "0")
genesis_block.generate_hash()
self.chain.append(genesis_block)
def add_block(self, transactions):
previous_hash = (self.chain[len(self.chain) - 1]).hash
new_block = Block(transactions, previous_hash)
new_block.generate_hash()
# proof = proof_of_work(block) # Can add later for additional authenticity
self.chain.append(new_block)
def print_blocks(self):
for i in range(len(self.chain)):
current_block = self.chain[i]
print("Block {} {}".format(i, current_block))
current_block.print_contents()
def update_blocks(self):
index = len(self.chain) - 1
current_block = self.chain[index]
new_block = "Block {} {}".format(index, current_block)
with open("blockchain.json", 'r+') as file:
file_data = json.load(file)
contents = {
"timestamp": current_block.update_timestamp(),
"transactions": current_block.update_transactions(),
"current hash": current_block.update_current_hash(),
"previous hash": current_block.update_previous_hash()
}
block = {new_block: contents}
file_data["blockchain"].append(block)
file.seek(0)
string = json.dump(file_data, file, indent = 4)
def validate_chain(self):
for i in range(1, len(self.chain)):
current = self.chain[i]
previous = self.chain[i - 1]
if (current.hash != current.generate_hash()):
print("Current hash does not equal generated hash")
return False
if (current.previous_hash != previous.generate_hash()):
print("Previous block's hash was changed")
return False
return True
def proof_of_work(self, block, difficulty=2):
proof = block.generate_hash()
while proof[:2] != "0" * difficulty:
block.nonce += 1
proof = block.generate_hash()
block.nonce = 0
return proof