def blockNumber(config): """ this is query submodule get blockNumber command. """ platon = get_eth_obj(config) block_number = platon.blockNumber cust_print('{}'.format(block_number), fg='g')
def init(hrp, private_chain, config): """ this is node submodule init command. """ cust_print("Start initializing nodes.", fg='g') init_node(hrp, private_chain, config)
def initGroupParams(args): global cmd_path global short_help global help_info global options_metavar global isSubModule global isCmd isSubModule, isCmd = is_submodule_or_cmd(args) # 初始化cli if isCmd: cmd_path = "{}/".format(code_dir_name) elif isSubModule: # submodule cmd_path = "{}/{}/".format(code_dir_name, args) if args in dict_cmd_help and "" != dict_cmd_help[args]: help_info = dict_cmd_help[args] else: help_info = "this is " + args + " submodule." options_metavar = args else: cust_print( "submodule or command :【{}】 not found, please check!\n".format( sys.argv[1]), fg='r') show_help() sys.exit(1)
def withdrawDelegateReward(address, offline, config, style): """ this is delegate submodule withdrawDelegateReward command. """ wallet_dir = g_dict_dir_config["wallet_dir"] wallet_file_path, private_key, hrp, _ = verify_password(address, wallet_dir) ppos = get_eth_obj(config, 'ppos') _params = {'pri_key': private_key[2:], 'transaction_cfg': None} try: if offline: data = rlp.encode([rlp.encode(int(5000))]) _params['to_type'] = 'delegateReward' transaction_dict = un_sign_data(data, _params, ppos, _params['pri_key']) unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"] check_dir_exits(unsigned_tx_dir) unsigned_file_csv_name = "unsigned_delegate_withdrawDelegateReward_{}.csv".format(get_time_stamp()) unsigned_file_path = os.path.join(unsigned_tx_dir, unsigned_file_csv_name) if style == '': write_csv(unsigned_file_path, [transaction_dict]) else: unsigned_file_path = unsigned_file_path.replace('csv', 'jpg') write_QRCode(transaction_dict, unsigned_file_path) else: tx_hash = ppos.withdrawDelegateReward(*_params.values()) cust_print('delegate withdrawDelegateReward send transfer transaction successful, tx hash:{}.'.format(tx_hash),fg='g') except ValueError as e: cust_print('delegate withdrawDelegateReward send transfer transaction fail,error info:{}'.format(e), fg='r') sys.exit(1)
def update_for_platon(bin_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 is not initialized, please check!:{}'.format( g_current_dir), fg='r') sys.exit(1) platon_cfg = get_local_platon_cfg() # 进程是否在运行 pid = get_pid(PLATON_NAME, int(platon_cfg['rpcport'])) if pid: confirm = input( 'PlatON is running, rpc port:{}, Whether or not to continue? [Y|y/N|n]: ' .format(int(platon_cfg['rpcport']))) # 关闭进程 if confirm == 'Y' or confirm == 'y': shutdown_node() else: cust_print( 'Failed to upgrade platon node!:{}'.format(g_current_dir), fg='r') return # 开始下载,替换 # download_file(download_path, g_dict_dir_config["platon_dir"]) # 已下载到本地,直接替换 old_bin_dir = os.path.join(g_dict_dir_config["platon_dir"], PLATON_NAME) remove(old_bin_dir) shutil.move(bin_path, g_dict_dir_config["platon_dir"]) # 重启节点 startup_node()
def rollback_for_platon(dataPath): 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 is not initialized, please check!:{}'.format(g_current_dir), fg='r') sys.exit(1) platon_cfg = get_local_platon_cfg() # 进程是否在运行 pid = get_pid(PLATON_NAME, int(platon_cfg['rpcport'])) if pid: confirm = input('PlatON is running, rpc port:{}, Whether or not to continue? [Y|y/N|n]: '. format(int(platon_cfg['rpcport']))) # 关闭进程 if confirm == 'Y' or confirm == 'y': shutdown_node() else: cust_print('Failed to rollback platon data!:{}'.format(g_current_dir), fg='r') return confirm = input('Current CLI workspace directory:{}, do you want to continue? [Y|y/N|n]: '. format(g_current_dir)) # 关闭进程 if confirm != 'Y' and confirm != 'y': cust_print('Failed to rollback platon data!:{}'.format(g_current_dir), fg='r') return cust_print('start to rollback node data...:{}'.format(g_current_dir), fg='g') # delete data dir of platon old_data_dir = os.path.join(g_dict_dir_config["platon_dir"], "data") remove(old_data_dir) shutil.move(dataPath, old_data_dir) # 重启节点 startup_node() cust_print("Rollback success...", bg='y')
def getBlockByHash(hash, config): """ this is query submodule get blockNumber info by block hash command. """ platon = get_eth_obj(config) block_info = dict(platon.getBlock(hash)) HexBytes_to_str(block_info) cust_print('{}'.format(json.dumps(block_info, indent=2)), fg='g')
def getPackageReward(config): """ this is query submodule get Package Reward command. """ ppos = get_eth_obj(config, 'ppos') package_reward = ppos.getPackageReward() result = '{} {}'.format(ppos.w3.fromWei(package_reward['Ret'], "ether"), ppos.hrp.upper()) cust_print('Block rewards for the current settlement cycle:{}'.format(result), fg='g')
def getAvgPackTime(config): """ this is query submodule getAvgPackTime command. """ ppos = get_eth_obj(config, 'ppos') average_time = ppos.getAvgPackTime() cust_print('Average time for block packaging:{}s'.format( average_time['Ret'] / 1000), fg='g')
def reportDoubleSign(param, address, offline, config, style): """ this is government submodule reportDoubleSign command. """ if not os.path.isfile(param): cust_print('file {} not exits! please check!'.format(param), fg='r') sys.exit(1) params = read_json_file(param) wallet_dir = g_dict_dir_config["wallet_dir"] _, private_key, _, _ = verify_password(address, wallet_dir) ppos = get_eth_obj(config, 'ppos') try: _params = {'typ': params['type'], 'data': params['data']} except KeyError as e: cust_print( 'reportDoubleSign need params {},but it does not exist,please check!' .format(e), fg='r') sys.exit(1) try: if offline: data = rlp.encode([ rlp.encode(int(3000)), rlp.encode(params['type']), rlp.encode(params['data']) ]) _params['transaction_cfg'] = params.get('transaction_cfg', None) _params['to_type'] = 'penalty' transaction_dict = un_sign_data(data, _params, ppos, private_key[2:]) unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"] check_dir_exits(unsigned_tx_dir) unsigned_file_csv_name = "unsigned_government_reportDoubleSign_{}.csv".format( get_time_stamp()) unsigned_file_path = os.path.join(unsigned_tx_dir, unsigned_file_csv_name) if style == '': write_csv(unsigned_file_path, [transaction_dict]) else: unsigned_file_path = unsigned_file_path.replace('csv', 'jpg') write_QRCode(transaction_dict, unsigned_file_path) cust_print('unsigned_file save to:{}'.format(unsigned_file_path), fg='g') else: _params['pri_key'] = private_key[2:] _params['transaction_cfg'] = params.get('transaction_cfg', None) txhash = ppos.reportDuplicateSign(*_params.values()) cust_print( 'send raw transfer transaction successful, tx hash:{}.'.format( txhash), fg='g') except Exception as e: cust_print( 'government send transfer transaction fail,error info:{}'.format( e), fg='r') sys.exit(1)
def delete(address): """ this is account submodule delete command. """ wallet_dir = g_dict_dir_config["wallet_dir"] cust_print("Start delete wallet file...", fg='g') wallet_file_path, _, _, _ = verify_password(address, wallet_dir) try: os.remove(wallet_file_path) except: cust_print('delete wallet {} fail!!!'.format(wallet_file_path), fg='r') sys.exit(1)
def verify_password(address, wallet_dir, passwd=None): if address.endswith(".json"): config = os.path.join(g_dict_dir_config["conf_dir"], "node_config.json") info = read_json_file(config) find, wallet_file_path = get_dir_by_name(wallet_dir, address) if not find: cust_print('The wallet file of {} could not be found on {}'.format( address, wallet_dir), fg='r') sys.exit(1) try: hrp = info['hrp'] except: cust_print( 'the wallet {} is not alaya or platon,please check!'.format( wallet_file_path), fg='r') sys.exit(1) elif 42 != len(address): cust_print("Wrong address parameter: --address {}".format(address), fg='r') sys.exit(1) else: # 根据地址找钱包 hrp = address[:3] net_type = "mainnet" if hrp == 'lax' or hrp == 'atx': net_type = 'testnet' find, wallet_file_path, fileName = get_wallet_file_by_address( wallet_dir, address, net_type) if not find: cust_print('The wallet file of {} could not be found on {}'.format( fileName, wallet_dir), fg='r') sys.exit(1) check_name = fileName check_address = address cust_print("Name:{}, Address:{}".format(check_name, check_address), fg='g') if not passwd: if 'windows' == g_system: passwd = b''.join(input_passwd_for_win()).decode() else: passwd = input_passwd_for_linux() if 'lat' == hrp or 'lax' == hrp: from precompile_lib import Account, keys else: from precompile_lib import Alaya_Account as Account, Alaya_keys as keys privateKey = get_private_key_from_wallet_file(Account, keys, wallet_file_path, passwd) return wallet_file_path, privateKey, hrp, Account
def get_command(self, ctx, name): namespace = {} command_file = os.path.join(folder, name + '.py') if not os.path.exists(command_file): cust_print( "command:【{}】 is not exist, please check.".format(name), fg='r') show_help() sys.exit(1) with open(command_file, encoding='utf-8') as f: code = compile(f.read(), command_file, 'exec') eval(code, namespace, namespace) return namespace[name.replace('-', '_')]
def getRelatedListByDelAddress(address, config, fromaddress): """ this is delegate submodule getRelatedListByDelAddr command. """ try: ppos = get_eth_obj(config, 'ppos') fromaddress = None if fromaddress.replace(" ", "") == "" else fromaddress result = ppos.getRelatedListByDelAddr(address, fromaddress) for obj in result['Ret']: cust_print('{}'.format(json.dumps(obj, indent=2)), fg='g') except Exception as e: cust_print('Query exception,{}'.format(e), fg='r') sys.exit(1)
def generateNodeKey(keyPath): """ this is node submodule generateNodeKey command. """ if not os.path.exists(keyPath): cust_print("invalid path:{}".format(keyPath), bg='r') return nodeIdPath = os.path.join(keyPath, 'nodeid') nodeKeyPath = os.path.join(keyPath, 'nodekey') if os.path.exists(nodeIdPath) or os.path.exists(nodeKeyPath): confirm = input( 'The key file already exists in the directory. Do you want to overwrite it? [Y|y/N|n]: ' ) if confirm != 'Y' and confirm != 'y': cust_print('Generate node key fail!', fg='r') return platon_cfg_path = os.path.join(g_dict_dir_config["conf_dir"], 'platon.cfg') hrp = 'lat' if os.path.exists(platon_cfg_path): platon_cfg = get_local_platon_cfg() hrp = platon_cfg['hrp'] if generate_nodekey(keyPath, hrp): cust_print('Generate node key success:{}.'.format(keyPath), fg='y') else: cust_print('Generate node key fail!', fg='r')
def vote(param, address, offline, config, style): """ this is government submodule vote command. """ if not os.path.isfile(param): cust_print('file {} not exits! please check!'.format(param), fg='r') sys.exit(1) params = read_json_file(param) try: _params = {'verifier': params['verifier'], 'proposalId': params['proposalId'], 'option': int(params['option'])} except KeyError as e: cust_print('vote need params {},but it does not exist,please check!'.format(e), fg='r') sys.exit(1) wallet_dir = g_dict_dir_config["wallet_dir"] _, private_key, _, _ = verify_password(address, wallet_dir) ppos = get_eth_obj(config, 'ppos') pip = get_eth_obj(config, 'pip') msg = ppos.admin.getProgramVersion() program_version = msg['Version'] version_sign = msg['Sign'] try: if offline: data = rlp.encode( [rlp.encode(int(2003)), rlp.encode(bytes.fromhex(params['verifier'])), rlp.encode(bytes.fromhex(params['proposalId'])), rlp.encode(params['option']), rlp.encode(int(program_version)), rlp.encode(bytes.fromhex(version_sign))]) _params['transaction_cfg'] = params.get('transaction_cfg', None) _params['to_type'] = 'pip' transaction_dict = un_sign_data(data, _params, pip, private_key[2:]) unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"] check_dir_exits(unsigned_tx_dir) unsigned_file_csv_name = "unsigned_government_vote_{}.csv".format(get_time_stamp()) unsigned_file_path = os.path.join(unsigned_tx_dir, unsigned_file_csv_name) if style == '': write_csv(unsigned_file_path, [transaction_dict]) else: unsigned_file_path = unsigned_file_path.replace('csv', 'jpg') write_QRCode(transaction_dict, unsigned_file_path) cust_print('unsigned_file save to:{}'.format(unsigned_file_path), fg='g') else: _params['program_version'] = program_version _params['version_sign'] = version_sign _params['pri_key'] = private_key[2:] _params['transaction_cfg'] = params.get('transaction_cfg', None) txhash = pip.vote(*_params.values()) cust_print('send raw transfer transaction successful, tx hash:{}.'.format(txhash), fg='g') except Exception as e: cust_print('vote send transfer transaction fail,error info:{}'.format(e), fg='r') sys.exit(1)
def info(): """ this is node submodule info command. """ platon_cfg = get_local_platon_cfg() pid = get_pid(PLATON_NAME, int(platon_cfg['rpcport'])) if not pid: cust_print( "The node is not started, rpc port:{}, please check!...".format( int(platon_cfg['rpcport'])), fg='r') return url = "http://{}:{}".format(platon_cfg["rpcaddr"], platon_cfg["rpcport"]) w3 = Web3(HTTPProvider(url)) # 获取节点信息 admin = Admin(w3) nodeId = admin.nodeInfo.id cust_print("NodeId:{}".format(nodeId), fg='g') # NodeName NodeName = "" cust_print("NodeName:{}".format(NodeName), fg='g') # BenefitAddress BenefitAddress = "" cust_print("BenefitAddress:{}".format(BenefitAddress), fg='g')
def getProposal(proposal_id, config, fromaddress): """ this is government submodule getProposal command. """ try: fromaddress = None if fromaddress.replace(" ", "") == "" else fromaddress pip = get_eth_obj(config, 'pip') result = pip.getProposal(proposal_id, fromaddress) cust_print('{}'.format(json.dumps(result['Ret'], indent=2)), fg='g') except Exception as e: cust_print('government getProposal exception,error info:{}'.format(e), fg='r') sys.exit(1)
def GetRestrictingInfo(address, config, fromaddress): """ this is hedge submodule GetRestrictingInfo command. """ try: fromaddress = None if fromaddress.replace(" ", "") == "" else fromaddress ppos = get_eth_obj(config, 'ppos') result = ppos.getRestrictingInfo(address, fromaddress) cust_print('{}'.format(json.dumps(result['Ret'], indent=2)), fg='g') except Exception as e: cust_print( 'hedge GetRestrictingInfo exception,error info:{}'.format(e), fg='r') sys.exit(1)
def getAccuVerifiersCount(proposal_id, hash, config, fromaddress): """ this is government submodule getAccuVerifiersCount command. """ try: fromaddress = None if fromaddress.replace(" ", "") == "" else fromaddress pip = get_eth_obj(config, 'pip') result = pip.getAccuVerifiersCount(proposal_id, hash, fromaddress) cust_print('{}'.format(result['Ret']), fg='g') except Exception as e: cust_print( 'government getGovernParamValue exception,error info:{}'.format(e), fg='r') sys.exit(1)
def getActiveVersion(config, fromaddress): """ this is government submodule getActiveVersion command. """ try: fromaddress = None if fromaddress.replace(" ", "") == "" else fromaddress pip = get_eth_obj(config, 'pip') result = pip.getActiveVersion(fromaddress) cust_print('{}'.format(result['Ret']), fg='g') except Exception as e: cust_print( 'government getActiveVersion exception,error info:{}'.format(e), fg='r') sys.exit(1)
def checkDuplicateSign(type, nodeid, blocknumber, config, fromaddress): """ this is government submodule checkDuplicateSign command. """ try: fromaddress = None if fromaddress.replace(" ", "") == "" else fromaddress ppos = get_eth_obj(config, 'ppos') result = ppos.checkDuplicateSign(int(type), nodeid, blocknumber, fromaddress) cust_print('{}'.format(result), fg='g') except Exception as e: cust_print( 'government checkDuplicateSign exception,error info:{}'.format(e), fg='r') sys.exit(1)
def is_continue(platon_cfg, running_dir): # 进程是否在运行 pid = get_pid(PLATON_NAME, int(platon_cfg['rpcport'])) if pid: confirm = input( 'PlatON is running, rpc port:{}, Whether or not to continue? [Y|y/N|n]: ' .format(int(platon_cfg['rpcport']))) # 关闭进程 if confirm == 'Y' or confirm == 'y': shutdown_node() else: cust_print('Failed to move block data!:{}'.format(running_dir), fg='r') return False return True
def listGovernParam(module, config, fromaddress): """ this is government submodule listGovernParam command. """ try: fromaddress = None if fromaddress.replace(" ", "") == "" else fromaddress pip = get_eth_obj(config, 'pip') result = pip.listGovernParam(module, fromaddress) for obj in result['Ret']: cust_print('{}'.format(json.dumps(obj, indent=2)), fg='g') except Exception as e: cust_print( 'government listGovernParam exception,error info:{}'.format(e), fg='r') sys.exit(1)
def send_offline(data, config): """ this is tx submodule send_offline command. """ signed_tx_dir = g_dict_dir_config["signed_tx_dir"] abspath = os.path.join(signed_tx_dir, data) if not os.path.isfile(abspath): cust_print('{} not exists,please check!'.format(abspath), fg='r') sys.exit(1) try: with open(abspath, 'r') as f: result = f.read() sign_data = ast.literal_eval(result) except: cust_print('analytical exception,please check!', fg='r') sys.exit(1) try: # 发送交易 platon = get_eth_obj(config) tx_hash_list = [] for data in sign_data: txhash, _ = send_transaction(platon, data) tx_hash_list.append(txhash) txhash = ','.join(tx_hash_list) except Exception as e: cust_print( 'send raw transfer transaction failure, error message:{}!!!'. format(e), fg='r') sys.exit(1) else: dir_name = os.path.dirname(abspath) base_name = os.path.basename(abspath) new_base_name = base_name + '.done' os.rename(abspath, os.path.join(dir_name, new_base_name)) cust_print( 'send raw transfer transaction successful, tx hash:{}.'.format( txhash), fg='g') cust_print('send raw transfer transaction successful, {} to {}'.format( base_name, new_base_name), fg='g')
def recovery(types): """ this is account submodule recovery wallet command. """ message = 'Private key:' if types == 'private' else 'Mnemonic code:' if 'windows' == g_system: mp = b''.join(input_passwd_for_win(message)).decode() password = b''.join(input_passwd_for_win()).decode() else: mp = input_passwd_for_linux(message) password = input_passwd_for_linux() if types == 'private': check_private_key = mp[2:] if mp.startswith('0x') else mp try: private_key_obj = crypto.PrivateKey.from_hex(check_private_key) keystores = private_key_obj.to_keyfile_json(password) except Exception as e: cust_print( 'Incorrect private key or password recovery failed!,exception info:{}' .format(e), fg='r') sys.exit(1) recovery_path = g_dict_dir_config['wallet_recovery_dir'] if not os.path.exists(recovery_path): os.makedirs(recovery_path) wallet_name = 'recovery_wallet_{}.json'.format(get_time_stamp()) wallet_path = os.path.join(recovery_path, wallet_name) with open(wallet_path, 'w') as f: json.dump(keystores, f) cust_print('recovery successful!', fg='g') cust_print('recovery to {}.'.format(wallet_path), fg='g') else: # Todo pass
def read_file(data_file): """ :param data_file: xxxxxx.csv or xxxx.jpg :return: """ unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"] # unsigned_tx_dir = r'D:\project\platoncli\unsigned_transaction' abspath = os.path.join(unsigned_tx_dir, data_file) if not os.path.isfile(abspath): cust_print('No {} file found in the {} directory please check!'.format( data_file, unsigned_tx_dir), fg='r') sys.exit(1) result = [] _, suffix = os.path.splitext(data_file) if suffix == '.csv': with open(abspath, 'r') as f: reader = csv.DictReader(f) for v in reader: if v.get('value', None): v['value'] = int(ast.literal_eval(v['value'])) if v.get('data', None): v['data'] = ast.literal_eval(v['data']) result.append(dict(v)) elif suffix == '.jpg': result = read_QRCode(abspath) else: cust_print('{} illegal,please check!'.format(data_file), fg='r') sys.exit(1) if len(result) == 0: cust_print('{} class content is empty,please check!'.format(data_file), fg='r') sys.exit(1) return result
def sign(data, address): """ this is account submodule offline sign command. """ wait_sign_data = read_file(data) wallet_dir = g_dict_dir_config["wallet_dir"] wallet_file_path, private_key, hrp, account = verify_password( address, wallet_dir) sign_data = [] for _wait_sign_data in wait_sign_data: rawTransaction, _ = sign_one_transaction_by_prikey( account, None, _wait_sign_data, hrp, private_key) sign_data.append(rawTransaction) signed_tx_dir = g_dict_dir_config["signed_tx_dir"] check_dir_exits(signed_tx_dir) name = 'signed_transfer_tx_{}.txt'.format(get_time_stamp()) abspath = os.path.join(signed_tx_dir, name) with open(abspath, 'w', encoding='utf-8') as f: f.write(str(sign_data)) cust_print('sign successful!', fg='g') cust_print('sign after data save to {}'.format(abspath), fg='g')
def blockexport(savePath): """ this is node submodule blockexport command. """ if not os.path.exists(savePath): cust_print("invalid path: {}".format(savePath), fg='r') return # 节点数据 data_dir = os.path.join(g_dict_dir_config["platon_dir"], "data") if not os.path.exists(data_dir): cust_print("Data file not found: {}".format(data_dir), fg='r') return platon_cfg = get_local_platon_cfg() # 进程是否在运行 pid = get_pid(PLATON_NAME, int(platon_cfg['rpcport'])) if pid: confirm = input( 'PlatON is running, rpc port:{}, Whether or not to continue? [Y|y/N|n]: ' .format(int(platon_cfg['rpcport']))) # 关闭进程 if confirm == 'Y' or confirm == 'y': shutdown_node() else: cust_print('Failed to export block data!:{}'.format(g_current_dir), fg='r') return cust_print('Start exporting the block data.', fg='g') # make zip zip_name = "data_" + get_time_stamp() + ".zip" zip_path = os.path.join(savePath, zip_name) make_zip(data_dir, zip_path) cust_print('Export block data successfully.', fg='g')
def check(address, test_net): """ this is account submodule check command. """ wallet_dir = g_dict_dir_config["wallet_dir"] net_type = "mainnet" if test_net: net_type = "testnet" cust_print("Start check wallet files...", fg='g') if "" != address: if address.endswith(".json"): check_name = address check_address, _ = get_address_by_file_name( wallet_dir, address, net_type) elif 42 != len(address): cust_print("Wrong address parameter: --address {}".format(address), fg='r') sys.exit(1) else: find, _, fileName = get_wallet_file_by_address( wallet_dir, address, net_type) if not find: cust_print( 'The wallet file of {} could not be found on {}'.format( fileName, wallet_dir), fg='r') sys.exit(1) check_name = fileName check_address = address cust_print("Name:{}, Address:{}".format(check_name, check_address), fg='g') else: dict_all_wallet = get_all_wallet_file_on_dir(wallet_dir, net_type) for k in dict_all_wallet: cust_print("Name:{}, Address:{}".format(k, dict_all_wallet[k]), fg='g')