-
Notifications
You must be signed in to change notification settings - Fork 2
/
block_chain.py
169 lines (147 loc) · 5.93 KB
/
block_chain.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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import hashlib
from random import vonmisesvariate
import datetime
import time
class Transaction:
def __init__(self, voter, voting, amounts, fee, message):
self.voter = voter
self.voting = voting
# self.sender = sender
# self.receiver = receiver
self.amounts = amounts
self.fee = fee
self.message = message
class Block:
def __init__(self, previous_hash, difficulty, miner, miner_rewards):
self.previous_hash = previous_hash
self.hash = ''
self.difficulty = difficulty
self.nonce = 0
self.timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
self.transactions = []
self.miner = miner
self.miner_rewards = miner_rewards
class BlockChain:
def __init__(self):
self.adjust_difficulty_blocks = 10
self.difficulty = 1
self.block_time = 30
self.miner_rewards = 10
self.block_limitation = 32
self.chain = []
self.pending_transactions = []
def create_genesis_block(self):
print("Create genesis block...")
new_block = Block('Hello World!', self.difficulty,
'lkm543', self.miner_rewards)
new_block.hash = self.get_hash(new_block, 0)
self.chain.append(new_block)
def transaction_to_string(self, transaction):
transaction_dict = {
'voter': str(transaction.voter),
'voting': transaction.voting,
# 'sender': str(transaction.sender),
# 'receiver': str(transaction.receiver),
'amounts': transaction.amounts,
'fee': transaction.fee,
'message': transaction.message
}
return str(transaction_dict)
def get_transactions_string(self, block):
transaction_str = ''
for transaction in block.transactions:
transaction_str += self.transaction_to_string(transaction)
return transaction_str
def get_hash(self, block, nonce):
s = hashlib.sha1()
s.update(
(
block.previous_hash
+ str(block.timestamp)
+ self.get_transactions_string(block)
+ str(nonce)
).encode("utf-8")
)
h = s.hexdigest()
return h
def add_transaction_to_block(self, block):
# Get the transaction with highest fee by block_limitation
self.pending_transactions.sort(key=lambda x: x.fee, reverse=True)
if len(self.pending_transactions) > self.block_limitation:
transcation_accepted = self.pending_transactions[:self.block_limitation]
self.pending_transactions = self.pending_transactions[self.block_limitation:]
else:
transcation_accepted = self.pending_transactions
self.pending_transactions = []
block.transactions = transcation_accepted
def mine_block(self, miner, voting):
start = time.process_time()
# self.miner_rewards = voting
last_block = self.chain[-1]
new_block = Block(last_block.hash, self.difficulty,
miner, self.miner_rewards)
new_block.miner_rewards = voting
self.add_transaction_to_block(new_block)
new_block.previous_hash = last_block.hash
new_block.difficulty = self.difficulty
new_block.hash = self.get_hash(new_block, new_block.nonce)
while new_block.hash[0: self.difficulty] != '0' * self.difficulty:
new_block.nonce += 1
new_block.hash = self.get_hash(new_block, new_block.nonce)
time_consumed = round(time.process_time() - start, 5)
print(
f"Hash found: {new_block.hash} @ difficulty {self.difficulty}, time cost: {time_consumed}s")
self.chain.append(new_block)
def return_chain(self):
return self.chain
def return_hash(self, block):
return block.hash
def return_timestamp(self, block):
return block.timestamp
def adjust_difficulty(self):
if len(self.chain) % self.adjust_difficulty_blocks != 1:
return self.difficulty
elif len(self.chain) <= self.adjust_difficulty_blocks:
return self.difficulty
else:
start = self.chain[-1*self.adjust_difficulty_blocks-1].timestamp
finish = self.chain[-1].timestamp
average_time_consumed = round(
(finish - start) / (self.adjust_difficulty_blocks), 2)
if average_time_consumed > self.block_time:
print(
f"Average block time:{average_time_consumed}s. Lower the difficulty")
self.difficulty -= 1
else:
print(
f"Average block time:{average_time_consumed}s. High up the difficulty")
self.difficulty += 1
def get_balance(self, account):
balance = 0
for block in self.chain:
# Check miner reward
miner = False
if block.miner == account:
miner = True
balance += block.miner_rewards
for transaction in block.transactions:
if miner:
balance += transaction.fee
if transaction.sender == account:
balance -= transaction.amounts
balance -= transaction.fee
elif transaction.receiver == account:
balance += transaction.amounts
return balance
def verify_blockchain(self):
previous_hash = ''
for idx, block in enumerate(self.chain):
if self.get_hash(block, block.nonce) != block.hash:
print("Error:Hash not matched!")
return False
elif previous_hash != block.previous_hash and idx:
print("Error:Hash not matched to previous_hash")
return False
previous_hash = block.hash
print("Hash correct!")
return True