-
Notifications
You must be signed in to change notification settings - Fork 1
/
problem_5.py
81 lines (60 loc) · 1.96 KB
/
problem_5.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
import hashlib
from datetime import datetime
class Block:
def __init__(self, data, previous_hash):
self.timestamp = self.get_utc_time()
self.data = data
self.previous_hash = previous_hash
self.hash = self.calc_hash(self.data)
self.next = None
def get_utc_time(self):
format = '%H:%M %d/%m/%Y'
return datetime.now().strftime(format)
def calc_hash(self, hash_str):
sha = hashlib.sha256()
hash_str = hash_str.encode('utf-8')
sha.update(hash_str)
return sha.hexdigest()
class Blockchain:
def __init__(self):
self.root = None
def add_block(self, data):
if self.root == None:
self.root = Block(data, 0)
else:
current = self.root
while current.next:
current = current.next
previous_hash = current.hash
current.next = Block(data, previous_hash)
def print_blockchain(self):
if self.root == None:
print("There is no block!")
return
else:
current = self.root
index = 0
print()
print("----------------")
print("Blockchain Is Printing..")
print("----------------")
while current:
print("Index:", index)
print("Timestamp:", current.timestamp)
print("Data:", current.data)
print("SHA256 Hash:", current.hash)
print("Prev_Hash:", current.previous_hash)
print("--------------->")
current = current.next
index += 1
print("")
bitcoin = Blockchain()
bitcoin.print_blockchain()
bitcoin.add_block("block1 Data")
bitcoin.add_block("block2 Data")
bitcoin.add_block("block3 Data")
bitcoin.add_block("block4 Data")
bitcoin.print_blockchain()
bitcoin.add_block("block5 Data")
bitcoin.add_block("block6 Data")
bitcoin.print_blockchain()