-
Notifications
You must be signed in to change notification settings - Fork 0
/
blockchain.py
237 lines (199 loc) · 8.17 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
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import contextlib
import hashlib
import json
import logging
import sys
import time
import threading
from ecdsa import NIST256p
from ecdsa import VerifyingKey
import requests
import utils
MINING_DIFFICULTY = 3
MINING_SENDER = 'THE BLOCKCHAIN'
MINING_REWARD = 1.0
MINING_TIMER_SEC = 20
BLOCKCHAIN_PORT_RANGE = (5000, 5003)
NEIGHBOURS_IP_RANGE_NUM = (0, 1)
BLOCKCHAIN_NEIGHBOURS_SYNC_TIME_SEC = 20
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger(__name__)
class BlockChain(object):
def __init__(self, blockchain_address=None, port=None):
self.transaction_pool = []
self.chain = []
self.neighbours = []
self.create_block(0, self.hash({}))
self.blockchain_address = blockchain_address
self.port = port
self.mining_semaphore = threading.Semaphore(1)
self.sync_neighbours_semaphore = threading.Semaphore(1)
def run(self):
self.sync_neighbours()
self.resolve_conflicts()
self.start_mining()
def set_neighbours(self):
self.neighbours = utils.find_neighbours(
utils.get_host(), self.port,
NEIGHBOURS_IP_RANGE_NUM[0], NEIGHBOURS_IP_RANGE_NUM[1],
BLOCKCHAIN_PORT_RANGE[0], BLOCKCHAIN_PORT_RANGE[1])
logger.info({
'action': 'set_neighbours', 'neighbours': self.neighbours
})
def sync_neighbours(self):
is_acquire = self.sync_neighbours_semaphore.acquire(blocking=False)
if is_acquire:
with contextlib.ExitStack() as stack:
stack.callback(self.sync_neighbours_semaphore.release)
self.set_neighbours()
loop = threading.Timer(
BLOCKCHAIN_NEIGHBOURS_SYNC_TIME_SEC, self.sync_neighbours)
loop.start()
def create_block(self, nonce, previous_hash):
block = utils.sorted_dict_by_key({
'timestamp': time.time(),
'transactions': self.transaction_pool,
'nonce': nonce,
'previous_hash': previous_hash
})
self.chain.append(block)
self.transaction_pool = []
for node in self.neighbours:
requests.delete(f'http://{node}/transactions')
return block
def hash(self, block):
sorted_block = json.dumps(block, sort_keys=True)
return hashlib.sha256(sorted_block.encode()).hexdigest()
def add_transaction(self, sender_blockchain_address,
recipient_blockchain_address, value,
sender_public_key=None, signature=None):
transaction = utils.sorted_dict_by_key({
'sender_blockchain_address': sender_blockchain_address,
'recipient_blockchain_address': recipient_blockchain_address,
'value': float(value)
})
if sender_blockchain_address == MINING_SENDER:
self.transaction_pool.append(transaction)
return True
if self.verify_transaction_signature(
sender_public_key, signature, transaction):
if (self.calculate_total_amount(sender_blockchain_address)
< float(value)):
logger.error(
{'action': 'add_transaction', 'error': 'no_value'})
return False
self.transaction_pool.append(transaction)
return True
return False
def create_transaction(self, sender_blockchain_address,
recipient_blockchain_address, value,
sender_public_key, signature):
is_transacted = self.add_transaction(
sender_blockchain_address, recipient_blockchain_address,
value, sender_public_key, signature)
if is_transacted:
for node in self.neighbours:
requests.put(
f'http://{node}/transactions',
json={
'sender_blockchain_address': sender_blockchain_address,
'recipient_blockchain_address':
recipient_blockchain_address,
'value': value,
'sender_public_key': sender_public_key,
'signature': signature,
}
)
return is_transacted
def verify_transaction_signature(
self, sender_public_key, signature, transaction):
sha256 = hashlib.sha256()
sha256.update(str(transaction).encode('utf-8'))
message = sha256.digest()
signature_bytes = bytes().fromhex(signature)
verifying_key = VerifyingKey.from_string(
bytes().fromhex(sender_public_key), curve=NIST256p)
verified_key = verifying_key.verify(signature_bytes, message)
return verified_key
def valid_proof(self, transactions, previous_hash, nonce,
difficulty=MINING_DIFFICULTY):
guess_block = utils.sorted_dict_by_key({
'transactions': transactions,
'nonce': nonce,
'previous_hash': previous_hash
})
guess_hash = self.hash(guess_block)
return guess_hash[:difficulty] == '0'*difficulty
def proof_of_work(self):
transactions = self.transaction_pool.copy()
previous_hash = self.hash(self.chain[-1])
nonce = 0
while self.valid_proof(transactions, previous_hash, nonce) is False:
nonce += 1
return nonce
def mining(self):
# if not self.transaction_pool:
# return False
self.add_transaction(
sender_blockchain_address=MINING_SENDER,
recipient_blockchain_address=self.blockchain_address,
value=MINING_REWARD)
nonce = self.proof_of_work()
previous_hash = self.hash(self.chain[-1])
self.create_block(nonce, previous_hash)
logger.info({'action': 'mining', 'status': 'success'})
for node in self.neighbours:
requests.put(f'http://{node}/consensus')
return True
def start_mining(self):
is_acquire = self.mining_semaphore.acquire(blocking=False)
if is_acquire:
with contextlib.ExitStack() as stack:
stack.callback(self.mining_semaphore.release)
self.mining()
loop = threading.Timer(MINING_TIMER_SEC, self.start_mining)
loop.start()
def calculate_total_amount(self, blockchain_address):
total_amount = 0.0
for block in self.chain:
for transaction in block['transactions']:
value = float(transaction['value'])
if blockchain_address == \
transaction['recipient_blockchain_address']:
total_amount += value
if blockchain_address == \
transaction['sender_blockchain_address']:
total_amount -= value
return total_amount
def valid_chain(self, chain):
pre_block = chain[0]
current_index = 1
while current_index < len(chain):
block = chain[current_index]
if block['previous_hash'] != self.hash(pre_block):
return False
if not self.valid_proof(
block['transactions'], block['previous_hash'],
block['nonce'], MINING_DIFFICULTY):
return False
pre_block = block
current_index += 1
return True
def resolve_conflicts(self):
longest_chain = None
max_length = len(self.chain)
for node in self.neighbours:
response = requests.get(f'http://{node}/chain')
if response.status_code == 200:
response_json = response.json()
chain = response_json['chain']
chain_length = len(chain)
if chain_length > max_length and self.valid_chain(chain):
max_length = chain_length
longest_chain = chain
if longest_chain:
self.chain = longest_chain
logger.info({'action': 'resolve_conflicts', 'status': 'replaced'})
return True
logger.info({'action': 'resolve_conflicts', 'status': 'not_replaced'})
return False