forked from theQRL/QRL
-
Notifications
You must be signed in to change notification settings - Fork 1
/
node.py
2177 lines (1681 loc) · 75 KB
/
node.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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# QRL testnet node..
# -features POS, quantum secure signature scheme..
__author__ = 'pete'
import time, struct, random, copy, decimal
import chain, wallet, merkle
import logger
from twisted.internet.protocol import ServerFactory, Protocol
from twisted.internet import reactor, defer, task, threads
from merkle import sha256, numlist, hexseed_to_seed, mnemonic_to_seed, GEN_range, random_key
from operator import itemgetter
from collections import Counter, defaultdict
from math import ceil
from blessings import Terminal
import statistics
import json
version_number = "alpha/0.04a"
log = logger.getLogger(__name__)
cmd_list = ['balance', 'mining', 'seed', 'hexseed', 'recoverfromhexseed', 'recoverfromwords', 'stakenextepoch', 'stake', 'address', 'wallet', 'send', 'mempool', 'getnewaddress', 'quit', 'exit', 'search' ,'json_search', 'help', 'savenewaddress', 'listaddresses','getinfo','blockheight', 'json_block']
api_list = ['block_data','stats', 'ip_geotag','exp_win','txhash', 'address', 'empty', 'last_tx', 'stake_reveal_ones', 'last_block', 'richlist', 'ping', 'stake_commits', 'stake_reveals', 'stake_list', 'stakers', 'next_stakers', 'latency']
term = Terminal();
print term.enter_fullscreen
#Initializing function to log console output
printL = logger.PrintHelper(log).printL
chain.printL = printL
wallet.printL = printL
merkle.printL = printL
r1_time_diff = defaultdict(list) #r1_time_diff[block_number] = { 'stake_address':{ 'r1_time_diff': value_in_ms }}
r2_time_diff = defaultdict(list) #r2_time_diff[block_number] = { 'stake_address':{ 'r2_time_diff': value_in_ms }}
pending_blocks = {} #Used only for synchronization of blocks
isDownloading = False
sameEpochSync = False
last_pos_cycle = 0
last_selected_height = 0
reveal_cleaned = True
sync_time = 0
last_bk_time = 0
next_header_hash = None
next_block_number = None
allow_reveal_duplicates = False
def parse(data):
return data.replace('\r\n','')
def monitor_bk():
global last_pos_cycle, last_bk_time, isDownloading
if not isDownloading and time.time() - last_pos_cycle > 240:
if time.time() - last_bk_time > 120:
printL (( ' POS cycle activated by monitor_bk() ' ))
restart_post_block_logic()
reactor.callLater(120, monitor_bk)
# pos functions. an asynchronous loop.
# first block 1 is created with the stake list for epoch 0 decided from circulated st transactions
def pre_pos_1(data=None): # triggered after genesis for block 1..
printL(( 'pre_pos_1'))
# are we a staker in the stake list?
if chain.mining_address in chain.m_blockchain[0].stake_list:
printL(('mining address:', chain.mining_address,' in the genesis.stake_list'))
chain.my[0][1].hashchain(epoch=0)
chain.hash_chain = chain.my[0][1].hc
printL(('hashchain terminator: ', chain.hash_chain[-1]))
st = chain.CreateStakeTransaction(chain.hash_chain[-1])
wallet.f_save_winfo()
chain.add_st_to_pool(st)
f.send_st_to_peers(st) #send the stake tx to generate hashchain terminators for the staker addresses..
printL(( 'await delayed call to build staker list from genesis'))
reactor.callLater(5, pre_pos_2, st)
return
printL(( 'not in stake list..no further pre_pos_x calls'))
return
def pre_pos_2(data=None):
printL(( 'pre_pos_2'))
# assign hash terminators to addresses and generate a temporary stake list ordered by st.hash..
tmp_list = []
for st in chain.stake_pool:
if st.txfrom in chain.m_blockchain[0].stake_list:
tmp_list.append([st.txfrom, st.hash, 0])
chain.stake_list = sorted(tmp_list, key=itemgetter(1))
numlist(chain.stake_list)
printL(( 'genesis stakers ready = ', len(chain.stake_list),'/',len(chain.m_blockchain[0].stake_list)))
printL(( 'node address:', chain.mining_address))
if len(chain.stake_list) < len(chain.m_blockchain[0].stake_list): # stake pool still not full..reloop..
f.send_st_to_peers(data)
printL(( 'waiting for stakers.. retry in 5s'))
reactor.callID = reactor.callLater(5, pre_pos_2, data)
return
for s in chain.stake_list:
if s[0] == chain.mining_address:
spos = chain.stake_list.index(s)
chain.epoch_prf = chain.pos_block_selector(chain.m_blockchain[-1].stake_seed, len(chain.stake_pool)) #Use PRF to decide first block selector..
#def GEN_range(SEED, start_i, end_i, l=32):
chain.epoch_PRF = GEN_range(chain.m_blockchain[-1].stake_seed, 1, 10000, 32)
printL(( 'epoch_prf:', chain.epoch_prf[1]))
printL(( 'spos:', spos))
if spos == chain.epoch_prf[1]:
printL(( 'designated to create block 1: building block..'))
# create the genesis block 2 here..
b = chain.m_create_block(chain.hash_chain[-2])
#chain.json_printL(((b)
#printL(( chain.validate_block(b)))
if chain.m_add_block(b) == True:
f.send_block_to_peers(b)
#f.get_m_blockheight_from_peers()
printL(( '**POS commit call later 30 (genesis)...**'))
f.send_stake_reveal_one()
reactor.callLater(15, reveal_two_logic)
else:
printL(( 'await block creation by stake validator:', chain.stake_list[chain.epoch_prf[1]][0]))
#f.send_st_to_peers(data)
return
# we end up here exactly 30 seconds after the last block arrived or was created and sent out..
# collate the reveal_ones messages to decide the winning hash..send out reveal_two's with our vote..
def reveal_two_logic(data=None):
printL(( 'reveal_two_logic'))
#chain.stake_reveal_one.append([stake_address, headerhash, block_number, reveal_one, reveal_two])
reveals = []
curr_time = int(time.time()*1000)
global r1_time_diff
r1_time_diff[chain.m_blockchain[-1].blockheader.blocknumber+1] = map(lambda t1: curr_time - t1,r1_time_diff[chain.m_blockchain[-1].blockheader.blocknumber+1])
for s in chain.stake_reveal_one:
if s[1] == chain.m_blockchain[-1].blockheader.headerhash and s[2] == chain.m_blockchain[-1].blockheader.blocknumber+1:
reveals.append(s[3])
# are we forked and creating only our own blocks?
if len(reveals) <= 1:
printL(( 'only received one reveal for this block..quitting reveal_two_logic'))
f.get_m_blockheight_from_peers()
restart_post_block_logic()
return
# what is the PRF output and expected winner for this block?
epoch = (chain.m_blockchain[-1].blockheader.blocknumber+1)/10000 #+1 = next block
winner = chain.cl_hex(chain.epoch_PRF[(chain.m_blockchain[-1].blockheader.blocknumber+1)-(epoch*10000)], reveals)
if f.stake == True:
if chain.mining_address in [s[0] for s in chain.stake_list_get()]:
f.send_stake_reveal_two(winner)
if chain.mining_address in [s[0] for s in chain.stake_reveal_one]:
for t in chain.stake_reveal_one:
print t[0], chain.mining_address
if t[0]==chain.mining_address:
if t[2]==chain.m_blockchain[-1].blockheader.blocknumber+1:
our_reveal = t[3]
reactor.callIDR2 = reactor.callLater(15, reveal_three_logic, winner=winner, reveals=reveals, our_reveal=our_reveal)
return
reactor.callIDR2 = reactor.callLater(15, reveal_three_logic, winner=winner, reveals=reveals)
return
# here ~30s after last block..
# collate the R2 messages to see if we are creating the block by network consensus..
def reveal_three_logic(winner, reveals, our_reveal=None):
printL(( 'reveal_three_logic:'))
# rank the received votes for winning reveal_one hashes
if not pos_d(chain.m_blockchain[-1].blockheader.blocknumber+1, chain.m_blockchain[-1].blockheader.headerhash):
printL (( "POS_d failed to make consensus at R2 " ))
restart_post_block_logic()
printL(( 'R2 CONSENSUS:', chain.pos_d[1],'/', chain.pos_d[2],'(', chain.pos_d[3],'%)', 'voted/staked emission %:', chain.pos_d[6],'v/s ', chain.pos_d[4]/100000000.0, '/', chain.pos_d[5]/100000000.0 ,'for: ', chain.pos_d[0] ))
if f.stake == True:
if chain.mining_address in [s[0] for s in chain.stake_list_get()]:
f.send_stake_reveal_three(chain.pos_d[0])
reactor.callIDR3 = reactor.callLater(15, reveal_four_logic, reveals, our_reveal)
return
def reveal_four_logic(reveals, our_reveal):
printL(('reveal_four_logic: '))
if pos_consensus(chain.m_blockchain[-1].blockheader.blocknumber+1, chain.m_blockchain[-1].blockheader.headerhash) == False:
#failure recovery entry here..
reset_everything()
printL(('pos_consensus() is false: failure recovery mode..'))
restart_post_block_logic()
return
printL(( 'R3 CONSENSUS:', chain.pos_consensus[1],'/', chain.pos_consensus[2],'(', chain.pos_consensus[3],'%)', 'voted/staked emission %:', chain.pos_consensus[6],'v/s ', chain.pos_consensus[4]/100000000.0, '/', chain.pos_consensus[5]/100000000.0 ,'for: ', chain.pos_consensus[0] ))
if consensus_rules_met() == False:
reset_everything()
restart_post_block_logic()
return
chain.pos_flag = [chain.m_blockchain[-1].blockheader.blocknumber+1, chain.m_blockchain[-1].blockheader.headerhash] #set POS flag for block logic sync..
if our_reveal == chain.pos_consensus[0]:
printL(( 'CHOSEN BLOCK SELECTOR'))
f.sync = 1
f.partial_sync = [0, 0]
reactor.callLater(10, create_new_block, our_reveal, reveals)
return
printL(( 'CONSENSUS winner: ', chain.pos_consensus[7], 'hash ', chain.pos_consensus[0]))
printL(( 'our_reveal', our_reveal))
#reactor.ban_staker = reactor.callLater(25, ban_staker, chain.pos_consensus[7])
global last_pos_cycle
last_pos_cycle = time.time()
return
def ban_staker(stake_address):
del chain.stake_reveal_one[:] # as we have just created this there can be other messages yet for next block, safe to erase
del chain.stake_reveal_two[:]
del chain.stake_reveal_three[:]
chain.ban_stake(stake_address)
return
# consensus rules..
def consensus_rules_met():
if chain.pos_consensus[3] >= 75:
if chain.pos_consensus[6] >= 75:
return True
printL(( 'Network consensus inadequate..rejected'))
return False
# create new block..
def create_new_block(winner, reveals):
printL(( 'create_new_block'))
tx_list = []
for t in chain.transaction_pool:
tx_list.append(t.txhash)
block_obj = chain.create_stake_block(tx_list, winner, reveals)
if chain.m_add_block(block_obj) is True:
stop_all_loops()
del chain.stake_reveal_one[:] # as we have just created this there can be other messages yet for next block, safe to erase
del chain.stake_reveal_two[:]
del chain.stake_reveal_three[:]
f.send_block_to_peers(block_obj) # relay the block
else:
printL(( 'bad block'))
return
# if staking
restart_post_block_logic()
return
def pos_missed_block(data=None):
printL(( '** Missed block logic ** - trigger m_blockheight recheck..'))
f.get_m_blockheight_from_peers()
f.send_m_blockheight_to_peers()
return
def reset_everything(data=None):
printL(( '** resetting loops and emptying chain.stake_reveal_one, reveal_two, chain.pos_d and chain.expected_winner '))
stop_all_loops()
del chain.stake_reveal_one[:]
del chain.stake_reveal_two[:]
del chain.stake_reveal_three[:]
del chain.expected_winner[:]
del chain.pos_d[:]
del chain.pos_consensus[:]
del chain.pos_flag[:]
return
def stop_all_loops(data=None):
printL(( '** stopping timing loops **'))
try: reactor.ban_staker.cancel()
except: pass
try: reactor.callIDR15.cancel() #reveal loop
except: pass
try: reactor.callID.cancel() #cancel the ST genesis loop if still running..
except: pass
try: reactor.callIDR3.cancel()
except: pass
try: reactor.callIDR2.cancel()
except: pass
try: reactor.callID2.cancel() #cancel the soon to be re-called missed block logic..
except: pass
return
def stop_pos_loops(data=None):
printL(( '** stopping pos loops and resetting flags **'))
try: reactor.callIDR15.cancel() #reveal loop
except: pass
try: reactor.callIDR3.cancel()
except: pass
try: reactor.callIDR2.cancel()
except: pass
try: reactor.callID.cancel() #cancel the ST genesis loop if still running..
except: pass
# flags
del chain.pos_flag[:]
del chain.pos_d[:]
del chain.pos_consensus[:]
return
def start_all_loops(data=None):
printL(( '** starting loops **'))
reactor.callID2 = reactor.callLater(120, pos_missed_block)
reactor.callIDR15 = reactor.callLater(15, reveal_two_logic)
return
# remove old messages - this is only called when we have just added the last block so we know that messages related to this block and older are no longer necessary..
#chain.stake_reveal_two.append([z['stake_address'],z['headerhash'], z['block_number'], z['reveal_one'], z['nonce'], z['winning_hash']])
#chain.stake_reveal_one.append([z['stake_address'],z['headerhash'], z['block_number'], z['reveal_one'], z['reveal_two'], rkey])
#chain.stake_reveal_three.append([z['stake_address'],z['headerhash'], z['block_number'], z['consensus_hash'], z['nonce2']])
def filter_reveal_one_two(blocknumber = None):
if not blocknumber:
blocknumber = chain.m_blockchain[-1].blockheader.blocknumber
chain.stake_reveal_one = filter(lambda s: s[2] > blocknumber, chain.stake_reveal_one)
chain.stake_reveal_two = filter(lambda s: s[2] > blocknumber, chain.stake_reveal_two)
chain.stake_reveal_three = filter(lambda s: s[2] > blocknumber, chain.stake_reveal_three)
return
def select_blockheight_by_consensus():
global last_selected_height
block_height_counter = Counter()
for s in chain.stake_reveal_three:
block_height_counter[s[2]] += 1
target_block_height = block_height_counter.most_common(1)
if len(target_block_height) == 0:
return None
if last_selected_height == target_block_height[0][0]:
filter_reveal_one_two(last_selected_height)
last_selected_height = select_blockheight_by_consensus()
return last_selected_height
last_selected_height = target_block_height[0][0]
return last_selected_height
# supra factory block logic
# pre block logic..
def pre_block_logic(block_obj):
global isDownloading, next_header_hash, next_block_number, last_pos_cycle, sync_tme, last_bk_time
last_bk_time = time.time()
blocknumber = block_obj.blockheader.blocknumber
headerhash = block_obj.blockheader.headerhash
time_diff = time.time() - last_pos_cycle
try:
if (not isDownloading) and time_diff > 240 and chain.m_blockheight() + 1 < blocknumber:
blocknumber = select_blockheight_by_consensus()
if blocknumber != block_obj.blockheader.blocknumber:
printL (( 'Block number mismatch with consensus | Rejected - ', blocknumber ))
return
target_block_number = next_block_number
target_header_hash = next_header_hash
next_block_number = blocknumber + 1
next_header_hash = headerhash
if not (pos_consensus(target_block_number, target_header_hash)):
printL (( 'Not matched with reveal, skipping block number ', blocknumber ))
return
if chain.pos_consensus[3] < 75 or chain.pos_consensus[6] < 75:
printL (( ' Consensus ', chain.pos_consensus[3] ,'% below 75% for block number ', blocknumber ))
return
pending_blocks[blocknumber] = [None, block_obj, headerhash, None]
printL (( 'Calling downloader from perblocklogic due to block number ', blocknumber ))
printL (( 'Download block from ', chain.m_blockheight()+1 ,' to ', blocknumber-1 ))
isDownloading = True
download_blocks(blocknumber - 1, block_obj.blockheader.prev_blockheaderhash)
elif chain.m_blockheight() + 1 == blocknumber:
if time_diff > 240:
pos_d(chain.m_blockchain[-1].blockheader.blocknumber+1, chain.m_blockchain[-1].blockheader.headerhash)
pos_consensus(chain.m_blockchain[-1].blockheader.blocknumber+1, chain.m_blockchain[-1].blockheader.headerhash)
if chain.m_blockchain[-1].blockheader.headerhash == block_obj.blockheader.prev_blockheaderhash and chain.m_blockchain[-1].blockheader.blocknumber+1 == blocknumber:
received_block_logic(block_obj, time_diff)
else:
printL (( 'next_header_hash and next_block_number didnt match for ', blocknumber ))
printL (( 'Expected next_header_hash ', chain.m_blockchain[-1].blockheader.headerhash, ' received ', block_obj.blockheader.prev_blockheaderhash ))
printL (( 'Expected next_block_number ', chain.m_blockchain[01].blockheader.blocknumber+1, ' received ', blocknumber ))
except Exception as Ex:
printL (( ' Exception by pos_consensus for block number ', blocknumber ))
printL (( Ex ))
return
def received_block_logic(block_obj, time_diff):
global sync_time
if time_diff > 240 and (sync_time ==0 or time.time() - sync_time < 7):
sync_time = time.time()
chain.recent_blocks.append(block_obj)
synchronising_update_chain()
return
sync_time = 0
# rapid logic
if block_obj.blockheader.headerhash == chain.m_blockchain[-1].blockheader.headerhash:
return
if block_obj.blockheader.blocknumber != chain.m_blockheight()+1:
printL(( '>>>BLOCK - out of order - need', str(chain.m_blockheight()+1), ' received ', str(block_obj.blockheader.blocknumber), block_obj.blockheader.headerhash))#, ' from ', self.transport.getPeer().host
f.get_m_blockheight_from_peers()
return
if block_obj.blockheader.prev_blockheaderhash != chain.m_blockchain[-1].blockheader.headerhash:
printL(( '>>>WARNING: FORK..'))
return
# pos checks
if block_obj.blockheader.blocknumber > 1:
if block_meets_consensus(block_obj.blockheader) != True:
return
# validation and state checks, then housekeeping
if chain.m_add_block(block_obj) is True:
f.send_block_to_peers(block_obj)
restart_post_block_logic()
return
def restart_post_block_logic(delay = 0):
try: reactor.post_block_logic.cancel()
except Exception: pass
reactor.post_block_logic = reactor.callLater(delay, post_block_logic)
# post block logic we initiate the next POS cycle, send R1, send ST, reset POS flags and remove unnecessary messages in chain.stake_reveal_one and _two..
def post_block_logic():
stop_all_loops()
start_all_loops()
filter_reveal_one_two()
del chain.pos_flag[:]
del chain.pos_d[:]
del chain.expected_winner[:]
if f.stake == True:
if chain.mining_address in [s[0] for s in chain.stake_list_get()]:
f.send_stake_reveal_one()
if chain.mining_address not in [s[0] for s in chain.next_stake_list_get()]:
f.send_st_to_peers(chain.CreateStakeTransaction())
wallet.f_save_winfo()
return
# network consensus rules set here for acceptable stake validator counts and weight based upon address balance..
# to be updated..
def block_meets_consensus(blockheader_obj):
#if len(chain.pos_flag)==0:
# printL(( 'POS reveal_three_logic not activated..'))
# return False
#if chain.pos_flag[0]!=blockheader_obj.blocknumber or chain.pos_flag[1]!=blockheader_obj.prev_blockheaderhash:
if chain.m_blockchain[-1].blockheader.blocknumber+1!=blockheader_obj.blocknumber or chain.m_blockchain[-1].blockheader.headerhash!=blockheader_obj.prev_blockheaderhash:
printL(( 'POS reveal_three_logic not activated for this block..'))
return False
#printL(( 'CONSENSUS:', chain.pos_d[1],'/', chain.pos_d[2],'(', chain.pos_d[3],'%)', 'voted/staked emission %:', chain.pos_d[6], ' for: ', chain.pos_d[0]
# check consensus rules..stake validators have to be in 75% agreement or if less then 75% of funds have to be agreement..
if consensus_rules_met() is False:
return False
# is it the correct winner?
if blockheader_obj.hash != chain.pos_d[0]:
printL(( 'Winning hash does not match consensus..rejected'))
return False
if blockheader_obj.stake_selector != chain.pos_d[7]:
printL(( 'Stake selector does not match consensus..rejected'))
return False
return True
# synchronisation functions.. use random sampling of connected nodes to reduce chatter between nodes..
def get_synchronising_blocks(block_number):
f.sync = 0
f.requested[1] += 1
stop_all_loops()
behind = block_number-chain.m_blockheight()
peers = len(f.peers)
if f.requested[0] == chain.m_blockheight()+1:
if f.requested[1] <= len(f.peers):
return
printL(( 'local node behind connection by ', behind, 'blocks - synchronising..'))
f.requested = [chain.m_blockheight()+1, 0]
f.get_block_n_random_peer(chain.m_blockheight()+1)
return
def download_blocks(block_number, last_block_headerhash):
global pending_blocks
random_peer = random.choice(f.peers)
random_host = random_peer.transport.getHost()
block_monitor = reactor.callLater(15, randomize_block_call, block_number)
pending_blocks[block_number] = [random_host.host+":"+str(random_host.port), None, last_block_headerhash, block_monitor]
random_peer.fetch_block_n(block_number)
def randomize_block_call(block_number):
if not pending_blocks[block_number][1]:
random_peer = random.choice(f.peers)
random_host = random_peer.transport.getHost()
last_block_headerhash = pending_blocks[block_number][2]
block_monitor = reactor.callLater(15, randomize_block_call, block_number)
pending_blocks[block_number] = [random_host.host+":"+str(random_host.port), None, last_block_headerhash, block_monitor]
random_peer.fetch_block_n(block_number)
def synchronising_update_chain(data=None):
printL(( 'sync update chain'))
chain.recent_blocks.sort(key=lambda x: x.blockheader.blocknumber) # sort the contents of the recent_blocks pool in ascending block number order..
tmp_recent_blocks = []
for b in chain.recent_blocks:
if b.blockheader.blocknumber != chain.m_blockheight()+1:
printL(( 'Received Block ', b.blockheader.blocknumber , ' expected block number ', chain.m_blockheight()+1 ))
pass
else:
if b.blockheader.prev_blockheaderhash != chain.m_blockchain[-1].blockheader.headerhash:
printL(( 'potential fork..block hashes do not fit, discarded'))
continue #forked blocks?
else:
chain.m_add_block(b, new=0)
if b.blockheader.blocknumber <= chain.m_blockheight():
continue
tmp_recent_blocks.append(b)
chain.recent_blocks = tmp_recent_blocks
del chain.recent_blocks[:]
f.get_m_blockheight_from_random_peer()
return
# blockheight map for connected nodes - when the blockheight seems up to date after a sync or error, we check all connected nodes to ensure all on same chain/height..
# note - may not return correctly during a block propagation..
# once working alter to identify fork better..
def blockheight_map():
#i = [block_number, headerhash, self.transport.getPeer().host]
printL(( 'blockheight_map:'))
printL(( chain.blockheight_map))
# first strip out any laggards..
chain.blockheight_map = filter(lambda s: s[0]>=chain.m_blockheight(), chain.blockheight_map)
bmap_fail = 0
# next identify any node entries which are not exactly correct..
for s in chain.blockheight_map:
if s[0]==chain.m_blockheight() and s[1]==chain.m_blockchain[-1].blockheader.headerhash:
printL(( 'node: ', s[2], '@', s[0], 'w/:', s[1], 'OK'))
elif s[0] > chain.m_blockheight():
printL(( 'warning..', s[2], 'at blockheight', s[0]))
bmap_fail = 1
# wipe it..
del chain.blockheight_map[:]
if bmap_fail == 1:
return False
return True
# rank the winning hashes for the current block number, by number, by address balance and both..after receipt of each valid R2 msg
def pos_d(block_number, headerhash):
#chain.stake_reveal_one.append([stake_address, headerhash, block_number, reveal_one, reveal_two])
#chain.stake_reveal_two.append([stake_address, headerhash, block_number, reveal_one, nonce, winning_hash, reveal_three] rkey2
p = []
l = []
curr_time = int(time.time()*1000)
global r2_time_diff
r2_time_diff[chain.m_blockchain[-1].blockheader.blocknumber+1] = map(lambda t2: curr_time - t2, r2_time_diff[chain.m_blockchain[-1].blockheader.blocknumber+1])
for s in chain.stake_reveal_two:
if s[1]==headerhash and s[2]==block_number:
p.append(chain.state_balance(s[0]))
l.append([chain.state_balance(s[0]),s[5]])
if len(p) <= 1:
return False
total_staked = sum(p)
total_voters = len(l)
c = Counter([s[1] for s in l]).most_common(2) #list containing tuple count of (winning hash, count) - first two..
# all votes same..should be this every time
if len(c) != 1 :
printL(( 'warning, more than one winning hash is being circulated by incoming R2 messages..'))
stake_address = None
for s in chain.stake_reveal_one:
if s[3]==c[0][0]:
stake_address = s[0]
if not stake_address:
return False
percentage_a = decimal.Decimal(c[0][1])/decimal.Decimal(total_voters)*100 #percentage of voters choosing winning hash
total_voted=0
for s in l:
if s[1]==c[0][0]:
total_voted+=s[0]
percentage_d = decimal.Decimal(total_voted)/decimal.Decimal(total_staked)*100
chain.pos_d = [c[0][0], c[0][1], total_voters, percentage_a, total_voted, total_staked, percentage_d, stake_address]
return True
# rank the consensus hashes..
def pos_consensus(block_number, headerhash):
#chain.stake_reveal_three.append([stake_address,headerhash, block_number, consensus_hash, nonce2])
p = []
l = []
for s in chain.stake_reveal_three:
if s[1]==headerhash and s[2]==block_number:
p.append(chain.state_balance(s[0]))
l.append([chain.state_balance(s[0]),s[3]])
if len(p) <= 1:
return False
total_staked = sum(p)
total_voters = len(l)
c = Counter([s[1] for s in l]).most_common(2) #list containing tuple count of (winning hash, count) - first two..
# all votes same..should be this every time
if len(c) != 1 :
printL(( 'warning, more than one consensus_hash is being circulated by incoming R2 messages..'))
stake_address = None
for s in chain.stake_reveal_one:
if s[3]==c[0][0]:
stake_address = s[0]
if not stake_address:
return False
percentage_a = decimal.Decimal(c[0][1])/decimal.Decimal(total_voters)*100 #percentage of voters choosing winning hash
total_voted=0
for s in l:
if s[1]==c[0][0]:
total_voted+=s[0]
percentage_d = decimal.Decimal(total_voted)/decimal.Decimal(total_staked)*100
chain.pos_consensus = [c[0][0], c[0][1], total_voters, percentage_a, total_voted, total_staked, percentage_d, stake_address]
return True
# factories and protocols..
class ApiProtocol(Protocol):
def __init__(self):
pass
def parse_cmd(self, data):
data = data.split() #typical request will be: "GET /api/{command}/{parameter} HTTP/1.1"
#printL(( data
if len(data) == 0: return
if data[0] != 'GET' and data[0] != 'OPTIONS':
return False
if data[0] == 'OPTIONS':
http_header_OPTIONS = ("HTTP/1.1 200 OK\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Access-Control-Allow-Methods: GET\r\n"
"Access-Control-Allow-Headers: x-prototype-version,x-requested-with\r\n"
"Content-Length: 0\r\n"
"Access-Control-Max-Age: 2520\r\n"
"\r\n")
self.transport.write(http_header_OPTIONS)
return
data = data[1][1:].split('/')
if data[0].lower() != 'api':
return False
if len(data) == 1:
data.append('')
if data[1] == '':
data[1] = 'empty'
if data[1].lower() not in api_list: #supported {command} in api_list
error = {'status': 'error', 'error': 'supported method not supplied', 'parameter' : data[1] }
self.transport.write(chain.json_print_telnet(error))
return False
my_cls = ApiProtocol() #call the command from api_list directly
api_call = getattr(my_cls, data[1].lower())
if len(data) < 3:
json_txt = api_call()
#self.transport.write(api_call())
else:
json_txt = api_call(data[2])
#self.transport.write(api_call(data[2]))
http_header_GET = ("HTTP/1.1 200 OK\r\n"
"Content-Type: application/json\r\n"
"Content-Length: %s\r\n"
"Access-Control-Allow-Headers: x-prototype-version,x-requested-with\r\n"
"Access-Control-Max-Age: 2520\r\n"
"Access-Control-Allow-Origin: *\r\n"
"Access-Control-Allow-Methods: GET\r\n"
"\r\n") % (str(len(json_txt)))
self.transport.write(http_header_GET+json_txt)
return
def exp_win(self, data=None):
printL(( '<<< API expected winner call'))
return chain.exp_win(data)
def ping(self, data=None):
printL(( '<<< API network latency ping call'))
f.ping_peers() # triggers ping for all connected peers at timestamp now. after pong response list is collated. previous list is delivered.
pings = {}
pings['status'] = 'ok'
pings['peers'] = {}
pings['peers'] = chain.ping_list
return chain.json_print_telnet(pings)
def stakers(self, data=None):
printL(( '<<< API stakers call'))
return chain.stakers(data)
def next_stakers(self, data=None):
printL(( '<<< API next_stakers call'))
return chain.next_stakers(data)
def stake_commits(self, data=None):
printL(( '<<< API stake_commits call'))
return chain.stake_commits(data)
def stake_reveals(self, data=None):
printL(( '<<< API stake_reveals call'))
return chain.stake_reveals(data)
def stake_reveal_ones(self, data=None):
printL(( '<<< API stake_reveal_ones'))
return chain.stake_reveal_ones(data)
def richlist(self,data=None):
printL(( '<<< API richlist call'))
return chain.richlist(data)
def last_block(self, data=None):
printL(( '<<< API last_block call'))
return chain.last_block(data)
def last_tx(self, data=None):
printL(( '<<< API last_tx call'))
return chain.last_tx(data)
def ip_geotag(self, data=None):
printL(( '<<< API ip_geotag call'))
f.ip_geotag_peers()
return chain.ip_geotag(data)
def empty(self, data=None):
error = {'status': 'error','error' : 'no method supplied', 'methods available' : 'block_data, stats, txhash, address, last_tx, last_block, richlist, ping, stake_commits, stake_reveals, stakers, next_stakers'}
return chain.json_print_telnet(error)
def block_data(self, data=None): # if no data = last block ([-1]) #change this to add error..
error = {'status': 'error', 'error' : 'block not found', 'method': 'block_data', 'parameter' : data}
printL(( '<<< API block data call', data ))
if not data:
#return chain.json_printL((_telnet(chain.m_get_last_block())
data = chain.m_get_last_block()
data1 = copy.deepcopy(data)
data1.status = 'ok'
return chain.json_print_telnet(data1)
try: int(data) # is the data actually a number?
except:
return chain.json_print_telnet(error)
#js_bk = chain.json_printL((_telnet(chain.m_get_block(int(data)))
js_bk = chain.m_get_block(int(data))
#if js_bk == 'false':
if js_bk == False:
return chain.json_print_telnet(error)
else:
js_bk1 = copy.deepcopy(js_bk)
js_bk1.status = 'ok'
js_bk1.blockheader.block_reward = js_bk1.blockheader.block_reward/100000000.000000000
return chain.json_print_telnet(js_bk1)
def stats(self, data=None):
printL(( '<<< API stats call'))
# calculate staked/emission %
b=0
for s in chain.stake_list_get():
b+=chain.state_balance(s[0])
staked = decimal.Decimal((b/100000000.000000000)/(chain.db.total_coin_supply()/100000000.000000000)*100).quantize(decimal.Decimal('1.00')) #/100000000.000000000)
staked = float(str(staked))
# calculate average blocktime over last 100 blocks..
z=0
t = []
for b in reversed(chain.m_blockchain[-100:]):
if b.blockheader.blocknumber > 0:
x = b.blockheader.timestamp-chain.m_blockchain[b.blockheader.blocknumber-1].blockheader.timestamp
t.append(x)
z+=x
#printL(( 'mean', z/len(chain.m_blockchain[-100:]), 'max', max(t), 'min', min(t), 'variance', max(t)-min(t)
net_stats = {'status': 'ok', 'version': version_number, 'block_reward' : chain.m_blockchain[-1].blockheader.block_reward/100000000.00000000, 'stake_validators' : len(chain.m_blockchain[-1].blockheader.reveal_list), 'epoch' : chain.m_blockchain[-1].blockheader.epoch, 'staked_percentage_emission' : staked , 'network' : 'qrl testnet', 'network_uptime': time.time()-chain.m_blockchain[1].blockheader.timestamp,'block_time' : z/len(chain.m_blockchain[-100:]), 'block_time_variance' : max(t)-min(t) ,'blockheight' : chain.m_blockheight(), 'nodes' : len(f.peers)+1, 'emission': chain.db.total_coin_supply()/100000000.000000000, 'unmined' : 21000000-chain.db.total_coin_supply()/100000000.000000000 }
return chain.json_print_telnet(net_stats)
def txhash(self, data=None):
printL(( '<<< API tx/hash call', data))
return chain.search_txhash(data)
def address(self, data=None):
printL(( '<<< API address call', data))
return chain.search_address(data)
def dataReceived(self, data=None):
self.parse_cmd(data)
self.transport.loseConnection()
def connectionMade(self):
self.factory.connections += 1
#printL(( '>>> new API connection'
def connectionLost(self, reason):
#printL(( '<<< API disconnected'
self.factory.connections -= 1
def latency(self, type=None):
output = {}
if type and type.lower() in ['mean', 'median', 'last']:
for block_num in chain.stake_validator_latency.keys():
output[block_num] = {}
for stake in chain.stake_validator_latency[block_num].keys():
time_list = chain.stake_validator_latency[block_num][stake]
print time_list
output[block_num][stake] = {}
if type.lower()=='mean':
output[block_num][stake]['r1_time_diff'] = statistics.mean(time_list['r1_time_diff'])
if 'r2_time_diff' in time_list:
output[block_num][stake]['r2_time_diff'] = statistics.mean(time_list['r2_time_diff'])
elif type.lower()=='last':
output[block_num][stake]['r1_time_diff'] = time_list['r1_time_diff'][-1]
if 'r2_time_diff' in time_list:
output[block_num][stake]['r2_time_diff'] = time_list['r2_time_diff'][-1]
elif type.lower()=='median':
output[block_num][stake]['r1_time_diff'] = statistics.median(time_list['r1_time_diff'])
if 'r2_time_diff' in time_list:
output[block_num][stake]['r2_time_diff'] = statistics.median(time_list['r2_time_diff'])
else:
output = chain.stake_validator_latency
output = json.dumps(output)
return output
class WalletProtocol(Protocol):
def __init__(self):
pass
def parse_cmd(self, data):
data = data.split()
args = data[1:]
if len(data) != 0:
if data[0] in cmd_list:
if data[0] == 'getnewaddress':
self.getnewaddress(args)
return
if data[0] == 'hexseed':
for c in chain.my:
if type(c[1])== list:
pass
else:
if c[1].type == 'XMSS':
self.transport.write('Address: '+ c[1].address+'\r\n')
self.transport.write('Recovery seed: '+c[1].hexSEED+'\r\n')
return
if data[0] == 'seed':
for c in chain.my:
if type(c[1])== list:
pass
else:
if c[1].type == 'XMSS':
self.transport.write('Address: '+ c[1].address+'\r\n')
self.transport.write('Recovery seed: '+c[1].mnemonic+'\r\n')
return
elif data[0] == 'search':
if not args:
self.transport.write('>>> Usage: search <txhash or Q-address>'+'\r\n')
return
for result in chain.search_telnet(args[0], long=0):
self.transport.write(result+'\r\n')
return