-
Notifications
You must be signed in to change notification settings - Fork 10
/
blockchain.py
136 lines (115 loc) · 3.83 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
import hashlib
import json
import os
from time import time
BLOCKCHAIN_DIR = os.curdir + "/blocks/"
def check_blocks_integrity():
result = []
cur_proof = -1
for i in range(2, int(get_next_block())):
prev_index = str(i - 1)
cur_index = str(i)
tmp = {"block": "", "result": "", "proof": ""}
try:
file_dict = json.load(open(f"{BLOCKCHAIN_DIR}{cur_index}.json"))
cur_hash = file_dict["prev_hash"]
cur_proof = file_dict["proof"]
except Exception as e:
print(e)
try:
prev_hash = hashlib.sha256(
open(BLOCKCHAIN_DIR + prev_index + ".json", "rb").read()
).hexdigest()
except Exception as e:
print(e)
tmp["block"] = prev_index
tmp["proof"] = cur_proof
if cur_hash == prev_hash:
tmp["result"] = "ok"
else:
tmp["result"] = "error"
result.append(tmp)
return result
def check_block(index):
cur_index = str(index)
prev_index = str(int(index) - 1)
cur_proof = -1
cur_hash = 0
prev_hash = 0
tmp = {"block": "", "result": "", "proof": ""}
try:
file_dict = json.load(open(BLOCKCHAIN_DIR + cur_index + ".json"))
cur_hash = file_dict["prev_hash"]
cur_proof = file_dict["proof"]
except Exception as e:
print(e)
try:
prev_hash = hashlib.sha256(
open(BLOCKCHAIN_DIR + prev_index + ".json", "rb").read()
).hexdigest()
except Exception as e:
print(e)
tmp["block"] = prev_index
tmp["proof"] = cur_proof
if cur_hash == prev_hash:
tmp["result"] = "ok"
else:
tmp["result"] = "error"
return tmp
def get_hash(file_name):
file_name = str(file_name)
if not file_name.endswith(".json"):
file_name += ".json"
try:
with open(BLOCKCHAIN_DIR + file_name, "rb") as file:
return hashlib.sha256(file.read()).hexdigest()
except Exception:
print(f"File {file_name} is not found")
raise
def get_next_block():
files = os.listdir(BLOCKCHAIN_DIR)
index_list = [int(file.split(".")[0]) for file in files]
cur_index = sorted(index_list)[-1]
next_index = cur_index + 1
return str(next_index)
def is_valid_proof(last_proof, proof, difficulty):
guess = f"{last_proof}{proof}".encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:difficulty] == "0" * difficulty
def get_POW(file_name, difficulty=1):
# POW - proof of work
file_name = str(file_name)
if file_name.endswith(".json"):
file_name = int(file_name.split(".")[0])
else:
file_name = int(file_name)
last_proof = json.load(open(BLOCKCHAIN_DIR + str(file_name - 1) + ".json"))["proof"]
proof = 0
while is_valid_proof(last_proof, proof, difficulty) is False:
proof += 1
cur_block = json.load(open(BLOCKCHAIN_DIR + str(file_name) + ".json"))
cur_block["proof"] = proof
cur_block["prev_hash"] = get_hash(str(file_name - 1))
with open(BLOCKCHAIN_DIR + str(file_name) + ".json", "w") as file:
json.dump(cur_block, file, indent=4, ensure_ascii=False)
def write_block(text, make_proof=False):
cur_index = get_next_block()
prev_index = str(int(cur_index) - 1)
prev_block_hash = get_hash(prev_index)
data = {
"text": text,
"prev_hash": prev_block_hash,
"timestamp": time(),
"proof": -1,
"index": cur_index,
}
with open(f"{BLOCKCHAIN_DIR}{cur_index}.json", "w") as file:
json.dump(data, file, indent=4, ensure_ascii=False)
if make_proof:
get_POW(str(cur_index))
if __name__ == "__main__":
for data in range(10):
write_block(str(data), True)
for data in range(2, 10):
print(check_block(str(data)))
print(check_blocks_integrity())