-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathstatus.py
executable file
·2332 lines (1910 loc) · 89.6 KB
/
status.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
#!/usr/bin/python3
import sys,os,curses,json,time,select,random,threading,urllib.request,contextlib
from datetime import datetime,timedelta,timezone
from collections import namedtuple
from configparser import ConfigParser
import platform,subprocess,re,getopt
import requests,hmac,hashlib,base64
import math
peer_blacklist = []
peer_wrong_chain = []
purse_uref = 0;
global_events = dict()
peer_address = None
finality_signatures = []
missing_validators = []
proposers_dict = dict()
our_blocks = dict()
currentProposerBlock = 0
blocks_start = 0
era_rewards_dict = dict()
num_era_rewards = dict()
era_block_start = dict()
our_rewards = []
cpu_usage = []
transfer_dict = dict()
trusted_blocked = []
deploy_dict = dict()
peer_scan_dict = dict()
peer_scan_running = False
peer_scan_last_run = None
our_era_rewards = dict()
reactor_state = None
millnames = ['',' K',' M',' B',' T']
def millify(n):
n = float(n)
millidx = max(0,min(len(millnames)-1, int(math.floor(0 if n == 0 else math.log10(abs(n))/3))))
return '${:.1f}{}'.format(n / 10**(3 * millidx), millnames[millidx])
def system_memory():
global sysmemory
sysmemory = curses.newwin(5, 40, 0, 70)
sysmemory.box()
box_height, box_width = sysmemory.getmaxyx()
text_width = box_width - 17 # length of the Text before it gets printed
sysmemory.addstr(0, 2, 'System Memory', curses.color_pair(4))
MemInfoEntry = namedtuple('MemInfoEntry', ['value', 'unit'])
meminfo = {}
with open('/proc/meminfo') as file:
for line in file:
key, value, *unit = line.strip().split()
meminfo[key.rstrip(':')] = MemInfoEntry(value, unit)
sysmemory.addstr(1, 2, 'Mem Total : ', curses.color_pair(1))
sysmemory.addstr('{:.2f} GB'.format(float(meminfo['MemTotal'].value)/1024/1024), curses.color_pair(4))
sysmemory.addstr(2, 2, 'Mem Avail : ', curses.color_pair(1))
sysmemory.addstr('{:.2f} GB'.format(float(meminfo['MemAvailable'].value)/1024/1024), curses.color_pair(4))
mem_total = float(meminfo['MemTotal'].value)
mem_percent = 100*(mem_total-float(meminfo['MemAvailable'].value))/mem_total
sysmemory.addstr(3, 2, 'Mem Used', curses.color_pair(1))
for x in range(25):
sysmemory.addstr(3,13+x,' ', curses.color_pair(6))
for x in range(int(mem_percent/4)):
sysmemory.addstr(3,13+x,' ', curses.color_pair(7+int(mem_percent/25)))
sysmemory.addstr(3, 13, '{:.2f} %'.format(mem_percent), curses.color_pair(7+int(mem_percent/25)))
def system_disk():
global sysdisk
sysdisk = curses.newwin(5, 40, 5, 70)
sysdisk.box()
box_height, box_width = sysdisk.getmaxyx()
text_width = box_width - 17 # length of the Text before it gets printed
sysdisk.addstr(0, 2, 'Disk Usage', curses.color_pair(4))
result=os.statvfs(node_path)
block_size=result.f_frsize
total_blocks=result.f_blocks
free_blocks=result.f_bfree
# giga=1024*1024*1024
giga=1000*1000*1000
total_size=total_blocks*block_size/giga
free_size=free_blocks*block_size/giga
sysdisk.addstr(1, 2, 'Total Disk : ', curses.color_pair(1))
sysdisk.addstr('{:.2f} GB'.format(float(total_size)), curses.color_pair(4))
sysdisk.addstr(2, 2, 'Free Space : ', curses.color_pair(1))
sysdisk.addstr('{:.2f} GB'.format(float(free_size)), curses.color_pair(4))
disk_percent = 100*float(total_size-free_size)/float(total_size)
sysdisk.addstr(3, 2, 'Disk Used : ', curses.color_pair(1))
for x in range(25):
sysdisk.addstr(3,13+x,' ', curses.color_pair(6))
for x in range(int(disk_percent/4)):
sysdisk.addstr(3,13+x,' ', curses.color_pair(7+int(disk_percent/25)))
sysdisk.addstr(3, 13, '{:.2f} %'.format(disk_percent), curses.color_pair(7+int(disk_percent/25)))
def get_processor_name():
if platform.system() == "Windows":
return platform.processor()
elif platform.system() == "Darwin":
os.environ['PATH'] = os.environ['PATH'] + os.pathsep + '/usr/sbin'
command ="sysctl -n machdep.cpu.brand_string"
return subprocess.check_output(command).strip()
elif platform.system() == "Linux":
command = "cat /proc/cpuinfo"
all_info = subprocess.check_output(command, shell=True).strip()
for line in all_info.decode('utf-8').split("\n"):
if "model name" in line:
return re.sub( ".*model name.*:", "", line,1)
return ""
def system_cpu():
global syscpu
syscpu = curses.newwin(6, 40, 10, 70)
syscpu.box()
box_height, box_width = syscpu.getmaxyx()
text_width = box_width - 17 # length of the Text before it gets printed
syscpu.addstr(0, 2, 'CPU Usage - ', curses.color_pair(4))
syscpu.addstr('{} Cores'.format(cpu_cores), curses.color_pair(5))
syscpu.addstr(' /', curses.color_pair(4))
syscpu.addstr('{}'.format(cpu_name[:14]), curses.color_pair(5))
result=os.statvfs(node_path)
block_size=result.f_frsize
total_blocks=result.f_blocks
free_blocks=result.f_bfree
# giga=1024*1024*1024
giga=1000*1000*1000
total_size=total_blocks*block_size/giga
free_size=free_blocks*block_size/giga
cpu_checks = [1, 300, 3600, 86400]
index = 1
for key in cpu_checks:
m, s = divmod(key, 60)
h, s = divmod(m, 60)
d, s = divmod(h, 24)
interval = '{}{}'.format(d if d > 0 else h if h > 0 else m if m > 0 else key, 'd' if d > 0 else 'h' if h > 0 else 'm' if m > 0 else 's')
syscpu.addstr(index, 2, 'Polling {} : '.format(interval), curses.color_pair(1))
usage = 0
local_usage = cpu_usage[::-1]
items = 0
if len(local_usage) > 0:
if key == 86400:
usage = sum(local_usage)
items = len(local_usage)
else:
for cpu in local_usage:
usage += cpu
items += 1
if items >= key:
break;
if usage > 0:
usage /= items
for x in range(25):
syscpu.addstr(index,13+x,' ', curses.color_pair(6))
for x in range(int(usage/4)):
syscpu.addstr(index,13+x,' ', curses.color_pair(7+int(usage/25)))
syscpu.addstr(index, 13, '{:.2f}%'.format(usage), curses.color_pair(7+int(usage/25)))
# if len(local_usage) > 0:
# for i in local_usage:
# syscpu.addstr('{},'.format(int(i)), curses.color_pair(5))
index += 1
# syscpu.addstr(2, 2, 'Free Space : ', curses.color_pair(1))
# syscpu.addstr('{:.2f} GB'.format(float(free_size)), curses.color_pair(4))
disk_percent = 100*float(total_size-free_size)/float(total_size)
# syscpu.addstr(3, 2, 'Disk Used : ', curses.color_pair(1))
# for x in range(25):
# syscpu.addstr(3,13+x,' ', curses.color_pair(6))
# for x in range(int(disk_percent/4)):
# syscpu.addstr(3,13+x,' ', curses.color_pair(6+int(disk_percent/25)))
# syscpu.addstr(3, 13, '{:.2f} %'.format(disk_percent), curses.color_pair(11+int(disk_percent/25)))
def casper_transfers():
global transfers_view
max_display = 37
local_events = transfer_dict # make a copy in case our thread tries to stomp
length = len(transfer_dict.keys())
if length > max_display:
length = max_display
transfers_view = curses.newwin(3 + (1 if length < 1 else length), 64, 0, 150)
transfers_view.box()
box_height, box_width = transfers_view.getmaxyx()
text_width = box_width - 17 # length of the Text before it gets printed
transfers_view.addstr(0, 2, 'Casper Transfers', curses.color_pair(4))
transfers_view.addstr(1, 2, ' Block / From uref / To uref / Amount', curses.color_pair(4))
my_uref = 0 if not purse_uref else purse_uref[5:69]
items_2_remove = []
if length < 1:
transfers_view.addstr(2, 2, 'Waiting for next Transfer', curses.color_pair(5))
else:
index = 1
for key in list(sorted(local_events.keys(), reverse=True)):
if index <= max_display:
transfer = local_events[key]
transfers_view.addstr(1+index, 2,'{}'.format(str(transfer[0]).rjust(8, ' ')), curses.color_pair(4))
transfers_view.addstr(' / ', curses.color_pair(4))
source = transfer[2][5:69]
target = transfer[3][5:69]
transfers_view.addstr('{}..{}'.format(source[:4],source[-4:]), curses.color_pair(1 if source != my_uref else 5))
transfers_view.addstr(' / ', curses.color_pair(4))
transfers_view.addstr('{}..{}'.format(target[:4],target[-4:]), curses.color_pair(1 if target != my_uref else 5))
transfers_view.addstr(' / ', curses.color_pair(4))
amount = int(transfer[1])
transfer_string = ''
if (amount > 1000000000):
transfer_string = '{:,.4f} CSPR'.format(amount / 1000000000)
else:
transfer_string = '{:,} mote'.format(amount)
transfers_view.addstr(transfer_string.rjust(20, ' '), curses.color_pair(5))
else:
items_2_remove.append(key)
index += 1
if items_2_remove:
for key in items_2_remove:
del transfer_dict[key]
def casper_deploys():
global deploy_view
box_height, box_width = peers.getmaxyx()
starty = 34+box_height
max_display = main_height - starty - 3
length = len(deploy_dict.keys())
if length > max_display:
length = max_display
if len(deploy_dict.keys()) and length < 1:
length = 1
box_height, box_width = peers.getmaxyx()
deploy_view = curses.newwin(2 + (1 if length < 1 else length), 214, 34+box_height, 0)
deploy_view.box()
box_height, box_width = deploy_view.getmaxyx()
text_width = box_width - 17 # length of the Text before it gets printed
deploy_view.addstr(0, 2, 'Casper Deploys', curses.color_pair(4))
deploy_view.addstr(0, 178, 'Spent - Used = Overage', curses.color_pair(4))
if length < 1:
deploy_view.addstr(1, 2, 'Waiting for next Deploy', curses.color_pair(5))
else:
index = 0
for key in list(sorted(deploy_dict.keys(), reverse=True)):
if index < length:
deploy = deploy_dict[key]
deploy_type = deploy[1]
params = deploy[2]
name = deploy[3]
entry = deploy[4]
result = deploy[5]
error_message = deploy[6]
paid_cost = int(deploy[7])
actual_cost = int(deploy[8])
highlight_color = 2 if result == 'Failure' else 5
base_color = 2 if result == 'Failure' else 4
deploy_view.addstr(1+index, 2,'{}'.format(str(deploy[0]).rjust(8, ' ')), curses.color_pair(2 if result == 'Failure' else 4))
deploy_view.addstr(' / ', curses.color_pair(4))
string = deploy_type
if len(deploy_type) > 11:
string = '{}..{}'.format(deploy_type[:6], deploy_type[-6:])
deploy_view.addstr('{}'.format(string.rjust(14,' ')[:14]), curses.color_pair(highlight_color))
if name:
deploy_view.addstr(' / ', curses.color_pair(4))
deploy_view.addstr('{}: '.format('name'.rjust(12,' ')), curses.color_pair(base_color))
if name == 'caspersign_contract':
name = 'cs_sgn_cntr'
deploy_view.addstr('{}'.format(name.ljust(11, ' ')[:11]), curses.color_pair(highlight_color))
if entry:
deploy_view.addstr(' / ', curses.color_pair(4))
deploy_view.addstr('{}: '.format('entry'.rjust(12,' ')), curses.color_pair(base_color))
if entry == 'store_signature':
entry = 'store_sig'
deploy_view.addstr('{}'.format(entry.ljust(11, ' ')[:11]), curses.color_pair(highlight_color))
amount = 0
param_index = 0
param_area_size = 12
param_clip = 5
for param in params:
param_index += 1
if param_index == 5:
param_area_size = 10
param_clip = 4
if param == 'amount':
amount = int(params[param]) / 1000000000
else:
# deploy_view.addstr(' / ', curses.color_pair(4))
deploy_view.addstr(' / ')
string = str(params[param])
if param == 'delegation_rate':
param = 'd_rate'
elif param == 'validator_public_key':
param = 'val_pub_key'
elif param == 'store_signature':
param = 'store_sig'
elif len(param) > param_area_size:
param = '{}..{}'.format(param[:param_clip], param[-param_clip:])
if param_index > 4:
deploy_view.addstr('{}: '.format(param[:10]), curses.color_pair(1))
else:
deploy_view.addstr('{}: '.format(param.rjust(param_area_size,' ')[:param_area_size]), curses.color_pair(base_color))
if len(string) > 60:
string = '{}..{}'.format(string[:4],string[-4:])
elif len(string) > 11:
string = '{}..{}'.format(string[:5], string[-4:])
if param_index > 4:
deploy_view.addstr('{}'.format(string[:len(string)]), curses.color_pair(highlight_color))
else:
if string == '{}..{}'.format(public_key[:4], public_key[-4:]):
deploy_view.addstr('{}'.format(string.ljust(11,' '))[:11], curses.color_pair(1))
else:
deploy_view.addstr('{}'.format(string.ljust(11,' '))[:11], curses.color_pair(highlight_color))
if amount and len(params) < 6:
deploy_view.move(1+index,212-41-28-4)
deploy_view.addstr(' / ', curses.color_pair(4))
deploy_view.addstr('amount: ', curses.color_pair(base_color))
amount_str = '{:,.2f} CSPR'.format(amount)
deploy_view.addstr('{}'.format(amount_str.rjust(17,' ')[:17]), curses.color_pair(highlight_color))
over_under = paid_cost - actual_cost
if len(params) < 7:
deploy_view.move(1+index,167)
if not error_message:
paid = '{:,.4f}'.format(paid_cost / 1000000000)[:6]
actual = '{:,.4f}'.format(actual_cost / 1000000000)[:6]
diff = '{:+,.4f}'.format(over_under / 1000000000)[:6]
string = ' / paid: ({} - {}) = {} CSPR'.format(paid, actual, diff)
deploy_view.addstr(' / ', curses.color_pair(4))
deploy_view.addstr('paid: (', curses.color_pair(1))
deploy_view.addstr('{}'.format(paid), curses.color_pair(5))
deploy_view.addstr(' - ', curses.color_pair(4))
deploy_view.addstr('{}'.format(actual), curses.color_pair(5))
deploy_view.addstr(') = ', curses.color_pair(1))
deploy_view.addstr('{} CSPR'.format(diff), curses.color_pair(5))
else:
deploy_view.addstr(' / paid: {} {}'.format('{:,.2f}'.format(paid_cost / 1000000000)[:4],error_message[:31]), curses.color_pair(base_color))
index += 1
def casper_bonds():
global bonds
bonds = curses.newwin(11, 40, 0, 110)
bonds.box()
box_height, box_width = bonds.getmaxyx()
text_width = box_width - 17 # length of the Text before it gets printed
bonds.addstr(0, 2, 'Casper Bond Info', curses.color_pair(4))
try:
bids = auction_info['bids']
for item in bids:
if item['public_key'].strip("\"") == public_key:
bond_info = item['bid']
break
try:
staked = float(bond_info['staked_amount'].strip("\""))
except:
staked = 0
try:
inactive = bond_info['inactive']
except:
inactive = False
try:
delegation = bond_info['delegation_rate']
except:
delegation = 0
try:
delegates = bond_info['delegators']
num_delegates = len(delegates)
except:
num_delegates = 0
try:
delegate_stake = 0
for d in delegates:
delegate_stake += float(d['staked_amount'].strip("\""))
except:
delegate_stake = 0
bonds.addstr(1, 2, 'Active : ', curses.color_pair(1))
if inactive:
bonds.addstr('Not Active', curses.color_pair(2 if blink else 20))
else:
bonds.addstr('True', curses.color_pair(4))
bonds.addstr(2, 2, 'Dele % : ', curses.color_pair(1))
bonds.addstr('{} %'.format(delegation), curses.color_pair(4))
bonds.addstr(3, 2, 'Num Dele : ', curses.color_pair(1))
bonds.addstr('{}'.format(num_delegates), curses.color_pair(4))
our_stake_str = '{:,} CSPR'.format(int(staked / 1000000000))
delegate_str = '{:,} CSPR'.format(int(delegate_stake / 1000000000))
total_stake_str = '{:,} CSPR'.format(int((staked + delegate_stake) / 1000000000))
if (last_val_reward > 1000000000):
our_reward_str = '{:,} CSPR'.format(int(last_val_reward / 1000000000))
else:
our_reward_str = '{:,} mote'.format(int(last_val_reward))
if (last_del_reward > 1000000000):
del_reward_str = '{:,} CSPR'.format(int(last_del_reward / 1000000000))
else:
del_reward_str = '{:,} mote'.format(int(last_del_reward))
longest_len = max(len(delegate_str), len(total_stake_str), len(our_reward_str), len(del_reward_str), len(our_stake_str))
bonds.addstr(4, 2, 'Bond : ', curses.color_pair(1))
bonds.addstr('{}'.format(our_stake_str.rjust(longest_len, ' ')), curses.color_pair(4))
bonds.addstr(' {}'.format(millify(int(staked / 1000000000)*float(current_price))), curses.color_pair(1))
bonds.addstr(5, 2, 'Delegate : ', curses.color_pair(1))
bonds.addstr('{}'.format(delegate_str.rjust(longest_len, ' ')), curses.color_pair(4))
bonds.addstr(' {}'.format(millify(int(delegate_stake / 1000000000)*float(current_price))), curses.color_pair(1))
bonds.addstr(6, 2, 'Total : ', curses.color_pair(1))
bonds.addstr('{}'.format(total_stake_str.rjust(longest_len, ' ')), curses.color_pair(4))
bonds.addstr(' {}'.format(millify(int((staked + delegate_stake) / 1000000000)*float(current_price))), curses.color_pair(1))
bonds.addstr(7, 2, '--------- Previous Reward ----------', curses.color_pair(5))
bonds.addstr(8, 2, 'Validator : ', curses.color_pair(1))
reward_percent = last_val_reward/(staked if staked else 1)*12*365
if longest_len > 13:
bonds.addstr('{} {:d}%'.format(our_reward_str.rjust(longest_len, ' '),int(reward_percent*100)), curses.color_pair(4))
else:
bonds.addstr('{} ({:.2%})'.format(our_reward_str.rjust(longest_len, ' '),reward_percent), curses.color_pair(4))
bonds.addstr(9, 2, 'Delegates : ', curses.color_pair(1))
reward_percent = last_del_reward/(delegate_stake if delegate_stake else 1)*12*365
if longest_len > 13:
bonds.addstr('{} {:d}%'.format(del_reward_str.rjust(longest_len, ' '),int(reward_percent*100)), curses.color_pair(4))
else:
bonds.addstr('{} ({:.2%})'.format(del_reward_str.rjust(longest_len, ' '),reward_percent), curses.color_pair(4))
except:
bonds.addstr(1, 2, 'No Bond Info Found', curses.color_pair(1))
class ProposerTask:
def __init__(self):
self._running = True
def terminate(self):
global_events['terminating'] = 1
self._running = False
def run(self):
loaded1stBlock = False
global currentProposerBlock
global blocks_start
while not loaded1stBlock and self._running:
time.sleep(1)
try:
block_info = json.loads(os.popen('casper-client get-block').read())
currentProposerBlock = int(block_info['result']['block']['header']['height'])
loaded1stBlock = True
except:
pass
# now that we have the 1st block... loop back X blocks to get a brief history
xBlocks = 700
lastBlock = currentProposerBlock - xBlocks
if lastBlock < 1:
lastBlock = 0
while currentProposerBlock > lastBlock and self._running:
try:
block_info = json.loads(os.popen('casper-client get-block -b {}'.format(currentProposerBlock)).read())
proposer = block_info['result']['block']['body']['proposer'].strip("\"")
transfers = block_info['result']['block']['body']['transfer_hashes']
deploys = block_info['result']['block']['body']['deploy_hashes']
if proposer in proposers_dict:
proposers_dict[proposer] = proposers_dict[proposer] + 1
else:
proposers_dict[proposer] = 1
if proposer == public_key:
era_id = block_info['result']['block']['header']['era_id']
if era_id in our_blocks:
our_blocks[era_id] = our_blocks[era_id] + 1
else:
our_blocks[era_id] = 1
ProcessDeploy(deploys, currentProposerBlock)
if transfers:
transfer = json.loads(os.popen('casper-client get-block-transfers -b {}'.format(currentProposerBlock)).read())
transfers = transfer['result']['transfers']
block_hash = transfer['result']['block_hash'].strip("\"")
root_hash = block_info['result']['block']['header']['state_root_hash']
for transfer in transfers:
amount = transfer['amount']
source = transfer['source'].strip("\"")
target = transfer['target'].strip("\"")
transfer_dict['{}-{}-{}-{}'.format(str(currentProposerBlock).rjust(8,' '),block_hash,source,target)] = [currentProposerBlock,amount,source,target]
currentProposerBlock -= 1
blocks_start = blocks_start + 1
except:
global_events['proposer loop error'] = 1
time.sleep(2)
pass
def getEraInfo(block, currentEra, update_globals):
block_info = json.loads(os.popen('casper-client get-era-info-by-switch-block -b {}'.format(block)).read())
summary = block_info['result']['era_summary']
if summary != None:
eraInfo = summary['stored_value']['EraInfo']['seigniorage_allocations']
currentEra = int(summary['era_id'])
num_era_rewards[currentEra] = 0
our_era_rewards[currentEra] = 0
era_block_start[currentEra] = block
my_val_reward = 0
my_del_reward = 0
for info in eraInfo:
if 'Delegator' in info:
amount = int(info['Delegator']['amount'])
if currentEra in era_rewards_dict:
era_rewards_dict[currentEra] = era_rewards_dict[currentEra] + amount
else:
era_rewards_dict[currentEra] = amount
num_era_rewards[currentEra] += 1
# now check if it was us
val = info['Delegator']['validator_public_key'].strip("\"")
if val == public_key:
my_del_reward += amount
elif 'Validator' in info:
amount = int(info['Validator']['amount'])
if currentEra in era_rewards_dict:
era_rewards_dict[currentEra] = era_rewards_dict[currentEra] + amount
else:
era_rewards_dict[currentEra] = amount
num_era_rewards[currentEra] += 1
# now check if it was us
val = info['Validator']['validator_public_key'].strip("\"")
if val == public_key:
my_val_reward += amount
our_rewards.append(my_val_reward + my_del_reward)
our_era_rewards[currentEra] = my_val_reward + my_del_reward
global last_val_reward
global last_del_reward
if update_globals or not last_val_reward:
last_val_reward = my_val_reward
last_del_reward = my_del_reward
return currentEra
class EraTask:
def __init__(self):
self._running = True
def terminate(self):
global_events['terminating'] = 1
self._running = False
def run(self):
loaded1stBlock = False
while not loaded1stBlock and self._running:
time.sleep(1)
try:
block_info = json.loads(os.popen('casper-client get-block').read())
currentBlock = int(block_info['result']['block']['header']['height'])
currentEra = int(block_info['result']['block']['header']['era_id'])
era_block_start[currentEra] = currentBlock
loaded1stBlock = True
except:
pass
# now that we have the current era... loop back X eras to get a brief history
xEras = 10
lastEra = currentEra - xEras
while currentBlock > 0 and currentEra > lastEra and self._running:
try:
currentEra = getEraInfo(currentBlock, currentEra, False)
currentBlock = currentBlock - 1
except:
# global_events['era loop error'] = 1
# global_events['era block '] = currentBlock
# time.sleep(2)
pass
def getPeerInfo(ip):
status = None
try:
status = json.loads(os.popen('curl -m 2 -s {}:8888/status'.format(ip)).read())
except:
pass
return status
def getStatusInfo(status,ip):
try:
current_api_version = status['api_version']
current_chain_name = status['chainspec_name']
last_block_added_info = status['last_added_block_info']
current_era_id = last_block_added_info['era_id']
current_height = last_block_added_info['height']
peer_public_key = status['our_public_signing_key']
next_upgrade = status['next_upgrade']
peer_scan_dict[ip] = [peer_public_key,current_api_version,current_chain_name,last_block_added_info,current_era_id,current_height,next_upgrade]
except:
pass
class ScanValidatorsTask:
def __init__(self):
self._running = True
def terminate(self):
global_events['terminating'] = 1
self._running = False
def run(self):
global peer_scan_running
global peer_scan_last_run
while self._running:
# start = time.time()
peer_scan_dict.clear()
status_not_responding = True
while status_not_responding:
try:
peers_info = json.loads(os.popen('curl -s {}:8888/status'.format(localhost)).read())
status_not_responding = False
except:
time.sleep(2)
peer_scan_running = True
getStatusInfo(peers_info,'localhost')
peers = peers_info['peers']
for peer in peers:
address = peer['address']
ip = address[:address.index(':')]
status = getPeerInfo(ip)
if status != None:
getStatusInfo(status,ip)
else:
peer_scan_dict[ip] = None
# end = time.time()
# global_events['scan_time'] = end - start
peer_scan_running = False
peer_scan_last_run = datetime.now(timezone.utc)
time.sleep(900)
class PeersTask:
def __init__(self):
self._running = True
def terminate(self):
global_events['terminating'] = 1
self._running = False
def run(self):
global testing_trusted
while self._running:
working = []
for ip in trusted_blocked:
status = getPeerInfo(ip)
if status:
working.append(ip)
not_working = []
for ip in trusted_ips:
status = getPeerInfo(ip)
if not status:
not_working.append(ip)
for ip in working:
if ip in trusted_blocked:
trusted_blocked.remove(ip)
if ip not in trusted_ips:
trusted_ips.append(ip)
for ip in not_working:
if ip in trusted_ips:
trusted_ips.remove(ip)
if ip not in trusted_blocked:
trusted_blocked.append(ip)
testing_trusted = False
time.sleep(300)
def sha265hmac(data, key):
h = hmac.new(key, data.encode('utf-8'), digestmod=hashlib.sha256)
return base64.b64encode(h.digest()).decode('utf-8')
class CoinList(object):
def __init__(self, access_key, access_secret, endpoint_url='https://trade-api.coinlist.co'):
self.access_key = access_key
self.access_secret = access_secret
self.endpoint_url = endpoint_url
def request(self, method, path, params={}, body={}):
timestamp = str(int(time.time()))
# build the request path with any GET params already included
path_with_params = requests.Request(method, self.endpoint_url + path, params=params).prepare().path_url
json_body = json.dumps(body, separators=(',', ':')).strip()
message = timestamp + method + path_with_params + ('' if not body else json_body)
secret = base64.b64decode(self.access_secret).strip()
signature = sha265hmac(message, secret)
headers = {
'Content-Type': 'application/json',
'CL-ACCESS-KEY': self.access_key,
'CL-ACCESS-SIG': signature,
'CL-ACCESS-TIMESTAMP': timestamp
}
url = self.endpoint_url + path_with_params
r = requests.request(method, url, headers=headers, data=json_body)
return r.json()
class CpuTask:
def __init__(self, max_time_interval):
self._running = True
self._max_time = int(max_time_interval)
def terminate(self):
global_events['terminating'] = 1
self._running = False
def run(self):
last_idle = last_total = 0
initialized = False
while self._running:
with open('/proc/stat') as f:
fields = [float(column) for column in f.readline().strip().split()[1:]]
idle, total = fields[3], sum(fields)
idle_delta, total_delta = idle - last_idle, total - last_total
last_idle, last_total = idle, total
utilisation = 100.0 * (1.0 - idle_delta / total_delta)
if not initialized:
initialized = True
for _ in range(self._max_time):
cpu_usage.append(utilisation)
cpu_usage.append(utilisation)
if len(cpu_usage) > self._max_time:
cpu_usage.pop(0)
time.sleep(1)
class CoinListTask:
def __init__(self):
self._running = True
def terminate(self):
global_events['terminating'] = 1
self._running = False
def run(self):
global current_price
coinlist = CoinList('50883453-345b-4b11-ade9-105ca81c53fd', 'YTxYSY7lXzp7Uq26dXnnPeYSQ2g3JYG1nVP/hmJ9u5eGBS/XXf6OjnnnLr5Nr87GW1upSkVcLDDxxX5hnwaAGA==')
while self._running:
try:
global_events.pop('price_error', None)
coin_info = coinlist.request('GET', '/v1/symbols/CSPR-USD')
current_price = coin_info['symbol']['fair_price'][:-4]
except:
global_events['price_error'] = 1
pass
time.sleep(60)
def ProcessStep(transforms, last_height):
for transform in transforms:
if transform['key'].startswith('era-'):
eraInfo = transform['transform']['WriteEraInfo']['seigniorage_allocations']
currentEra = int(str(transform['key'])[4:])
num_era_rewards[currentEra] = 0
our_era_rewards[currentEra] = 0
era_block_start[currentEra] = last_height
my_val_reward = 0
my_del_reward = 0
for info in eraInfo:
if 'Delegator' in info:
amount = int(info['Delegator']['amount'])
if currentEra in era_rewards_dict:
era_rewards_dict[currentEra] = era_rewards_dict[currentEra] + amount
else:
era_rewards_dict[currentEra] = amount
num_era_rewards[currentEra] += 1
# now check if it was us
val = info['Delegator']['validator_public_key'].strip("\"")
if val == public_key:
my_del_reward += amount
elif 'Validator' in info:
amount = int(info['Validator']['amount'])
if currentEra in era_rewards_dict:
era_rewards_dict[currentEra] = era_rewards_dict[currentEra] + amount
else:
era_rewards_dict[currentEra] = amount
num_era_rewards[currentEra] += 1
# now check if it was us
val = info['Validator']['validator_public_key'].strip("\"")
if val == public_key:
my_val_reward += amount
if (my_val_reward > 1000000000):
global_events['Last Reward'] = '{:,.4f} CSPR'.format(my_val_reward / 1000000000)
else:
global_events['Last Reward'] = '{:,} mote'.format(int(my_val_reward))
if (my_val_reward > 1000000000):
global_events['Our Last Reward'] = '{:,.4f} CSPR'.format(my_val_reward / 1000000000)
else:
global_events['Our Last Reward'] = '{:,} mote'.format(int(my_val_reward))
if (my_del_reward > 1000000000):
global_events['Del Last Reward'] = '{:,.4f} CSPR'.format(my_del_reward / 1000000000)
else:
global_events['Del Last Reward'] = '{:,} mote'.format(int(my_del_reward))
our_rewards.append(my_val_reward + my_del_reward)
our_era_rewards[currentEra] = my_val_reward + my_del_reward
last_del_reward = my_del_reward
last_val_reward = my_val_reward
def ProcessDeploy(deploys, height):
if deploys:
for deploy in deploys:
deploy = deploy.strip("\"")
d = json.loads(os.popen('casper-client get-deploy {}'.format(deploy)).read())
payment = d['result']['deploy']['payment']
session = d['result']['deploy']['session']
results = d['result']['execution_results'][0]['result']
result = None
error_message = None
actual_cost = 0
for r in results:
result = r
actual_cost = results[r]['cost']
if result == 'Failure':
error_message = results[r]['error_message']
break
if session:
for key in session:
if key == 'Transfer' and result != 'Failure':
return
args = None
name = None if 'name' not in session[key] else session[key]['name']
entry = None if 'entry_point' not in session[key] else session[key]['entry_point']
paid_cost = 0
args = payment['ModuleBytes']['args']
if args:
for arg in args:
if arg[0] == 'amount':
paid_cost = arg[1]['parsed']
args = session[key]['args']
if args:
params = dict()
for arg in args:
params[arg[0]] = arg[1]['parsed']
deploy_dict['{}-{}'.format(str(height).rjust(8,' '),deploy)] = [height,key,params,name,entry,result,error_message,paid_cost,actual_cost]
class EventTask:
def __init__(self):
self._running = True
def terminate(self):
global_events['terminating'] = 1
self._running = False
def has_finality(self):
timestamp = datetime.now() - self._time_before_read
if timestamp.seconds > 10 and 'FinalitySignature' in global_events:
return True
return False
def run(self):
global localhost
global round_time
global avg_rnd_time
url = 'http://{}:9999/events/main'.format(localhost)
localhost_active = False
while not localhost_active and self._running:
try:
r = requests.get(url, stream=True)
localhost_active = True
except:
time.sleep(10)
CHUNK = 6 * 1024
partial_line = ""
last_block_time = datetime.now(timezone.utc) + timedelta(seconds=65)
last_height = 0
StepEvents = False
try:
while self._running:
self._time_before_read = datetime.now()
try:
lines = r.iter_lines()
if not lines:
break
except:
os.execv(sys.argv[0], sys.argv)
break;
if self.has_finality():
global_events['FinalitySignature'] = 0
finality_signatures.clear()
first = True
for line in lines:
line = line.decode('utf-8')
if first and len(partial_line):
line = '{}{}'.format(partial_line, line)
partial_line = ""
if line.startswith('data:'):
try:
json_str = json.loads(line[5:])