-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutility.py
1435 lines (1167 loc) · 45.3 KB
/
utility.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
# coding=utf-8
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import csv
import re
import os
import sys
import json
import time
import signal
import shutil
import zipfile
import tarfile
from copy import copy
from hexbytes import HexBytes
import platform
import subprocess
from configparser import ConfigParser
from PIL import Image
from pyzbar import pyzbar
from string import Template
from logger import writeLog, setLogLevel
import click
import urllib.request as urlrequest
import psutil
import qrcode
def HexBytes_to_str(tx):
for t in tx:
if isinstance(tx[t], HexBytes):
tx[t] = tx[t].hex()
def read_json_file(file_abspath):
try:
with open(file_abspath, 'r') as load_f:
info = json.load(load_f)
except Exception as e:
cust_print('read {} fail!exception info is:{}'.format(file_abspath, e), fg='r')
sys.exit(1)
return info
def get_eth_obj(config, obj_type='platon'):
"""
:param obj_type: ppos、platon、pip
:param config: 节点配置文件
:return: Eth对象
"""
# 节点配置文件
if "" == config:
config = os.path.join(g_dict_dir_config["conf_dir"], "node_config.json")
if not os.path.exists(config):
cust_print("The node profile exists:{}, please check it.".format(config), fg='r')
sys.exit(1)
node_conf_info = read_json_file(config)
hrp = node_conf_info["hrp"]
rpcAddress = node_conf_info["rpcAddress"]
chain_id = node_conf_info["chainId"]
if 'lat' == hrp or 'lax' == hrp:
from precompile_lib import Web3, HTTPProvider, Eth, Ppos, Admin, datatypes, Pip
else:
from precompile_lib import Alaya_Web3 as Web3, Alaya_HTTPProvider as HTTPProvider, Alaya_Eth as Eth, \
Alaya_Ppos as Ppos, Alaya_Admin as Admin, Alaya_datatypes as datatypes, Alaya_Pip as Pip
if obj_type == 'platon':
w3 = Web3(HTTPProvider(rpcAddress))
obj = connect_node(w3, Eth)
elif obj_type == 'ppos':
function_name = sys._getframe(1).f_code.co_name
w3 = Web3(HTTPProvider(rpcAddress), chain_id=chain_id)
obj = Ppos(w3)
setattr(obj, 'w3', w3)
if function_name == 'getPackageReward':
setattr(obj, 'hrp', hrp)
elif function_name in ['create', 'update', 'vote', 'declareVersion']:
admin = Admin(w3)
setattr(obj, 'admin', admin)
else:
w3 = Web3(HTTPProvider(rpcAddress), chain_id=chain_id)
obj = Pip(w3)
exclude_list = ['ppos', 'pip']
if obj_type in exclude_list:
setattr(obj, 'datatypes', datatypes)
return obj
def write_QRCode(data, save_path):
"""
QRCode主要功能是用来存待签名信息的
:param data: 需要保存到二维码中的数据
:param save_path: 二维码保存的路径
:return:
"""
# 实例化二维码生成类
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# 设置二维码数据
qr.add_data(data=data)
# 启用二维码颜色设置
qr.make(fit=True)
img = qr.make_image(fill_color="green", back_color="white")
img.save(save_path)
def read_QRCode(abspath):
"""
二维码识别
:param abspath:
:return:
"""
import ast
img = Image.open(abspath)
barcodes = pyzbar.decode(img)
data = []
for barcode in barcodes:
barcodeData = barcode.data.decode("utf-8")
data = [dict(da) for da in ast.literal_eval(barcodeData)]
return data
def get_current_dir():
return os.getcwd()
def get_time_stamp():
'''
获取时间戳
:return:
时间戳字符串:如:20200528
'''
ct = time.time()
local_time = time.localtime(ct)
data_head = time.strftime("%Y%m%d%H%M%S", local_time)
return data_head
g_system = platform.system().lower()
if g_system == "linux":
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# 系统自带的 cmd 和 powershell,在 ANSI 转义序列支持上有一个 Bug,
# 即必须事先使用 os.system("") 之后,才能正常启用转义序列功能
if os.name == "nt":
os.system("")
# 判断ip是否在中国
def ip_in_china():
url = 'http://ip-api.com/json'
try:
result = json.loads(urlrequest.urlopen(url).read())
except:
result = {}
if result and result['status'] == 'success':
return result['countryCode'] == 'CN'
else:
return False
# cli版本
CLI_VERSION = '0.2.0'
CLI_NAME = 'platoncli'
PLATON_NAME = 'platon'
if "windows" == g_system:
PLATON_NAME = "platon.exe"
# default_download_url = "https://github.com/PlatONnetwork/downloads/releases/download" # 默认下载路径
default_download_url = "https://github.com/luo-dahui/downloads/releases/download" # 默认下载路径
# 下载路径
if ip_in_china():
default_download_url = 'http://47.91.153.183'
# 当前目录
g_current_dir = get_current_dir()
g_dict_dir_config = {
"default_download_url": default_download_url, # 默认下载路径
"current_dir": g_current_dir,
"tmpl_dir": os.path.join(g_current_dir, "templates"), # 模板文件路径
"conf_dir": os.path.join(g_current_dir, "config"), # 配置文件路径
"download_cnf_url": os.path.join(default_download_url, "config"),
"download_cnf_name": "download_conf.json", # 下载链接配置文件
"platon_dir": os.path.join(g_current_dir, "platon"), # platon目录
"blskey_dir": os.path.join(os.path.join(g_current_dir, "platon"), "blsKey"), # blskey目录
"nodekey_dir": os.path.join(os.path.join(g_current_dir, "platon"), "nodeKey"), # nodekey目录
"wallet_dir": os.path.join(g_current_dir, "wallet"),
"unsigned_tx_dir": os.path.join(g_current_dir, "unsigned_transaction"),
"signed_tx_dir": os.path.join(g_current_dir, "signed_transaction"),
"wallet_recovery_dir": os.path.join(g_current_dir, "wallet_recovery_dir")
}
g_test_address_info = {
"pri_key": "0x117cbac1f5d481ebf74a642ef7825d03232db812bb6214e088426f966ffed513",
"lat": "lat1a9gps7ckrak7pk7uwhjxaushterge27k0w3l89",
"lax": "lax1a9gps7ckrak7pk7uwhjxaushterge27kqtrsf2",
"atp": "atp1a9gps7ckrak7pk7uwhjxaushterge27kkc88c2",
"atx": "atx1a9gps7ckrak7pk7uwhjxaushterge27ku7mdtq"
}
for x in ['platon', 'config', 'templates']:
tmp_dir = os.path.join(g_current_dir, x)
if not os.path.exists(tmp_dir):
os.mkdir(tmp_dir)
for x in ['blsKey', 'nodeKey', 'log']:
tmp_dir = os.path.join(g_dict_dir_config["platon_dir"], x)
if not os.path.exists(tmp_dir):
os.mkdir(tmp_dir)
start_time = time.time()
def cust_print(fmt, fg=None, bg=None, style=None, level="", saveLog=True):
"""
prints table of formatted text format options
"""
COLCODE = {
'k': 0, # black
'r': 1, # red
'g': 2, # green
'y': 3, # yellow
'b': 4, # blue
'm': 5, # magenta
'c': 6, # cyan
'w': 7 # white
}
FMTCODE = {
'b': 1, # bold
'f': 2, # faint
'i': 3, # italic
'u': 4, # underline
'x': 5, # blinking
'y': 6, # fast blinking
'r': 7, # reverse
'h': 8, # hide
's': 9, # strikethrough
}
# properties
props = []
if isinstance(style, str):
props = [FMTCODE[s] for s in style]
if isinstance(fg, str):
props.append(30 + COLCODE[fg])
if isinstance(bg, str):
props.append(40 + COLCODE[bg])
# display
props = ';'.join([str(x) for x in props])
if props:
print('\x1b[%sm%s\x1b[0m' % (props, fmt))
else:
print(fmt)
if saveLog:
# logging.info(fmt)
LOG_LEVEL = {
None: 'info',
'k': 'info', # black
'g': 'info', # green
'b': 'debug', # blue
'y': 'warning', # yellow
'r': 'error', # red
'm': 'critical', # magenta
'c': 'info', # cyan
'w': 'info' # white
}
# 没有指定日志级别时,以颜色进行界定日志级别
if level == "":
level = LOG_LEVEL[fg]
writeLog(fmt, level)
def set_log_level(level):
setLogLevel(level)
def get_system_info():
system = platform.system().lower()
arch = platform.machine().lower()
if arch in ['armv5l', 'armv6l', 'armv7l']:
arch = 'arm'
elif arch == 'aarch64':
arch = 'arm64'
else:
arch = 'amd64'
return system, arch
# 获取py文件中的帮助信息
def get_cmd_help_by_file(path):
help_info = ""
with open(path, encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
if "@click.command" in line and "help=" in line:
line = line.replace('"', "'")
help_info = line[line.find("help='") + 6:line.find("',")]
# print(help_info)
break
return help_info
def get_submodule_help_by_file(path, fileName):
help_info = ""
filePath = os.path.join(path, fileName)
if not os.path.exists(filePath):
return help_info
with open(filePath, encoding='utf-8') as f:
help_info = f.readline()
return help_info
# 获取命令的usage信息(添加submodule)
def get_command_usage(submodule, isShowSubModule=True):
class CommandUsage(click.Command):
def format_usage(self, ctx, formatter):
if isShowSubModule:
usage = ctx.parent.command_path + ' ' + submodule + ' ' + ctx.command.name
else:
usage = ctx.parent.command_path + ' ' + ctx.command.name
pieces = self.collect_usage_pieces(ctx)
formatter.write_usage(usage, ' '.join(pieces))
return CommandUsage
'''
#############节点模块######################
'''
def get_local_latest_version(version_path, name):
# version_path = os.path.join(conf_dir, version_cnf_name)
try:
with open(version_path, 'r') as load_f:
version_info = json.load(load_f)
latest_version = version_info[name]
except:
cust_print('Unable to get latest version', fg='r')
latest_version = '0.0.0'
return latest_version
'''
# 获取版本号
def get_latest_version(name):
version_path = os.path.join(conf_dir, version_cnf_name)
if not os.path.exists(version_path):
# 从服务器上下载到config目录
version_url = '{0}/{1}/{2}'.format(g_download_url, 'version', version_cnf_name)
try:
cust_print('download version config file: {}'.format(version_url), fg='g')
resp = urlrequest.urlopen(version_url)
with open(os.path.join(conf_dir, version_cnf_name), 'wb') as f:
shutil.copyfileobj(resp, f)
except:
cust_print('Unable to download version config file {0}'.format(version_url), fg='r')
# 从本地的latest.json文件获取
latest_version = get_local_latest_version(version_path, name)
return latest_version
'''
def remove(path):
if os.path.isfile(path) or os.path.islink(path):
os.remove(path)
elif os.path.isdir(path):
shutil.rmtree(path)
else:
raise ValueError("{} is not a file or dir.".format(path))
def Schedule(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 设置下载进度条
f = sys.stdout
pervent = recv_size / totalsize
if pervent > 1:
percent_str = "%.2f%%" % 100
else:
percent_str = "%.2f%%" % (pervent * 100)
n = round(pervent * 50)
s = ('#' * n).ljust(50, '-')
f.write(percent_str.ljust(8, ' ') + '[' + s + ']' + speed_str)
f.flush()
# time.sleep(0.1)
f.write('\r')
# 字节bytes转化K\M\G
def format_size(bytes):
try:
bytes = float(bytes)
kb = bytes / 1024
except:
print("传入的字节格式不对")
return "Error"
if kb >= 1024:
M = kb / 1024
if M >= 1024:
G = M / 1024
return "%.3fG" % G
else:
return "%.3fM" % M
else:
return "%.3fK" % kb
def download_genesis_file(hrp, bForced=False):
download_conf_file = os.path.join(g_dict_dir_config["conf_dir"], g_dict_dir_config["download_cnf_name"])
if not os.path.exists(download_conf_file):
cust_print("download config file is not exist:{}, please check!".format(download_conf_file), fg='r')
sys.exit(1)
try:
with open(download_conf_file, 'r') as load_f:
download_info = json.load(load_f)
download_url = download_info["platon_url"]
if 'atp' == hrp or 'atx' == hrp:
download_url = download_info["alaya_url"]
genesis_name = "{}_genesis.json".format(hrp)
download_url = os.path.join(download_url, genesis_name)
# download_file(download_url, g_dict_dir_config["conf_dir"], dest_file_name="genesis.json")
genesis_tmpl_path = os.path.join(g_dict_dir_config["tmpl_dir"], genesis_name)
is_download = True
if os.path.exists(genesis_tmpl_path):
if not bForced:
confirm = input('The genesis block template file already exists. Would you like to download it again? ['
'Y|y/N|n]: ')
# 是否重新下载
if confirm != 'Y' and confirm != 'y':
is_download = False
return
# 删除创世区块模板文件
remove(genesis_tmpl_path)
if is_download:
download_file(download_url, g_dict_dir_config["tmpl_dir"])
except Exception as e:
cust_print('Failed to download genesis file:{}'.format(e), fg='r')
sys.exit(1)
# cust_print('download genesis config file succeed: {}.'.format(download_url), fg='g')
def download_file(download_url, dest_dir_path, dest_file_name=""):
download_url = download_url.replace("\\", "/")
_, download_file_name = os.path.split(download_url)
try:
cust_print('start to download file:{}'.format(download_url), fg='g')
# resp = urlrequest.urlopen(platon_url)
global start_time
start_time = time.time()
urlrequest.urlretrieve(download_url, download_file_name, Schedule)
except Exception as e:
cust_print('Unable to download file, error message: {}!'.format(e), fg='r')
sys.exit(1)
# 指定保存文件的名称
if "" == dest_file_name:
dest_file_name = download_file_name
# 移动文件
src_path = os.path.join(g_current_dir, download_file_name)
des_path = os.path.join(dest_dir_path, dest_file_name)
shutil.move(src_path, des_path)
cust_print('save file succeed: {}'.format(des_path), fg='g')
# 下载路径
def download_url_config_file():
download_conf_name = g_dict_dir_config["download_cnf_name"]
local_file_path = os.path.join(g_dict_dir_config["conf_dir"], download_conf_name)
if os.path.exists(local_file_path):
confirm = input('The download_conf.json file is exist,'
'Whether to download again the download_conf.json file? [Y|y/N|n]: ')
# 是否下载路径配置文件
if confirm != 'Y' and confirm != 'y':
return local_file_path
download_conf_url = g_dict_dir_config["download_cnf_url"]
download_conf_path = os.path.join(download_conf_url, download_conf_name).replace("\\", "/")
download_file(download_conf_path, g_dict_dir_config["conf_dir"])
cust_print('download config file succeed: {}.'.format(download_conf_path), fg='g')
return local_file_path
# 下载二进制包
def download_binary_tar(network_type="PlatON"):
download_conf_current_path = os.path.join(g_dict_dir_config["conf_dir"],
g_dict_dir_config["download_cnf_name"])
if not os.path.exists(download_conf_current_path):
# 是否下载
confirm = input('The download_conf.json file does not exist,'
'Whether to download the download_conf.json file? [Y|y/N|n]: ')
# 是否下载路径配置文件
if confirm == 'Y' or confirm == 'y':
download_url_config_file()
else:
cust_print('Unable to download platon binary package, '
'error message: The download_conf.json file does not exist!', fg='r')
sys.exit(1)
KEY_TOOL_NAME = get_keytool_name(network_type)
with open(download_conf_current_path, 'r') as load_f:
download_info = json.load(load_f)
download_url = download_info["platon_url"]
if 'alaya' == network_type.lower():
download_url = download_info["alaya_url"]
system, arch = get_system_info()
platon_name = "platon-{}-{}".format(system, arch)
platon_file = "{}.tar.gz".format(platon_name)
platon_url = os.path.join(download_url, platon_file).replace("\\", "/")
try:
cust_print('download platon binary:{}'.format(platon_url), fg='g')
# resp = urlrequest.urlopen(platon_url)
global start_time
start_time = time.time()
urlrequest.urlretrieve(platon_url, platon_file, Schedule)
except Exception as e:
cust_print('Unable to download platon binary package, error message: {}!'.format(e), fg='r')
sys.exit(1)
# 解压
tar_path = os.path.join(g_current_dir, platon_file)
unpack_dir = g_dict_dir_config["platon_dir"]
with tarfile.open(tar_path, mode='r:*') as tar:
# tar.extractall(g_current_dir)
tar.extractall(unpack_dir)
for x in [PLATON_NAME, KEY_TOOL_NAME]:
# src_path = os.path.join(unpack_dir, x)
des_path = os.path.join(unpack_dir, x)
# shutil.move(src_path, des_path)
os.chmod(des_path, 0o755)
# 删除tar文件
remove(tar_path)
# 删除解压路径
# remove(unpack_dir)
# 拷贝模板文件
def copy_template_files():
release_template_path = os.path.join(os.path.split(os.path.realpath(__file__))[0], "templates")
current_template_path = os.path.join(os.getcwd(), "templates")
if release_template_path == current_template_path:
return
temp_file_list = ['platon_cfg.tmpl']
sys_type, _ = get_system_info()
if "linux" == sys_type:
temp_file_list.append('platon_cron.tmpl')
temp_file_list.append('platon_logrotate.tmpl')
# 拷贝模板文件
for y in temp_file_list:
src_file = os.path.join(release_template_path, y)
if not os.path.exists(src_file):
cust_print('template file {} is not exist, please check!'.format(src_file), fg='r')
else:
shutil.copy(src_file, current_template_path)
# 安装节点:二进制文件,模板文件
def install_node(hrp):
network_type = "PlatON"
if 'atp' == hrp or 'atx':
network_type = "Alaya"
# 判断是否已安装
isInstall = check_install_valid(network_type)
whether_install_binary = True
if isInstall:
confirm = input('Binary package installed. Do you want to reinstall? [Y|y/N|n]: ')
if confirm != 'Y' and confirm != 'y':
whether_install_binary = False
if whether_install_binary:
cust_print('Start to install platon binary...', fg='y')
# 下载二进制包并解压
download_binary_tar(network_type)
cust_print('Install platon node successfully.', fg='g')
# 拷贝模板文件
isExist = check_platon_tmpl_exist()
whether_reBuild_tmpl = True
if isExist:
confirm = input('The template file already exists. Do you want to rebuild it? [Y|y/N|n]: ')
if confirm != 'Y' and confirm != 'y':
whether_reBuild_tmpl = False
if whether_reBuild_tmpl:
cust_print('Start to copy platon template files...', fg='y')
# 拷贝模板文件
copy_template_files()
cust_print('copy platon template files successfully.', fg='g')
def check_platon_tmpl_exist():
count = 0
check_max_count = 1
tmpl_file_list = ['platon_cfg.tmpl']
if 'linux' == g_system:
tmpl_file_list.append('platon_cron.tmpl')
tmpl_file_list.append('platon_logrotate.tmpl')
check_max_count = check_max_count + 2
for y in tmpl_file_list:
if os.path.exists('{0}/{1}'.format(g_dict_dir_config["tmpl_dir"], y)):
count += 1
flag = False
if count == check_max_count:
flag = True
return flag
# 检查platon二进制,配置文件是否安装成功
def check_install_valid(network_type="PlatON"):
"""
Check for key files that indicate a valid install that can be updated
"""
count = 0
check_max_count = 2
KEY_TOOL_NAME = get_keytool_name(network_type)
for x in [PLATON_NAME, KEY_TOOL_NAME]:
if os.path.exists('{0}/{1}'.format(g_dict_dir_config["platon_dir"], x)):
count += 1
flag = False
if count == check_max_count:
flag = True
for x in [PLATON_NAME, KEY_TOOL_NAME]:
os.chmod(os.path.join(g_dict_dir_config["platon_dir"], x), 0o755)
return flag
def check_init_keys(blskey_dir=g_dict_dir_config["blskey_dir"],
nodeKey_dir=g_dict_dir_config["nodekey_dir"]):
count = 0
flag = False
check_files = {
'blskey': os.path.join(blskey_dir, 'blskey'),
'blspub': os.path.join(blskey_dir, 'blspub'),
'nodeid': os.path.join(nodeKey_dir, 'nodeid'),
'nodekey': os.path.join(nodeKey_dir, 'nodekey')
}
for name, path in check_files.items():
if os.path.exists(path):
count += 1
if len(check_files) == count:
flag = True
return flag
def check_init_valid():
count = 0
flag = False
check_files = {
'blskey': os.path.join(g_dict_dir_config["blskey_dir"], 'blskey'),
'blspub': os.path.join(g_dict_dir_config["blskey_dir"], 'blspub'),
'nodeid': os.path.join(g_dict_dir_config["nodekey_dir"], 'nodeid'),
'nodekey': os.path.join(g_dict_dir_config["nodekey_dir"], 'nodekey')
}
for name, path in check_files.items():
if not os.path.exists(path):
count += 1
if count > 0:
cust_print(
'You have to initialize platon node, please type `./platoncli init` first', fg='r')
sys.exit(-1)
else:
flag = True
return flag
def get_pid(pname, new_rpc_port=6789):
for proc in psutil.process_iter():
if proc.name() == pname:
list_cmdline = proc.cmdline()
bIsFindRpc = False
for param in list_cmdline:
if bIsFindRpc:
if new_rpc_port == int(param):
return proc.pid
break
if '--rpcport' == param:
bIsFindRpc = True
return None
def write_file(path, content):
with open(path, 'w') as fp:
fp.write(content)
def get_keytool_name(network_type):
KEY_TOOL_NAME = "platonkey"
if "alaya" == network_type.lower():
KEY_TOOL_NAME = "alayakey"
if "windows" == g_system:
KEY_TOOL_NAME = KEY_TOOL_NAME + ".exe"
return KEY_TOOL_NAME
def generate_nodekey(key_dir, hrp):
network_type = "PlatON"
if 'atp' == hrp.lower() or 'atx' == hrp.lower():
network_type = "Alaya"
KEY_TOOL_NAME = get_keytool_name(network_type)
keytool_path = os.path.join(g_dict_dir_config["platon_dir"], KEY_TOOL_NAME)
if not os.path.exists(keytool_path):
cust_print('keytool was not installed, Generate key file fail!', fg='r')
return False
keypair = subprocess.check_output(
[keytool_path, 'genkeypair']).decode('utf8').splitlines()
k_pri = re.findall(r"PrivateKey:(.*)", keypair[0].replace(' ', ''))[0]
k_pub = re.findall(r"PublicKey:(.*)", keypair[1].replace(' ', ''))[0]
write_file(os.path.join(key_dir, 'nodekey'), k_pri)
write_file(os.path.join(key_dir, 'nodeid'), k_pub)
return True
def generate_blskey(key_dir, hrp):
network_type = "PlatON"
if 'atp' == hrp.lower() or 'atx' == hrp.lower():
network_type = "Alaya"
KEY_TOOL_NAME = get_keytool_name(network_type)
keytool_path = os.path.join(g_dict_dir_config["platon_dir"], KEY_TOOL_NAME)
if not os.path.exists(keytool_path):
cust_print('{} was not installed, Generate key file fail!'.format(KEY_TOOL_NAME), fg='r')
return False
blskeypair = subprocess.check_output(
[keytool_path, 'genblskeypair']).decode('utf8').splitlines()
b_pri = re.findall(r"PrivateKey:(.*)",
blskeypair[0].replace(' ', ''))[0]
b_pub = re.findall(r"PublicKey:(.*)",
blskeypair[1].replace(' ', ''))[0]
write_file(os.path.join(key_dir, 'blskey'), b_pri)
write_file(os.path.join(key_dir, 'blspub'), b_pub)
return True
def save_node_conf(ip, rpc_port, hrp, chainId):
# 保存配置文件
'''
node_conf = {
"nodeAddress": ip,
"rpcPort": rpc_port,
"hrp": hrp,
"chainId": chainId
}
'''
node_conf = {
"rpcAddress": "http://{}:{}".format(ip, rpc_port),
"hrp": hrp,
"chainId": chainId
}
node_conf_path = os.path.join(g_dict_dir_config["conf_dir"], "node_config.json")
with open(node_conf_path, 'w') as f:
f.write(json.dumps(node_conf))
return node_conf_path
# 初始化创世区块
def init_genesis_block(hrp, genesis_file_path=""):
# 是否已经初始化
data_path = os.path.join(g_dict_dir_config["platon_dir"], "data")
if os.path.exists(data_path):
confirm = input('The genesis block has been initialized. Is it reinitialized (Y|y/N|n): ')
if confirm != 'Y' and confirm != 'y':
return
else:
# 删除创世区块文件目录
remove(data_path)
if "" == genesis_file_path:
genesis_file_path = os.path.join(g_dict_dir_config["conf_dir"], "genesis.json")
# 启动参数配置
start_config = ConfigParser()
start_config.read(os.path.join(g_dict_dir_config["conf_dir"], 'platon.cfg'))
params_dict = dict(start_config.items('platon'))
if not os.path.exists(genesis_file_path):
genesis_tmpl_path = os.path.join(g_dict_dir_config["tmpl_dir"], "{}_genesis.json".format(hrp))
if not os.path.exists(genesis_tmpl_path):
# 下载genesis模板文件
download_genesis_file(hrp, True)
try:
# get node id
nodeid_file_path = os.path.join(g_dict_dir_config["nodekey_dir"], "nodeid")
with open(nodeid_file_path, "r") as f_n:
nodeid = f_n.read()
# get blsPublicKey
blspub_file_path = os.path.join(g_dict_dir_config["blskey_dir"], "blspub")
with open(blspub_file_path, "r") as f_b:
blspub = f_b.read()
# get ip and port
rpcaddr = params_dict["rpcaddr"]
port = params_dict["port"]
except Exception as e:
cust_print("init genesis block failed, error message:{}".format(e))
sys.exit(1)
# 重新写入key等信息
config = {
'nodeid': nodeid,
'ip': rpcaddr,
"port": port,
"blsPubKey": blspub
}
conf_map = {
'{}_genesis.json'.format(hrp): 'genesis.json'
}
for k, v in conf_map.items():
with open(os.path.join(g_dict_dir_config["tmpl_dir"], k), 'r') as fp_in:
src = Template(fp_in.read())
result = src.substitute(config)
with open(os.path.join(g_dict_dir_config["conf_dir"], v), 'w') as fp_out:
fp_out.write(result)
cmd = '{0}/platon --datadir {1} init {2}'.format(g_dict_dir_config["platon_dir"],
params_dict['datadir'], genesis_file_path)
os.system(cmd)
# 将创世区块文件中的chainid写入node_conf.json文件中
with open(genesis_file_path, 'r') as load_f:
genesis_info = json.load(load_f)
chainId = genesis_info["config"]["chainId"]
save_node_conf(params_dict["rpcaddr"], params_dict["rpcport"], params_dict["hrp"], chainId)
cust_print('Initializing genesis block file successfully: {}.'.format(genesis_file_path), fg='g')
# 初始化节点
def init_node(hrp, is_private_chain=False, config_path=""):
# 安装节点
install_node(hrp)
# cust_print('Warning: Initialize node will regenerate keys if you have initialized before.', fg='y')
confirm = input('Do you want to initialize node (Y|y/N|n): ')
if confirm == 'Y' or confirm == 'y':
if not is_private_chain:
if 'atp' == hrp:
network = '--alaya'
elif 'atx' == hrp:
network = '--alayatestnet'
elif 'lat' == hrp:
network = '--mainnet'
elif 'lax' == hrp:
network = '--testnet'
else:
cust_print('error hrp type:{}!!!'.format(hrp), fg='r')
sys.exit(1)
else:
network = ""
else:
return
config = {
'base_dir': g_current_dir,
'network': network,
'hrp': hrp
}
conf_map = {
'platon_cfg.tmpl': 'platon.cfg'
}
if 'linux' == g_system:
linux_conf_map = {
'platon_cron.tmpl': '.platon_cron',
'platon_logrotate.tmpl': '.platon_logrotate'
}
conf_map.update(linux_conf_map)
cust_print('Generate platon configurations.', fg='y')
try:
for k, v in conf_map.items():
with open(os.path.join(g_dict_dir_config["tmpl_dir"], k), 'r') as fp_in:
src = Template(fp_in.read())
result = src.substitute(config)
with open(os.path.join(g_dict_dir_config["conf_dir"], v), 'w') as fp_out:
fp_out.write(result)
# linux启动定时任务
if 'linux' == g_system:
cmd = '/usr/bin/crontab {0}'.format(
os.path.join(g_dict_dir_config["conf_dir"], '.platon_cron'))
os.system(cmd)
cust_print('Generate platon configurations successfully.', fg='g')
except Exception as e:
cust_print('Failed to generate platon configurations:{}.'.format(e), fg='r')
try:
gen_key_info = True
if check_init_keys():
confirm = input('Blskey and NodeKey are already generated. Do you want to regenerate them? (Y|y/N|n): ')
if confirm != 'Y' and confirm != 'y':
gen_key_info = False
else:
# 重新生成key信息,删除genesis.json
genesis_path = os.path.join(g_dict_dir_config["conf_dir"], "genesis.json")
if is_private_chain and os.path.exists(genesis_path):
remove(genesis_path)
if gen_key_info:
cust_print('start to generate platon keys...', fg='y')
generate_nodekey(g_dict_dir_config["nodekey_dir"], hrp)
generate_blskey(g_dict_dir_config["blskey_dir"], hrp)
cust_print('Generate platon keys successfully.', fg='g')
# 私链初始化创始区块
if is_private_chain:
init_genesis_block(hrp, config_path)
except Exception as e:
cust_print(e, fg='r')
cust_print('Failed to initialize node, error message:{}!!!'.format(e), fg='r')
sys.exit(1)
cust_print('Initialize node successfully', fg='g')
def get_local_platon_cfg(platon_cfg_path=""):
# 检查启动参数配置文件
if "" == platon_cfg_path:
platon_cfg_path = os.path.join(g_dict_dir_config["conf_dir"], 'platon.cfg')
if not os.path.exists(platon_cfg_path):
cust_print('The node startup parameter profile does not exist:{}!!!'.format(platon_cfg_path), fg='r')
sys.exit(1)
config = ConfigParser()
config.read(platon_cfg_path)