Exemple #1
0
def exception_retry_request_setup():
    web3 = Mock()
    provider = HTTPProvider()
    errors = (ConnectionError, HTTPError, Timeout, TooManyRedirects)
    setup = exception_retry_middleware(provider.make_request, web3, errors, 5)
    setup.web3 = web3
    return setup
Exemple #2
0
def batch_send_transfer(txfile, config):
    # 交易文件列表
    if txfile == "":
        print("-f/--txfile is null, please input.")
        exit(1)

    # 发送交易的节点配置信息
    if config == "":
        print("-c/--config is null, please input.")
        exit(1)

    try:
        # 获取节点 url
        with open(config, 'r') as load_f:
            config_info = json.load(load_f)
            url = config_info['nodeAddress'] + ":" + config_info['nodeRpcPort']

        # 获取交易列表
        transaction_list_raw = read_csv(txfile)
        transaction_list = []
        for one_transaction in transaction_list_raw:
            transaction_list.append(transaction_str_to_int(one_transaction))

        if len(transaction_list) == 0 :
            print("have not transaction.")
            exit(1)
        w3 = Web3(HTTPProvider(url))
        platon = Eth(w3)
        # 获取当前nonce
        curr_nonce = platon.getTransactionCount(Web3.toChecksumAddress(transaction_list[0]["from"]))

        # 发送交易
        print('\nstart to send transfer transaction, please wait...\n')
        for one_transaction in transaction_list:
            if curr_nonce > int(one_transaction["nonce"]):
                continue
            transfer_send(platon, one_transaction["rawTransaction"])
            sleep(1)

    except Exception as e:
        print('{} {}'.format('exception: ', e))
        print('batch send transfer transaction failure!!!')
        sys.exit(1)
    else:
        print('batch send transfer transaction SUCCESS.')
        end = datetime.datetime.now()
        print("end:{}".format(end))
        print("总共消耗时间:{}s".format((end - start).seconds))
        sys.exit(0)
def load_provider_from_uri(uri_string, headers=None):
    uri = urlparse(uri_string)
    if uri.scheme == 'file':
        return IPCProvider(uri.path)
    elif uri.scheme in HTTP_SCHEMES:
        return HTTPProvider(uri_string, headers)
    elif uri.scheme in WS_SCHEMES:
        return WebsocketProvider(uri_string)
    else:
        raise NotImplementedError(
            'Web3 does not know how to connect to scheme %r in %r' % (
                uri.scheme,
                uri_string,
            )
        )
Exemple #4
0
def batch_send_transfer(accountsfile, config):
    # 交易文件列表
    if accountsfile == "":
        print("-f/--accountsfile is null, please input.")
        exit(1)

    # 发送交易的节点配置信息
    if config == "":
        print("-c/--config is null, please input.")
        exit(1)

    try:
        # 获取节点 url
        with open(config, 'r') as load_f:
            config_info = json.load(load_f)
            url = config_info['nodeAddress'] + ":" + config_info['nodeRpcPort']

        w3 = Web3(HTTPProvider(url))
        platon = Eth(w3)
        # 获取交易列表
        rows = read_csv(accountsfile)
        for row in rows:
            if 'address' in row:
                address = row["address"]
            else:
                raise Exception(
                    "The address field does not exist in the address file!")

            amount = platon.getBalance(Web3.toChecksumAddress(address))
            amount = w3.fromWei(amount, "ether")

            print("address:{}, amount:{}LAT".format(address, amount))

    except Exception as e:
        print('{} {}'.format('exception: ', e))
        print('batch get account balance failure!!!')
        sys.exit(1)
    else:
        print('batch get account balance  SUCCESS.')
        end = datetime.datetime.now()
        print("end:{}".format(end))
        print("总共消耗时间:{}s".format((end - start).seconds))
        sys.exit(0)
Exemple #5
0
def test_check_with_all_middlewares(make_post_request_mock):
    provider = HTTPProvider()
    w3 = client_sdk_python.Web3(provider)
    with pytest.raises(ConnectionError):
        w3.eth.blockNumber()
    assert make_post_request_mock.call_count == 5
Exemple #6
0
def test_is_strictly_default_http_middleware():
    web3 = HTTPProvider()
    assert 'http_retry_request' in web3.middlewares

    web3 = IPCProvider()
    assert 'http_retry_request' not in web3.middlewares
Exemple #7
0
def signed_batch_transfer(fromprivate, tolist, nonce, amount, config):
    # 发交易钱包文件
    if fromprivate == "":
        print("-f/--fromprivate is null, please input.")
        exit(1)

    # 接收交易地址列表文件
    if tolist == "":
        print("-t/--tolist is null, please input.")
        exit(1)
    else:
        if not tolist.endswith(".csv"):
            raise Exception("File format error")

    # 转账金额
    if amount == "":
        print("-a/--amount is null, please input.")
        exit(1)

    # 发送交易的节点配置信息
    if config == "":
        print("-c/--config is null, please input.")
        exit(1)

    try:
        # 获取转出地址
        address_prikey_list = read_csv(fromprivate)
        if len(address_prikey_list) == 0:
            print(
                "The wallet private key file that sent the transaction is empty, please check!"
            )
            exit(1)
        from_address = address_prikey_list[0]["address"]
        from_prikey = address_prikey_list[0]["private"]
        # 获取节点 url
        with open(config, 'r') as load_f:
            config_info = json.load(load_f)
            url = config_info['nodeAddress'] + ":" + config_info['nodeRpcPort']
            chainId = int(config_info['chainId'])
        # 和节点建立连接
        w3 = Web3(HTTPProvider(url))
        platon = Eth(w3)
        gasPrice = platon.gasPrice

        # 转账金额(LAT转换成VON)
        value = w3.toWei(amount, "ether")
        print("transfer amount:{}VON".format(value))

        if nonce == 0:
            nonce = platon.getTransactionCount(
                Web3.toChecksumAddress(from_address))

        # 获取转账 to 钱包名称
        all_transaction = []
        rows = read_csv(tolist)
        for row in rows:
            if 'address' in row:
                to_address = row["address"]
            else:
                raise Exception(
                    "The address field does not exist in the address file!")

            one_transaction_data = transfer_sign(from_address, to_address,
                                                 value, nonce, gasPrice,
                                                 from_prikey, chainId)
            all_transaction.append(one_transaction_data)
            nonce += 1

        # 生成 csv 文件
        #stamp = get_time_stamp()
        suffix = os.path.basename(tolist)
        transaction_file_name = "signed_batch_transfer_" + suffix
        write_csv(transaction_file_name, all_transaction)

    except Exception as e:
        print('{} {}'.format('exception: ', e))
        print('generate unsigned transaction file failure!!!')
        sys.exit(1)

    else:
        csvPath = os.getcwd() + "\\" + transaction_file_name
        print('{}{} {}'.format('SUCCESS\n',
                               "generate unsigned transaction file:", csvPath))
        end = datetime.datetime.now()
        print("end:{}".format(end))
        print("总共消耗时间:{}s".format((end - start).seconds))
        sys.exit(0)