def create_and_recharge(num):
    w3 = create_web3_instance("http://52.205.30.16:8545")
    acc = Account.privateKeyToAccount("f87fdefd98ef1347f4ee213d80e3495e4beaba5991a18bfee0fa80f0fba05b1a")
    nonce = w3.eth.getTransactionCount(acc.address)
    addrs = []
    for i in range(num):
        addr = create_acc()
        print(addr)
        transaction = {
            'to': addr,
            'value': value,
            'nonce': nonce,
        }

        gas = get_buffered_gas_estimate(w3, transaction)
        gas_price = w3.eth.gasPrice
        transaction['gas'] = gas
        transaction['gasPrice'] = gas_price
        signed = acc.signTransaction(transaction)
        w3.eth.sendRawTransaction(signed.rawTransaction)
        addrs.append(addr)
        nonce += 1

    time.sleep(100)
    for t in addrs:
        print(t, w3.eth.getBalance(t))
def send_normal_txs(acc, targetaddr, txnumber, txvalue, basevalue):
    w3 = create_web3_instance("http://127.0.0.1:2222")
    if txnumber * txvalue * 1.2 > basevalue:
        log_print("txnumber or txvalue is too big!")
        return
    index = 0
    nonce = w3.eth.getTransactionCount(acc.address)
    while index < txnumber:
        index = index + 1
        transaction = {
            'to': targetaddr,
            'value': txvalue,
            'nonce': nonce,
        }

        gas = get_buffered_gas_estimate(w3, transaction)
        gas_price = w3.eth.gasPrice
        # log_debug_print("use gas ", gas, "gasPrice", gas_price)
        transaction['gas'] = int(gas * 5)
        transaction['gasPrice'] = int(gas_price * 2)
        signed = acc.signTransaction(transaction)
        w3.eth.sendRawTransaction(signed.rawTransaction)
        nonce += 1

        if (index * 1000) % txnumber == 0:
            complete = index * 100.0 / txnumber
            log_print("{}: Create txs complet:{}%".format(
                str(acc.address)[:5], complete))
Beispiel #3
0
def deploy_contract(acc):
    try:
        nonce = w3.eth.getTransactionCount(acc.address)
        acc_balance = w3.eth.getBalance(acc.address)
        log_debug_print("address:", acc.address, "nonce:", nonce, "balance:",
                        acc_balance)
        transaction = {
            'data': bytecode,
            'nonce': nonce,
        }
        gas = get_buffered_gas_estimate(w3, transaction)
        gas_price = w3.eth.gasPrice

        clear_account_before_deploy(acc, gas * gas_price)

        log_debug_print("use gas ", gas, "gasPrice", gas_price)
        transaction['gas'] = gas
        transaction['gasPrice'] = w3.eth.gasPrice
        signed = acc.signTransaction(transaction)
        result = w3.eth.sendRawTransaction(signed.rawTransaction)
        log_debug_print("We creat contract. txHash:",
                        str(binascii.b2a_hex(result), encoding='utf-8'))
        log_print("Sleep wait 30 seconds for tx be putted into block")
        time.sleep(30)
        receipt = w3.eth.getTransactionReceipt(result)
        log_debug_print("TxReceipt status", receipt['status'])
        return True, None
    except Exception as e:
        log_print(e)
        return False, e
Beispiel #4
0
def clear_account_before_deploy(acc, threshold):
    balance = w3.eth.getBalance(acc.address)
    if balance >= threshold:
        nonce = w3.eth.getTransactionCount(acc.address)
        addr = get_rand_account().address
        transaction = {
            # Note that the address must be in checksum format:
            'nonce': nonce,
            'to': addr,
            'value': balance,
        }
        gas = get_buffered_gas_estimate(w3, transaction)
        gas_price = w3.eth.gasPrice
        log_debug_print("use gas ", gas, "gasPrice", gas_price)
        transaction['gas'] = gas
        transaction['gasPrice'] = w3.eth.gasPrice
        transaction['value'] = balance - w3.eth.gasPrice * gas
        signed = acc.signTransaction(transaction)
        result = w3.eth.sendRawTransaction(signed.rawTransaction)
        log_debug_print("We create clear account tx,  txHash:",
                        str(binascii.b2a_hex(result), encoding='utf-8'))
        time.sleep(30)
        receipt = w3.eth.getTransactionReceipt(result)
        log_debug_print("TxReceipt status", receipt['status'])
        balance = w3.eth.getBalance(acc.address)
        log_debug_print("balance end ", balance)
Beispiel #5
0
    def sendTransaction(self, transaction):
        formatted_transaction = formatters.input_transaction_formatter(self, transaction)
        if 'gas' not in formatted_transaction and 'data' in formatted_transaction:
            formatted_transaction['gas'] = get_buffered_gas_estimate(
                self.web3,
                transaction=formatted_transaction,
            )
        elif 'gas' not in formatted_transaction:
            formatted_transaction['gas'] = 90000

        return self.web3._requestManager.request_blocking(
            "eth_sendTransaction",
            [formatters.input_transaction_formatter(self, formatted_transaction)],
        )
Beispiel #6
0
    def sendTransaction(self, transaction):
        # TODO: move to middleware
        if 'from' not in transaction and is_checksum_address(self.defaultAccount):
            transaction = assoc(transaction, 'from', self.defaultAccount)

        # TODO: move gas estimation in middleware
        if 'gas' not in transaction:
            transaction = assoc(
                transaction,
                'gas',
                get_buffered_gas_estimate(self.web3, transaction),
            )

        return self.web3.manager.request_blocking(
            "eth_sendTransaction",
            [transaction],
        )
Beispiel #7
0
    def sendTransaction(self, transaction):
        # TODO: move to middleware
        if 'from' not in transaction and is_checksum_address(self.defaultAccount):
            transaction = assoc(transaction, 'from', self.defaultAccount)

        # TODO: move gas estimation in middleware
        if 'gas' not in transaction:
            transaction = assoc(
                transaction,
                'gas',
                get_buffered_gas_estimate(self.web3, transaction),
            )

        return self.web3.manager.request_blocking(
            "eth_sendTransaction",
            [transaction],
        )
Beispiel #8
0
    def sendTransaction(self, transaction):
        formatted_transaction = formatters.input_transaction_formatter(
            self, transaction)
        if 'gas' not in formatted_transaction and 'data' in formatted_transaction:
            formatted_transaction['gas'] = get_buffered_gas_estimate(
                self.web3,
                transaction=formatted_transaction,
            )
        elif 'gas' not in formatted_transaction:
            formatted_transaction['gas'] = 90000

        return self.web3._requestManager.request_blocking(
            "eth_sendTransaction",
            [
                formatters.input_transaction_formatter(self,
                                                       formatted_transaction)
            ],
        )
    def estimate_tx_gas(self, tx):
        """Estimate transaction gas.
        If there is a predefined limit, return it.
        Otherwise ask the API to estimate gas and add a buffer for safety.

        :param dict tx: sample transaction to estimate gas for.
        :return: estimated gas, or default gas if estimate has failed.
        :rtype: int
        """
        if self.gas_limit:
            return self.gas_limit
        gas_buffer = 10000 if tx.get('data') else 5000
        try:
            if tx['data']:
                tx['data'] = encode_hex(tx['data'])
            return get_buffered_gas_estimate(self.web3, tx, gas_buffer=gas_buffer)
        except Exception as e:
            logging.warning('cannot estimate gas for transaction: ' + str(e))
            return DEFAULT_GAS_PER_TX
Beispiel #10
0
    def estimate_tx_gas(self, tx):
        """Estimate transaction gas.
        If there is a predefined limit, return it.
        Otherwise ask the API to estimate gas and add a buffer for safety.

        :param dict tx: sample transaction to estimate gas for.
        :return: estimated gas, or default gas if estimate has failed.
        :rtype: int
        """
        if self.gas_limit:
            return self.gas_limit
        gas_buffer = 10000 if tx.get('data') else 5000
        try:
            if tx['data']:
                tx['data'] = encode_hex(tx['data'])
            return get_buffered_gas_estimate(self.web3, tx, gas_buffer=gas_buffer)
        except Exception as e:
            logging.warning('cannot estimate gas for transaction: ' + str(e))
            return DEFAULT_GAS_PER_TX
Beispiel #11
0
def do_test():
    acc1 = Account.privateKeyToAccount(
        "15bac02dbaff32a8da673c490753a070b054b9d62adbc52cc474f2b49370613b")

    normal_w3 = create_web3_instance("http://127.0.0.1:2222")
    miner_w3 = create_web3_instance("http://127.0.0.1:1111")
    balance_end = miner_w3.eth.getBalance(acc1.address)
    w3 = miner_w3
    print(balance_end)

    print(miner_w3.eth.getTransactionCount(acc1.address))
    # return
    nonce = w3.eth.getTransactionCount(acc1.address)

    accs = []
    for i in range(100):
        print("nonec", nonce)
        acc2 = get_rand_account()
        accs.append(acc2)
        transaction = {
            'to': acc2.address,
            'value': 1000000000,
            'nonce': nonce,
        }

        gas = get_buffered_gas_estimate(miner_w3, transaction)
        gas_price = w3.eth.gasPrice
        log_debug_print("use gas ", gas, "gasPrice", gas_price)
        transaction['gas'] = int(gas)
        transaction['gasPrice'] = int(gas_price)
        signed = acc1.signTransaction(transaction)
        res = w3.eth.sendRawTransaction(signed.rawTransaction)
        print(acc2.address,
              "0x" + str(binascii.b2a_hex(res), encoding='utf-8'))
        # time.sleep(15)
        print("---", w3.eth.getBalance(acc2.address))
        print("--------------------")
        nonce += 1
    time.sleep(40)
    for acc in accs:
        print("===>", acc.address, w3.eth.getBalance(acc.address))
Beispiel #12
0
def send_txs_by_addrs(process_id, thread_id, accs: list, targetaddr, txnumber,
                      txvalue, basevalue):
    ports = ["2222", "3333", "4444", "5555", "6666"]
    port = ports[(process_id % 5)]
    w3 = create_web3_instance("http://127.0.0.1:{}".format(port))
    log_print("thread_id:{}, len of accs:{}, txnumber:{}".format(
        thread_id, len(accs), txnumber))
    # w3 = create_web3_instance("http://127.0.0.1:2222")
    if txnumber * txvalue * 1.2 > basevalue:
        log_print("txnumber or txvalue is too big!", txnumber, txvalue,
                  basevalue)
        return
    index = 0
    nonce = w3.eth.getTransactionCount(accs[0].address)
    tag = "Tread id:{}".format(thread_id)
    while index < txnumber:

        for acc in accs:
            transaction = {
                'to': targetaddr,
                'value': txvalue,
                'nonce': nonce,
            }

            gas = get_buffered_gas_estimate(w3, transaction)
            gas_price = w3.eth.gasPrice
            # log_debug_print("use gas ", gas, "gasPrice", gas_price)
            transaction['gas'] = int(gas * 5)
            transaction['gasPrice'] = int(gas_price * 2)
            signed = acc.signTransaction(transaction)
            res = w3.eth.sendRawTransaction(signed.rawTransaction)

            index += 1
            if (index * 1000) % txnumber == 0:
                complete = index * 100.0 / txnumber
                # log_print("{}: Create txs complet:{}%".format(tag, complete))

        nonce += 1
def send_txs_by_addrs(threadindex, accs: list, targetaddr, txnumber, txvalue,
                      basevalue):
    w3 = create_web3_instance("http://127.0.0.1:2222")
    if txnumber * txvalue * 1.2 > basevalue:
        log_print("txnumber or txvalue is too big!")
        return
    index = 0
    nonce = w3.eth.getTransactionCount(accs[0].address)
    tag = "Tread inde:{}".format(threadindex)
    while index < txnumber:

        for acc in accs:
            if index > txnumber:
                break
            transaction = {
                'to': targetaddr,
                'value': txvalue,
                'nonce': nonce,
            }

            gas = get_buffered_gas_estimate(w3, transaction)
            gas_price = w3.eth.gasPrice
            # log_debug_print("use gas ", gas, "gasPrice", gas_price)
            transaction['gas'] = int(gas * 5)
            transaction['gasPrice'] = int(gas_price * 2)
            signed = acc.signTransaction(transaction)
            res = w3.eth.sendRawTransaction(signed.rawTransaction)
            # if int(threadindex) == 0:
            #     print(nonce, str(binascii.b2a_hex(res), 'utf-8'), targetaddr)
            index += 1
            if (index * 100) % txnumber == 0:
                complete = index * 100.0 / txnumber
                log_print("{}: Create txs complet:{}% at:{}".format(
                    tag, complete, index))

        nonce += 1
def call_normal_transactions(from_acc, to_acc, value=10000000000000):
    if not to_acc:
        to_acc = get_rand_account()
    recharge_balance = w3.eth.getBalance(from_acc.address)
    txnum = int(recharge_balance / value / 200)
    # txnum = 1000
    log_print("send {} normal txs from:{} to to:{} value:{}".format(txnum, from_acc.address, to_acc.address, value))
    if txnum == 0:
        return

    nonce = w3.eth.getTransactionCount(from_acc.address)
    index = 0
    while index < txnum:
        transaction = {
            'to': from_acc.address,
            'value': value,
            'nonce': nonce,
        }

        gas = get_buffered_gas_estimate(w3, transaction)
        gas_price = w3.eth.gasPrice
        transaction['gas'] = int(gas * 1.5)
        transaction['gasPrice'] = int(gas_price * 3)
        signed = from_acc.signTransaction(transaction)
        w3.eth.sendRawTransaction(signed.rawTransaction)
        nonce += 1
        index += 1
    log_print("Sleep 120 seconde for txs been putted into block")
    timeout = 120
    while True:
        if timeout < 1:
            break
        time.sleep(1)
        timeout = timeout - 1
        if timeout % 10 == 0:
            log_print("Time sleeps : {} * 10".format(int(timeout / 10)))
Beispiel #15
0
def init_accs_balances(w3, mainacc, subaccs: list, basevalue):
    sub_acc_num = len(subaccs)
    if sub_acc_num == 0 or basevalue < 1000000000000000000:
        log_print("len(subaccs) == 0! or base value to low")
        return False
    subvalue = int((basevalue - 1000000000000000000) / sub_acc_num)

    nonce = w3.eth.getTransactionCount(mainacc.address)
    log_print("start init_accs_balances")
    for acc in subaccs:
        transaction = {
            'to': acc.address,
            'value': subvalue,
            'nonce': nonce,
        }

        gas = get_buffered_gas_estimate(w3, transaction)
        gas_price = w3.eth.gasPrice
        transaction['gas'] = int(gas * 5)
        transaction['gasPrice'] = int(gas_price * 2)
        signed = mainacc.signTransaction(transaction)
        w3.eth.sendRawTransaction(signed.rawTransaction)
        nonce += 1
    return True
def start_mutiple_send_txs(w3, mainacc, subaccs: list, targetacc, txnumber,
                           txvalue, basevalue):
    log_print("start  start_mutiple_send_txs")
    sub_acc_num = len(subaccs)
    if sub_acc_num == 0:
        return
    subvalue = int((basevalue - 1000000000000000000) / sub_acc_num)
    percount = txnumber / 10
    nonce = w3.eth.getTransactionCount(mainacc.address)
    log_print("start recharge subaccs")
    for acc in subaccs:
        transaction = {
            'to': acc.address,
            'value': subvalue,
            'nonce': nonce,
        }

        gas = get_buffered_gas_estimate(w3, transaction)
        gas_price = w3.eth.gasPrice
        # log_debug_print("use gas ", gas, "gasPrice", gas_price)
        transaction['gas'] = int(gas * 5)
        transaction['gasPrice'] = int(gas_price * 2)
        signed = mainacc.signTransaction(transaction)
        w3.eth.sendRawTransaction(signed.rawTransaction)
        nonce += 1
    # time.sleep(20)
    log_print("saple address", subaccs[0].address)
    log_print("end recharge subaccs")
    log_print("call start_send_txs")
    batch_accs = []

    start_tps_count = False

    threadindex = 0
    batch_addrs_num = sub_acc_num / 5
    log_print("sum of addrs:{}, batch_addrs_num:{}".format(
        sub_acc_num, batch_addrs_num))
    while len(subaccs) > 0:
        for acc in subaccs:
            balance = w3.eth.getBalance(acc.address)

            if balance > 0 and len(batch_accs) < batch_addrs_num:
                batch_accs.append(acc)
                subaccs.remove(acc)

            if len(batch_accs) == batch_addrs_num:
                args_accs = batch_accs
                log_print("start thread: {}".format(threadindex))
                call_thread(send_txs_by_addrs, [
                    threadindex, args_accs, targetacc.address, percount,
                    txvalue, balance
                ])

                if not start_tps_count:
                    global thread_tps
                    thread_tps = threading.Thread(target=get_tps_eth,
                                                  name="get_tps_eth")
                    thread_tps.start()
                    start_tps_count = True

                batch_accs = []
                threadindex += 1
                log_print("end start thread: {}".format(threadindex))
        if len(subaccs) > batch_addrs_num:
            time.sleep(15)

    if len(batch_accs) > 0:
        args_accs = batch_accs
        t = threading.Thread(target=send_txs_by_addrs,
                             args=[
                                 threadindex, args_accs, targetacc.address,
                                 percount, txvalue, balance
                             ])
        t.start()
        batch_accs = []

    log_print("end  start_mutiple_send_txs")
def with_draw_one_times(output,
                        balance,
                        fee=0,
                        value=0,
                        keystore=keyfile_json,
                        keypass=password,
                        acc=None):
    try:
        if not acc:
            privatekey = Account.decrypt(keystore, keypass)
            log_debug_print("privateKey", binascii.b2a_hex(privatekey))
            acc = Account.privateKeyToAccount(privatekey)
        acc_balance = w3.eth.getBalance(acc.address)
        log_debug_print("use Address", acc.address, "balance", acc_balance)
        withdawcontact = w3.eth.contract(address=contract_info.address,
                                         abi=contract_info.abi)
        data = withdawcontact.encodeABI(fn_name="receivePayload",
                                        args=[output, balance, fee])
        nonce = w3.eth.getTransactionCount(acc.address)
        startvalue = w3.eth.getBalance(acc.address)

        transaction = {
            'to': contract_info.address,
            'value': value,
            'data': data,
            'nonce': nonce,
        }

        gas = get_buffered_gas_estimate(w3, transaction)
        gas_price = w3.eth.gasPrice
        log_debug_print("use gas ", gas, "gasPrice", gas_price)
        transaction['gas'] = gas
        transaction['gasPrice'] = gas_price
        signed = acc.signTransaction(transaction)

        result = w3.eth.sendRawTransaction(signed.rawTransaction)
        log_debug_print("We call contract. txHash:",
                        str(binascii.b2a_hex(result), encoding='utf-8'))
        # waiting for mined in block
        time.sleep(20)
        receipt = w3.eth.getTransactionReceipt(result)

        log_debug_print("TxReceipt status", receipt['status'])
        gasUsed = receipt['gasUsed']
        endvalue = w3.eth.getBalance(acc.address)
        subValue = startvalue - endvalue
        status = receipt['status']
        if status != 1:
            log_debug_print("Case not pass!, Tx not passed")
            return False, None, "Tx not passed"
        log_debug_print("startValue", startvalue, "endValue", endvalue,
                        "OutputValue", value, "Use Value ", subValue)
        log_debug_print("gas", gas, "gasPrice", gas_price, "gasUsed", gasUsed)
        if subValue - (value + gas_price * gasUsed) != 0.0:
            strerr = " Balance calc wrong! startBalance: " + str(
                startvalue) + " endBalance:" + str(
                    endvalue) + " subBalce:" + str(subValue)
            + " gasUsed: " + str(gasUsed) + " gasPrice" + str(gas_price)
            return False, None, strerr
        return True, result, None
    except Exception as e:
        return False, None, str(e) + ""