-
Notifications
You must be signed in to change notification settings - Fork 7
/
leader.py
499 lines (412 loc) · 17.2 KB
/
leader.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
from __future__ import print_function
import time
import uuid
import hashlib
import tornado.web
import tornado.websocket
import tornado.ioloop
import tornado.httpclient
import tornado.gen
import tornado.escape
import setting
import tree
import node
import database
certain_value = "0"
certain_value = certain_value + 'f'*(64-len(certain_value))
working = False
system_view = None
current_view = None
current_view_no = 0
view_transactions = {}
view_confirms = {}
root_jump = {}
def lastest_block(root_hash):
global root_jump
chains = []
prev_hashs = []
if root_hash in root_jump:
recent_hash = root_jump[root_hash]
chains.append([recent_hash])
prev_hashs.append(recent_hash)
else:
roots = database.connection.query("SELECT * FROM graph"+tree.current_port+" WHERE from_block = %s OR to_block = %s ORDER BY nonce", root_hash, root_hash)
for root in roots:
# print(root.id)
chains.append([root.hash])
prev_hashs.append(root.hash)
while True:
if prev_hashs:
prev_hash = prev_hashs.pop(0)
else:
break
leaves = database.connection.query("SELECT * FROM graph"+tree.current_port+" WHERE from_block = %s AND sender = %s ORDER BY nonce", prev_hash, root_hash)
if len(leaves) > 0:
for leaf in leaves:
# print(leaf.id)
for c in chains:
if c[-1] == prev_hash:
chain = c.copy()
chain.append(leaf.hash)
chains.append(chain)
break
if leaf.hash not in prev_hashs and leaf.hash:
prev_hashs.append(leaf.hash)
leaves = database.connection.query("SELECT * FROM graph"+tree.current_port+" WHERE to_block = %s AND receiver = %s ORDER BY nonce", prev_hash, root_hash)
if len(leaves) > 0:
for leaf in leaves:
# print(leaf.id)
for c in chains:
if c[-1] == prev_hash:
chain = c.copy()
chain.append(leaf.hash)
chains.append(chain)
break
if leaf.hash not in prev_hashs and leaf.hash:
prev_hashs.append(leaf.hash)
longest = []
for i in chains:
if not longest:
longest = i
if len(longest) < len(i):
longest = i
# print(longest)
if len(longest) > 3:
root_jump[root_hash] = longest[-3]
return longest
def forward(seq):
# global processed_message_ids
# msg_id = seq[-1]
# if msg_id in processed_message_ids:
# return
# processed_message_ids.add(msg_id)
msg = tornado.escape.json_encode(seq)
for leader_node in LeaderHandler.leader_nodes:
leader_node.write_message(msg)
for leader_connector in LeaderConnector.leader_nodes:
leader_connector.conn.write_message(msg)
# connect point from leader node
class LeaderHandler(tornado.websocket.WebSocketHandler):
leader_nodes = set()
def check_origin(self, origin):
return True
def open(self):
self.from_host = self.get_argument("host")
self.from_port = self.get_argument("port")
# self.remove_node = True
# if False: #temp disable force disconnect
# print(tree.current_port, "leader force disconnect")
# self.remove_node = False
# self.close()
# return
print(tree.current_port, "leader connected")
if self not in LeaderHandler.leader_nodes:
LeaderHandler.leader_nodes.add(self)
def on_close(self):
print(tree.current_port, "leader disconnected")
if self in LeaderHandler.leader_nodes: # and self.remove_node
LeaderHandler.leader_nodes.remove(self)
# self.remove_node = True
@tornado.gen.coroutine
def on_message(self, msg):
global current_view_no
seq = tornado.escape.json_decode(msg)
print(tree.current_port, "on message from leader connector", seq)
if seq[0] == "NEW_BLOCK":
miner.new_block(seq)
# elif seq[0] == "TX":
# transaction = seq[1]
# txid = transaction["transaction"]["txid"]
# sender = transaction["transaction"]["sender"]
# receiver = transaction["transaction"]["receiver"]
# amount = transaction["transaction"]["amount"]
# timestamp = transaction["transaction"]["timestamp"]
# signature = transaction["signature"]
# nonce = transaction["nonce"]
# from_block = transaction["from_block"]
# to_block = transaction["to_block"]
# # sender_blocks = lastest_block(sender)
# # receiver_blocks = lastest_block(receiver)
# if from_block in locked_blocks or to_block in locked_blocks:
# message = ["NAK", txid]
# self.write_message(tornado.escape.json_encode(message))
# else:
# message = ["ACK", txid]
# self.write_message(tornado.escape.json_encode(message))
# print(tree.current_port, "TX", message)
# return
# elif seq[0] == "ACK":
# txid = seq[1]
# reply = block_to_reply.get(txid)
# if self in reply:
# reply.remove(self)
# print(tree.current_port, "ACK reply", reply)
# if reply:
# return
# transaction = block_to_confirm.get(txid)
# sender = transaction["transaction"]["sender"]
# receiver = transaction["transaction"]["receiver"]
# block_hash = transaction["block_hash"]
# nonce = transaction["nonce"]
# from_block = transaction["from_block"]
# to_block = transaction["to_block"]
# return
# elif seq[0] == "NAK":
# txid = seq[1]
# transaction = block_to_confirm.get(txid)
# if transaction:
# from_block = transaction["from_block"]
# to_block = transaction["to_block"]
# if from_block in locked_blocks:
# locked_blocks.remove(from_block)
# if to_block in locked_blocks:
# locked_blocks.remove(to_block)
# if transaction:
# del block_to_confirm[txid]
# return
elif seq[0] == "PBFT_O":
# print(tree.current_port, "PBFT_O get message", seq[1])
view = seq[1]
view_no = seq[2]
# view's no should be continuous
transaction = seq[3]["transaction"]
txid = transaction["txid"]
# gen block
block_hash = ""
view_transactions["%s_%s"%(int(view), int(view_no))] = transaction
forward(["PBFT_P", view, view_no, txid, block_hash])
return
elif seq[0] == "PBFT_P":
view = seq[1]
view_no = seq[2]
txid = seq[3]
block_hash = seq[4]
# verify blockhash with own blockhash for txid
forward(["PBFT_C", view, view_no, txid, current_view])
return
elif seq[0] == "PBFT_C":
view = seq[1]
view_no = seq[2]
txid = seq[3]
confirm_view = seq[4]
k = "%s_%s"%(int(view), int(view_no))
transaction = view_transactions.get(k)
view_confirms.setdefault(k, set())
confirms = view_confirms[k]
if confirm_view not in confirms:
confirms.add(confirm_view)
if transaction and len(confirms)==2:
print(tree.current_port, "NEW_TX_BLOCK", txid, confirms)
message = ["NEW_TX_BLOCK", transaction, time.time(), uuid.uuid4().hex]
return
elif seq[0] == "PBFT_V":
pass
forward(seq)
# connector to leader node
class LeaderConnector(object):
"""Websocket Client"""
leader_nodes = set()
def __init__(self, to_host, to_port):
self.host = to_host
self.port = to_port
self.ws_uri = "ws://%s:%s/leader?host=%s&port=%s" % (self.host, self.port, tree.current_host, tree.current_port)
# self.branch = None
self.remove_node = False
self.conn = None
self.connect()
def connect(self):
tornado.websocket.websocket_connect(self.ws_uri,
callback = self.on_connect,
on_message_callback = self.on_message,
connect_timeout = 1000.0)
def close(self):
self.remove_node = True
if self in LeaderConnector.leader_nodes:
LeaderConnector.leader_nodes.remove(self)
self.conn.close()
def on_connect(self, future):
print(tree.current_port, "leader connect")
try:
self.conn = future.result()
if self not in LeaderConnector.leader_nodes:
LeaderConnector.leader_nodes.add(self)
except:
print(tree.current_port, "reconnect leader on connect ...")
tornado.ioloop.IOLoop.instance().call_later(1.0, self.connect)
def on_message(self, msg):
if msg is None:
if not self.remove_node:
print(tree.current_port, "reconnect leader on message...")
# self.ws_uri = "ws://%s:%s/leader?host=%s&port=%s" % (self.host, self.port, tree.current_host, tree.current_port)
tornado.ioloop.IOLoop.instance().call_later(1.0, self.connect)
return
seq = tornado.escape.json_decode(msg)
print(tree.current_port, "on message from leader", seq)
if seq[0] == "NEW_BLOCK":
miner.new_block(seq)
elif seq[0] == "PBFT_P":
view = seq[1]
view_no = seq[2]
txid = seq[3]
block_hash = seq[4]
# verify blockhash with own blockhash for txid
forward(["PBFT_C", view, view_no, txid, current_view])
return
elif seq[0] == "PBFT_C":
view = seq[1]
view_no = seq[2]
txid = seq[3]
confirm_view = seq[4]
k = "%s_%s"%(int(view), int(view_no))
transaction = view_transactions.get(k)
view_confirms.setdefault(k, set())
confirms = view_confirms[k]
if confirm_view not in confirms:
confirms.add(confirm_view)
if transaction and len(confirms)==2:
print(tree.current_port, "NEW_TX_BLOCK", txid, confirms)
message = ["NEW_TX_BLOCK", transaction, time.time(), uuid.uuid4().hex]
return
# elif seq[0] == "TX":
# transaction = seq[1]
# txid = transaction["transaction"]["txid"]
# sender = transaction["transaction"]["sender"]
# receiver = transaction["transaction"]["receiver"]
# amount = transaction["transaction"]["amount"]
# timestamp = transaction["transaction"]["timestamp"]
# signature = transaction["signature"]
# nonce = transaction["nonce"]
# from_block = transaction["from_block"]
# to_block = transaction["to_block"]
# # sender_blocks = lastest_block(sender)
# # receiver_blocks = lastest_block(receiver)
# if from_block in locked_blocks or to_block in locked_blocks:
# message = ["NAK", txid]
# self.conn.write_message(tornado.escape.json_encode(message))
# else:
# message = ["ACK", txid]
# self.conn.write_message(tornado.escape.json_encode(message))
# print(tree.current_port, "TX", message)
# return
# elif seq[0] == "ACK":
# txid = seq[1]
# reply = block_to_reply.get(txid)
# if self in reply:
# reply.remove(self)
# print(tree.current_port, "ACK reply", reply)
# if reply:
# return
# transaction = block_to_confirm.get(txid)
# sender = transaction["transaction"]["sender"]
# receiver = transaction["transaction"]["receiver"]
# block_hash = transaction["block_hash"]
# nonce = transaction["nonce"]
# from_block = transaction["from_block"]
# to_block = transaction["to_block"]
# data = {}
# database.connection.execute("INSERT INTO graph"+tree.current_port+" (hash, from_block, to_block, sender, receiver, nonce, data) VALUES (%s, %s, %s, %s, %s, %s, %s)", block_hash, from_block, to_block, sender, receiver, nonce, tornado.escape.json_encode(data))
# return
# elif seq[0] == "NAK":
# txid = seq[1]
# transaction = block_to_confirm.get(txid)
# if transaction:
# from_block = transaction["from_block"]
# to_block = transaction["to_block"]
# if from_block in locked_blocks:
# locked_blocks.remove(from_block)
# if to_block in locked_blocks:
# locked_blocks.remove(to_block)
# if transaction:
# del block_to_confirm[txid]
# return
# else:
forward(seq)
transactions = []
locked_blocks = set()
block_to_confirm = {}
block_to_reply = {}
def mining():
# global working
# global transactions
# global locked_blocks
global current_view_no
if working:
tornado.ioloop.IOLoop.instance().call_later(1, mining)
if transactions:
print(tree.current_port, "I'm the leader", current_view, "of leader view", system_view)
seq = transactions.pop(0)
if current_view != system_view:
return
transaction = seq[1]
txid = transaction["transaction"]["txid"]
sender = transaction["transaction"]["sender"]
receiver = transaction["transaction"]["receiver"]
amount = transaction["transaction"]["amount"]
timestamp = transaction["transaction"]["timestamp"]
signature = transaction["signature"]
sender_blocks = lastest_block(sender)
receiver_blocks = lastest_block(receiver)
from_block = sender_blocks[-1] if sender_blocks else sender
to_block = receiver_blocks[-1] if receiver_blocks else receiver
# if from_block in locked_blocks or to_block in locked_blocks:
# transactions.append(seq)
# tornado.ioloop.IOLoop.instance().call_later(1, mining)
# return
nonce = 0
data = txid + sender + receiver + str(amount) + str(timestamp) + signature + from_block + to_block + str(tree.current_port)
# while True:
block_hash = hashlib.sha256((data + str(nonce)).encode('utf8')).hexdigest()
# if block_hash < certain_value:
# locked_blocks.add(from_block)
# locked_blocks.add(to_block)
transaction["block_hash"] = block_hash
transaction["nonce"] = nonce
transaction["from_block"] = from_block
transaction["to_block"] = to_block
# block_to_confirm[txid] = transaction
# reply = block_to_reply.setdefault(txid, set())
# for leader_node in LeaderHandler.leader_nodes:
# reply.add(leader_node)
# for leader_connector in LeaderConnector.leader_nodes:
# reply.add(leader_connector)
# print(tree.current_port, "reply", reply)
# print(tree.current_port, message)
current_view_no += 1
message = ["PBFT_O", current_view, current_view_no, transaction]
forward(message)
# break
# nonce += 1
# print(tree.current_port, "txid", txid, from_block, to_block)
current_leaders = set()
previous_leaders = set()
def update(leaders):
global current_leaders
global previous_leaders
global working
current_leaders = leaders
if ("localhost", tree.current_port) in leaders - previous_leaders:
for other_leader_addr in leaders:
connected = set([(i.host, i.port) for i in LeaderConnector.leader_nodes]) |\
set([(i.from_host, i.from_port) for i in LeaderHandler.leader_nodes]) |\
set([(tree.current_host, tree.current_port)])
if other_leader_addr not in connected:
# print(tree.current_port, other_leader_addr, connected)
LeaderConnector(*other_leader_addr)
if not working:
tornado.ioloop.IOLoop.instance().add_callback(mining)
working = True
nodes_to_close = set()
for node in LeaderConnector.leader_nodes:
if (node.host, node.port) not in leaders:
nodes_to_close.add(node)
# print(tree.current_port, "nodes_to_close", len(nodes_to_close))
while nodes_to_close:
nodes_to_close.pop().close()
if ("localhost", tree.current_port) not in leaders:
working = False
while LeaderConnector.leader_nodes:
LeaderConnector.leader_nodes.pop().close()
previous_leaders = leaders
if __name__ == '__main__':
# main()
print("run python node.py pls")