예제 #1
0
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
예제 #2
0
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)
예제 #3
0
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)
예제 #4
0
def unStaking(address, file, config, offline, style):
    """
    this is staking submodule unStaking command.
    """
    params = read_json_file(file)
    node_id = params['node_id']
    transaction_cfg = params['transaction_cfg']

    check_node_id(node_id)
    wallet_dir = g_dict_dir_config["wallet_dir"]
    _, private_key, _, _ = verify_password(address, wallet_dir)
    private_key = private_key[2:]

    ppos = get_eth_obj(config, 'ppos')
    try:
        if offline:
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            check_dir_exits(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_staking_unStaking_{}.csv".format(
                get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir,
                                              unsigned_file_csv_name)
            data = rlp.encode(
                [rlp.encode(int(1003)),
                 rlp.encode(bytes.fromhex(node_id))])
            params['to_type'] = 'staking'
            transaction_dict = un_sign_data(data, params, ppos, private_key)
            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:
            tx_hash = ppos.withdrewStaking(node_id, private_key,
                                           transaction_cfg)
            cust_print(
                'withdrewStaking send transfer transaction successful, tx hash:{}.'
                .format(tx_hash),
                fg='g')
    except ValueError as e:
        cust_print(
            'unStaking send transfer transaction fail,error info:{}'.format(e),
            fg='r')
        sys.exit(1)
예제 #5
0
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')
예제 #6
0
def changePassword(address):
    """
        this is account submodule change password command.
        """
    wallet_dir = g_dict_dir_config["wallet_dir"]
    cust_print("Start change wallet password...", fg='g')

    wallet_file_path, private_key, hrp, _ = verify_password(
        address, wallet_dir)  # verify old password
    new_password = confirm_password()  # confirm new password

    private_key_obj = crypto.PrivateKey.from_hex(private_key[2:])
    keystores = private_key_obj.to_keyfile_json(new_password)
    public_key = private_key_obj.public_key.to_hex()
    public_address = private_key_obj.public_key.address(hrp)

    old_wallet_name = os.path.basename(wallet_file_path).split('.')[0]
    new_wallet_name = '{old_name}_{timestamp}.json'.format(
        old_name=old_wallet_name, timestamp=get_time_stamp())
    if not os.path.exists(wallet_dir):
        os.makedirs(wallet_dir)
    new_wallet_path = os.path.join(wallet_dir, new_wallet_name)
    with open(new_wallet_path, 'w') as f:
        json.dump(keystores, f)

    verify_password(new_wallet_name, wallet_dir,
                    new_password)  # verify new password is change successful
    os.remove(wallet_file_path)

    cust_print(
        "Congratulations on your successful password modification,old wallet {} already delete!"
        .format(new_wallet_name),
        fg='g')
    cust_print("New WalletName:{}".format(new_wallet_name), fg='g')
    cust_print("PublicKey:{}".format(public_key), fg='g')
    cust_print("Addresss:{}".format(public_address), fg='g')
    cust_print("Path:{}".format(new_wallet_path), fg='g')
예제 #7
0
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')
예제 #8
0
def create(file, address, template, config, offline, style):
    """
    this is staking submodule create command.
    """
    if template:
        show_params()
        return

    if not os.path.isfile(file):
        cust_print('file {} not exits! please check!'.format(file), fg='r')
        sys.exit(1)
    params = read_json_file(file)
    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')
    msg = ppos.admin.getProgramVersion()

    bls_pubkey = ppos.admin.nodeInfo.blsPubKey
    bls_proof = ppos.admin.getSchnorrNIZKProve()
    program_version = msg['Version']
    program_version_sign = msg['Sign']
    _params = {}
    try:
        _params['typ'] = params['typ']
        _params['benifit_address'] = params['benifit_address']
        _params['node_id'] = params['node_id'] or ppos.admin.nodeInfo.id

        _params['external_id'] = params['external_id']
        _params['node_name'] = params['node_name']
        _params['website'] = params['website']
        _params['details'] = params['details']

        _params['amount'] = ppos.w3.toWei(str(params['amount']), "ether")
        _params['program_version'] = params['program_version'] or program_version
        _params['program_version_sign'] = params['program_version_sign'] or program_version_sign
        _params['bls_pubkey'] = params['bls_pubkey'] or bls_pubkey
        _params['bls_proof'] = params['bls_proof'] or bls_proof
        _params['pri_key'] = private_key[2:]
        _params['reward_per'] = params['reward_per']
        if isinstance(params['transaction_cfg'], dict):
            _params['transaction_cfg'] = params['transaction_cfg']
    except KeyError as e:
        cust_print('Key {} does not exist in file {},please check!'.format(e, file), fg='r')
        sys.exit(1)
    try:
        if offline:
            data = rlp_params(tuple(_params.values()), hrp)
            params['to_type'] = 'staking'
            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_staking_create_{}.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:
            tx_hash = ppos.createStaking(*_params.values())
            cust_print('createStaking send transfer transaction successful, tx hash:{}.'.format(tx_hash), fg='g')
    except ValueError as e:
        cust_print('createStaking send transfer transaction fail,error info:{}'.format(e))
        sys.exit(1)
예제 #9
0
def increase(file, address, template, config, offline, style):
    """
    this is staking submodule increase command.
    """
    if template:
        show_params()
        return
    if not os.path.isfile(file):
        cust_print('file {} not exits! please check!'.format(file), fg='r')
        sys.exit(1)
    params = read_json_file(file)
    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 = {}
    try:
        _params['typ'] = params['typ']
        _params['node_id'] = params['node_id'] or ppos.admin.nodeInfo.id
        _params['amount'] = ppos.w3.toWei(str(params['amount']), "ether")
        _params['pri_key'] = private_key[2:]
        if isinstance(params['transaction_cfg'], dict):
            _params['transaction_cfg'] = params['transaction_cfg']
    except KeyError as e:
        cust_print('Key {} does not exist in file {},please check!'.format(
            e, file),
                   fg='r')
        sys.exit(1)
    try:
        if offline:
            data = HexBytes(
                rlp.encode([
                    rlp.encode(int(1002)),
                    rlp.encode(bytes.fromhex(_params['node_id'])),
                    rlp.encode(_params['typ']),
                    rlp.encode(_params['amount'])
                ])).hex()
            params['to_type'] = 'staking'
            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_staking_increase_{}.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:
            tx_hash = ppos.increaseStaking(*_params.values())
            cust_print(
                'increase staking send transfer transaction successful, tx hash:{}.'
                .format(tx_hash),
                fg='g')
    except ValueError as e:
        cust_print(
            'increase staking send transfer transaction fail,error info:{}'.
            format(e),
            fg='r')
        sys.exit(1)
def createRestrictingPlan(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)
    ppos = get_eth_obj(config, 'ppos')
    try:
        params['plans'] = [{
            'epoch':
            plan['epoch'],
            'amount':
            ppos.web3.toWei(str(plan['amount']), "ether")
        } for plan in params['plans']]
        _params = {'account': params['account'], 'plans': params['plans']}
    except KeyError as e:
        cust_print(
            'createRestrictingPlan 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, hrp, _ = verify_password(address, wallet_dir)
    try:
        if offline:
            account = bech32_address_bytes(hrp)(params['account'])
            plan_list = [[plan[k] for k in plan] for plan in params['plans']]
            data = rlp.encode([
                rlp.encode(int(4000)),
                rlp.encode(account),
                rlp.encode(plan_list)
            ])
            _params['transaction_cfg'] = params.get('transaction_cfg', None)
            _params['to_type'] = 'restricting'
            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_hedge_createRestrictingPlan_{}.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.createRestrictingPlan(*_params.values())
            cust_print(
                'send raw transfer transaction successful, tx hash:{}.'.format(
                    txhash),
                fg='g')
    except Exception as e:
        cust_print(
            'createRestrictingPlan send transfer transaction fail,error info:{}'
            .format(e),
            fg='r')
        sys.exit(1)
예제 #11
0
 truck3.load_packages("2", "5", "8", "9", "10", "12", "21", "22", "24",
                      "28", "33", "35", "39")
 # create sub graph for truck 3
 truck3.create_sub_graph()
 # sort the packages on truck 3
 truck3.shortest_path()
 # get the users menu selection
 user_input = input()
 # user wants to view a package at a certain time
 if user_input == "1":
     # get the package id from the user
     package_id = input("Enter a package ID: ")
     # get the time from the user
     package_time = input("Enter a time (HH:MM:SS)  ")
     # convert the time to a timedelta
     delta = utility.get_time_stamp(package_time)
     # run the trucks until the specified time
     truck1.deliver_packages(delta)
     truck2.deliver_packages(delta)
     truck3.deliver_packages(delta)
     # Print the package fields
     Package.print_package(hash_table.search(package_id))
     # display the menu
     printMenu.print_menu()
 # the user wants all of the packages at a specified time
 elif user_input == "2":
     # get the time from the user
     timestamp = input("Enter a time (HH:MM:SS) ")
     # convert the time to a timedelta
     delta = utility.get_time_stamp(timestamp)
     # run the trucks until the specified time
예제 #12
0
audio_directory = "/home/hexorcismos/Desktop/AI/MelGAN-VC/Datasets/aerofonos"

#AUDIO TO CONVERT
awv = audio_array(
    audio_directory)  #get waveform array from folder containing wav files
aspec = tospec(awv)  #get spectrogram array
adata = splitcut(aspec)  #split spectrogams to fixed
print(np.shape(adata))

#Start training from scratch or resume training

training_run_name = "aerofonos_test_train"
checkpoint_save_directory = "/home/hexorcismos/Desktop/AI/MelSpecVAE/checkpoints/"
resume_training = False
resume_training_checkpoint_path = "/content/drive/MyDrive/MelSpecVAE/Amazondotcom_e320_22_4_2021_1417_h256_w128_z64"
current_time = get_time_stamp()

if __name__ == "__main__":
    from vae import VAE

    if not resume_training:
        vae = train(adata, LEARNING_RATE, BATCH_SIZE, EPOCHS)
        vae.save(
            f"{checkpoint_save_directory}{training_run_name}_{current_time}_h{hop}_w{shape}_z{VECTOR_DIM}"
        )
    else:
        vae = continue_training(resume_training_checkpoint_path)
        vae.save(
            f"{checkpoint_save_directory}{training_run_name}_{current_time}_h{hop}_w{shape}_z{VECTOR_DIM}"
        )
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)
예제 #14
0
def transfer(param, address, offline, template, config, style):
    """
    this is tx submodule transfer command.
    """
    if template:
        show_params()
        return

    if param.endswith(".json"):
        try:
            with open(param, 'r') as f:
                dict_param = json.load(f)
        except:
            cust_print(
                "Params json file not exists or json file saved data is not json data,Please check {}"
                .format(param),
                fg='r')
            sys.exit(1)
    else:
        param = param.replace("\'", "\"")
        # 交易参数
        dict_param = json.loads(param)
    if "to" not in dict_param or "value" not in dict_param or 42 != len(
            dict_param["to"]):
        cust_print(
            "The transaction parameter is wrong, please check: {}.".format(
                param),
            fg='r')
        sys.exit(1)

    # 节点配置文件
    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)

    with open(config, 'r') as load_f:
        node_conf_info = json.load(load_f)
        hrp = node_conf_info["hrp"]
        chainId = node_conf_info["chainId"]
        rpcAddress = node_conf_info["rpcAddress"]

    if 'lat' == hrp or 'lax' == hrp:
        from precompile_lib import Web3, HTTPProvider, Eth
    else:
        from precompile_lib import Alaya_Web3 as Web3, Alaya_HTTPProvider as HTTPProvider, Alaya_Eth as Eth

    w3 = Web3(HTTPProvider(rpcAddress))
    platon = connect_node(w3, Eth)

    if dict_param["to"][:3] != hrp:
        cust_print(
            "To address is not in the right format:{}. What you want is {}.".
            format(dict_param["to"], hrp),
            fg='r')
        sys.exit(1)

    # 检查to地址是否合法
    if not decode(hrp, dict_param["to"]):
        cust_print("The to address is a non-BECh32 format address {}.".format(
            dict_param["to"]),
                   fg='r')
        sys.exit(1)

    # 检查from地址是否合法
    wallet_dir = g_dict_dir_config["wallet_dir"]
    wallet_file_path = ""
    net_type = "mainnet"
    if 'lax' == hrp or 'atx' == hrp:
        net_type = "testnet"
    if address.endswith(".json"):
        from_address, wallet_file_path = 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:
        # 在线直接发送交易,需要钱包文件
        if not offline:
            find, wallet_file_path, fileName = get_wallet_file_by_address(
                wallet_dir, address, net_type)
            if not find:
                cust_print(
                    'hrp:{}, The wallet file of address:{} could not be found on {}'
                    .format(hrp, address, wallet_dir),
                    fg='r')
                sys.exit(1)
        from_address = address

    # 检查from地址是否合法
    if not decode(hrp, from_address):
        cust_print(
            "The from address is a non-BECh32 format address {}.".format(
                from_address),
            fg='r')
        sys.exit(1)

    # w3 = Web3(HTTPProvider(rpcAddress))
    # platon = Eth(w3)

    # 查询余额
    free = platon.getBalance(from_address)
    if float(free) <= float(dict_param["value"]):
        free_amount = w3.fromWei(free, "ether")
        cust_print(
            "The balance is insufficient for the transfer, balance: {} {}.".
            format(free_amount, hrp),
            fg='r')
        sys.exit(1)

    nonce = platon.getTransactionCount(from_address)
    value = w3.toWei(str(dict_param["value"]), "ether")
    gas = 4700000
    gasPrice = 1000000000
    if "gas" in dict_param:
        gas = int(dict_param["gas"])
    if "gasPrice" in dict_param:
        gasPrice = int(dict_param["gasPrice"])

    dict_transfer_tx = transfer_unsign(from_address, dict_param["to"],
                                       gasPrice, gas, value, nonce, chainId)

    # 离线方式
    if offline:
        try:
            unsigned_tx_dir = g_dict_dir_config["unsigned_tx_dir"]
            if not os.path.exists(unsigned_tx_dir):
                os.mkdir(unsigned_tx_dir)
            unsigned_file_csv_name = "unsigned_tx_transfer_{}.csv".format(
                get_time_stamp())
            unsigned_file_path = os.path.join(unsigned_tx_dir,
                                              unsigned_file_csv_name)
            all_transaction = [dict_transfer_tx]
            # 生成待签名文件
            if style == '':
                write_csv(unsigned_file_path, all_transaction)
            else:
                unsigned_file_path = unsigned_file_path.replace('csv', 'jpg')
                write_QRCode(all_transaction, unsigned_file_path)
            cust_print('unsigned_file save to:{}'.format(unsigned_file_path),
                       fg='g')
        except Exception as e:
            print('{} {}'.format('exception: ', e))
            cust_print(
                'generate unsigned transfer transaction file failure:{}!!!'.
                format(e),
                fg='r')
            sys.exit(1)

        else:
            cust_print(
                'generate unsigned transfer transaction file successful:{}'.
                format(unsigned_file_path),
                fg='g')
    else:
        try:
            # 输入钱包密码,解锁私钥
            prompt_message = "Enter password:"
            if 'windows' == g_system:
                passwd = b''.join(
                    input_passwd_for_win(prompt_message)).decode()
            else:
                passwd = input_passwd_for_linux(prompt_message)

            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)
            # 签名交易
            rawTransaction, _ = sign_one_transaction_by_prikey(
                Account, None, dict_transfer_tx, hrp, privateKey)
            # print(rawTransaction)
            # 发送交易
            txhash, _ = send_transaction(platon, rawTransaction)

        except Exception as e:
            cust_print(
                'send transfer transaction failure, chainid:{}, error message:{}!!!'
                .format(chainId, e),
                fg='r')
            sys.exit(1)
        else:
            cust_print(
                'send transfer transaction successful, tx hash:{}.'.format(
                    txhash),
                fg='g')
예제 #15
0
def submitProposal(param, address, offline, module, config, style):
    """
    this is government submodule submitProposal 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)
    check_params(params)

    _params = {'verifier': params['verifier'], 'pip_id': params['pIDID']}
    _module, func = method_module[module]
    try:
        if _module == 'submitVersion':
            _params['new_version'] = params['newVersion']
            _params['end_voting_rounds'] = params['endVotingRound']
        if _module == 'submitCancel':
            _params['end_voting_rounds'] = params['endVotingRound']
            _params['tobe_canceled_proposal_id'] = params['canceledProposalID']
        if _module == 'submitParam':
            _params['module'] = params['module']
            _params['name'] = params['name']
            _params['new_value'] = params['newValue']
    except KeyError as e:
        cust_print(
            '{} need params {},but it does not exist,please check!'.format(
                module, e),
            fg='r')
        sys.exit(1)

    wallet_dir = g_dict_dir_config["wallet_dir"]
    _, private_key, _, _ = verify_password(address, wallet_dir)
    pip = get_eth_obj(config, 'pip')
    module, func = method_module[module]
    try:
        if offline:
            data = rlp_params(func, *_params.values())
            _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_submitProposal_{}_{}.csv".format(
                module, 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 = getattr(pip, module)(*_params.values())
            cust_print(
                'send raw transfer transaction successful, tx hash:{}.'.format(
                    txhash),
                fg='g')
    except Exception as e:
        cust_print(
            'submitProposal {} send transfer transaction fail,error info:{}'.
            format(module, e),
            fg='r')
        sys.exit(1)