def setup_class(self): self.auto = AutoDeployPlaton() self.auto.start_all_node(self.node_yml_path) self.genesis_dict = LoadFile(self.genesis_path).get_data() self.chainid = int(self.genesis_dict["config"]["chainId"]) self.ppos_link = Ppos(self.rpc_list[0], self.address, self.chainid) self.w3_list = [connect_web3(url) for url in self.rpc_list] """用新的钱包地址和未质押过的节点id封装对象""" self.ppos_noconsensus_1 = Ppos(self.rpc_list[0], self.account_list[0], self.chainid, privatekey=self.privatekey_list[0]) self.ppos_noconsensus_2 = Ppos(self.rpc_list[0], self.account_list[1], self.chainid, privatekey=self.privatekey_list[1]) self.ppos_noconsensus_3 = Ppos(self.rpc_list[0], self.account_list[2], self.chainid, privatekey=self.privatekey_list[2]) self.ppos_noconsensus_4 = Ppos(self.rpc_list[0], self.account_list[3], self.chainid, privatekey=self.privatekey_list[3]) self.ppos_noconsensus_5 = Ppos(self.rpc_list[0], self.account_list[4], self.chainid, privatekey=self.privatekey_list[4]) self.ppos_noconsensus_6 = Ppos(self.rpc_list[0], self.account_list[5], self.chainid, privatekey=self.privatekey_list[5]) self.eth = Eth(self.w3_list[0])
def test_platon_sign(self, unlocked_account): platon = Eth(unlocked_account['node'].web3) signature = platon.sign( unlocked_account['address'], text='Message tö sign. Longer than hash!' ) assert is_bytes(signature) assert len(signature) == 32 + 32 + 1 # test other formats hexsign = platon.sign( unlocked_account['address'], hexstr='0x4d6573736167652074c3b6207369676e2e204c6f6e676572207468616e206861736821' ) assert hexsign == signature intsign = platon.sign( unlocked_account['address'], 0x4d6573736167652074c3b6207369676e2e204c6f6e676572207468616e206861736821 ) assert intsign == signature bytessign = platon.sign( unlocked_account['address'], b'Message t\xc3\xb6 sign. Longer than hash!' ) assert bytessign == signature new_signature = platon.sign( unlocked_account['address'], text='different message is different' ) assert new_signature != signature
def test_platon_estimateGas(global_running_env): node = global_running_env.get_rand_node() account = global_running_env.account platon = Eth(node.web3) address = account.account_with_money["address"] nCount = platon.getTransactionCount(Web3.toChecksumAddress(address)) nonce = hex(nCount) estimateGas = transaction_func(node=node, from_addr=address, to_addr=to_address, nonce=nonce, gas='') gas = estimateGas tx_hash = transaction_func(node=node, from_addr=address, to_addr=to_address, nonce=nonce, gas=gas) assert len(tx_hash) == 32 nCount = nCount + 1 nonce = hex(nCount) gas = int(estimateGas * 2) tx_hash = transaction_func(node=node, from_addr=address, to_addr=to_address, nonce=nonce, gas=gas) assert len(tx_hash) == 32 nCount = nCount + 1 nonce = hex(nCount) gas = int(estimateGas / 2) status = 0 try: transaction_func(node=node, from_addr=address, to_addr=to_address, nonce=nonce, gas=gas) status = 1 except Exception as e: print("\nUse less gas than expected:【{}】,Send transaction failed,error message:{}".format(gas, e)) assert status == 0
def test_platon_getPrepareQC(global_running_env): node = global_running_env.get_rand_node() platon = Eth(node.web3) blockNumber = platon.blockNumber qc = platon.getPrepareQC(blockNumber) assert qc is not None print("\n查询区块的聚合签名成功:区块高度【{}】,签名数据:【{}】".format(blockNumber, qc))
def test_getTransactionCount(self, global_test_env): env = global_test_env node = env.get_rand_node() platon = Eth(node.web3) transaction_count = platon.getTransactionCount(env.account.get_rand_account()['address']) assert is_integer(transaction_count) assert transaction_count >= 0
def generate_account(self, web3, balance=0): platon = Eth(web3) account = platon.account.create(net_type=web3.net_type) address = account.address prikey = account.privateKey.hex()[2:] if balance != 0: self.sendTransaction(web3, '', self.account_with_money['address'], address, platon.gasPrice, 21000, balance) account = { "address": address, "nonce": 0, "balance": balance, "prikey": prikey, } self.accounts[address] = account # todo delete debug def debug(): from conf.settings import BASE_DIR from ruamel import yaml accounts = list(self.accounts.values()) with open(os.path.join(BASE_DIR, "deploy/tmp/accounts.yml"), mode="w", encoding="UTF-8") as f: yaml.dump(accounts, f, Dumper=yaml.RoundTripDumper) debug() return address, prikey
def test_platon_gasPrice(global_running_env): node = global_running_env.get_rand_node() platon = Eth(node.web3) account = global_running_env.account from_address = account.account_with_money["address"] nCount = platon.getTransactionCount(Web3.toChecksumAddress(from_address)) nonce = hex(nCount) gasprice = node.eth.gasPrice tx_hash = transaction_func(node=node, from_addr=from_address, to_addr=to_address, nonce=nonce, gasPrice=gasprice) assert len(tx_hash) == 32 gasprice = node.eth.gasPrice * 2 nCount = nCount + 1 nonce = hex(nCount) tx_hash = transaction_func(node=node, from_addr=from_address, to_addr=to_address, nonce=nonce, gasPrice=gasprice) assert len(tx_hash) == 32 gasprice = int(node.eth.gasPrice / 2) nCount = nCount + 1 nonce = hex(nCount) status = 0 try: transaction_func(node=node, from_addr=from_address, to_addr=to_address, nonce=nonce, gasPrice=gasprice) status = 1 except Exception as e: print("\nUse less than the recommended gasprice:{}, nonce:{}, Send transaction failed,error message:{}".format(gasprice, nonce, e)) assert status == 0
def sendTransaction(self, connect, data, from_address, to_address, gasPrice, gas, value, check_address=True): platon = Eth(connect) account = self.accounts[from_address] nonce = platon.getTransactionCount(from_address) transaction_dict = { "to": to_address, "gasPrice": gasPrice, "gas": gas, "nonce": nonce, "data": data, "chainId": self.chain_id, "value": value, } signedTransactionDict = platon.account.signTransaction( transaction_dict, account['prikey']) data = signedTransactionDict.rawTransaction result = HexBytes(platon.sendRawTransaction(data)).hex() # log.debug("result:::::::{}".format(result)) res = platon.waitForTransactionReceipt(result) account['nonce'] = nonce + 1 self.accounts[from_address] = account return res
def block_with_txn(global_test_env): env = global_test_env node = env.get_rand_node() account = env.account.account_with_money res = env.account.sendTransaction(node.web3, '', account['address'], account['address'], node.eth.gasPrice, 21000, 10000) platon = Eth(node.web3) return platon.getBlock(res['blockNumber'])
def test_platon_replaceTransaction_gas_price_defaulting_strategy_higher(self, unlocked_account): node = unlocked_account['node'] platon = Eth(node.web3) price = platon.gasPrice txn_params = { 'from': unlocked_account['address'], 'to': UNKNOWN_ADDRESS, 'value': 1, 'gas': 21000, 'gasPrice': price * 10, 'nonce': 1000, } txn_hash = platon.sendTransaction(txn_params) def higher_gas_price_strategy(web3, txn): return price * 20 platon.setGasPriceStrategy(higher_gas_price_strategy) node.web3.eth = platon txn_params.pop('gasPrice') replace_txn_hash = platon.replaceTransaction(txn_hash, txn_params) replace_txn = platon.getTransaction(replace_txn_hash) log.info(replace_txn) assert replace_txn['gasPrice'] == price * 20 # Strategy provides higher gas price
def block_with_txn_with_log(global_test_env): env = global_test_env node = env.get_rand_node() plan = [{"Epoch": 1, "Amount": 1000000}] res = env.account.create_restricting_plan(node.web3, COMMON_ADDRESS, plan, env.account.account_with_money['address'], node.eth.gasPrice * 2, 300000) platon = Eth(node.web3) return platon.getBlock(res['blockNumber'])
def test_platon_replaceTransaction_gas_price_defaulting_strategy_lower(self, unlocked_account): node = unlocked_account['node'] platon = Eth(node.web3) price = platon.gasPrice txn_params = { 'from': unlocked_account['address'], 'to': unlocked_account['address'], 'value': 3, 'gas': 21000, 'gasPrice': price * 2, 'nonce': 3000, } txn_hash = platon.sendTransaction(txn_params) def lower_gas_price_strategy(web3, txn): return price platon.setGasPriceStrategy(lower_gas_price_strategy) node.web3.eth = platon txn_params.pop('gasPrice') replace_txn_hash = platon.replaceTransaction(txn_hash, txn_params) replace_txn = platon.getTransaction(replace_txn_hash) # Strategy provices lower gas price - minimum preferred assert replace_txn['gasPrice'] == int(price * 2 * 1.1)
def test_platon_GetBlock(global_running_env): node = global_running_env.get_rand_node() account = global_running_env.account platon = Eth(node.web3) address = account.account_with_money["address"] nCount = platon.getTransactionCount(Web3.toChecksumAddress(address)) nonce = hex(nCount) log.info(f'node: {node.host} {node.p2p_port}, address: {address}') gasprice = node.eth.gasPrice # send transaction if g_txHash is None: tx_hash = transaction_func(node=node, from_addr=address, to_addr=to_address, nonce=nonce, gasPrice=gasprice) else: tx_hash = g_txHash assert len(tx_hash) == 32 tx_hash = HexBytes(tx_hash).hex() print("\ntransaction hash:{}".format(tx_hash)) # Waiting for transaction on the chain result = node.eth.waitForTransactionReceipt(tx_hash) assert None != result # get block info by transaction receipt blockHash = result["blockHash"] blockNumber = result["blockNumber"] assert len(blockHash) == 32 blockHash = HexBytes(blockHash).hex() # get block by blockHash # fullTx:Flase blockInfo = node.eth.getBlock(blockHash, False) blockHash = blockInfo['hash'] blockNumber = blockInfo['number'] assert len(blockHash) == 32 assert blockNumber > 0 fullTransaction = blockInfo["transactions"] assert len(fullTransaction) > 0 # fullTx:True blockInfo = node.eth.getBlock(blockHash, True) blockHash = blockInfo['hash'] assert len(blockHash) == 32 fullTransaction = blockInfo["transactions"] assert len(fullTransaction) > 0 # get block by blockNumber # fullTx:Flase blockInfo = node.eth.getBlock(blockNumber, False) blockHash = blockInfo['hash'] assert len(blockHash) == 32 fullTransaction = blockInfo["transactions"] assert len(fullTransaction) > 0 # fullTx:True blockInfo = node.eth.getBlock(blockNumber, True) blockHash = blockInfo['hash'] assert len(blockHash) == 32 fullTransaction = blockInfo["transactions"] assert len(fullTransaction) > 0
def test_new_account_transaction(): ''' 新建账号存在余额后转账给其他账号 ''' nocollusion_w3 = connect_web3(nocollusion_list[0]["url"]) eth = Eth(nocollusion_w3) # 先给新账户存钱 new_account = nocollusion_w3.toChecksumAddress( nocollusion_w3.personal.newAccount(conf.PASSWORD)) from_account = nocollusion_w3.toChecksumAddress(conf.ADDRESS) nocollusion_w3.personal.unlockAccount(from_account, conf.PASSWORD, 666666) trans_hex = transaction(nocollusion_w3, from_account, new_account) eth.waitForTransactionReceipt(HexBytes(trans_hex).hex()) # 新账户把钱转给其他账户 new_account2 = nocollusion_w3.toChecksumAddress( nocollusion_w3.personal.newAccount(conf.PASSWORD)) before_value = eth.getBalance(new_account2) nocollusion_w3.personal.unlockAccount(new_account, conf.PASSWORD, 666666) trans_hex2 = transaction(nocollusion_w3, new_account, new_account2, value=100) eth.waitForTransactionReceipt(HexBytes(trans_hex2).hex()) after_value = eth.getBalance(new_account2) assert after_value - before_value == 100, '交易失败,转账金额未到账'
def __init__(self, url, address, password, privatekey=conf.PRIVATE_KEY): self.web3 = connect_web3(url) if not self.web3.isConnected(): raise Exception("node connection failed") self.eth = Eth(self.web3) self.address = Web3.toChecksumAddress(address) self.privatekey = privatekey self.gasPrice = "0x8250de00" self.gas = "0x6fffffff"
def test_platon_GetBalance(global_running_env): node = global_running_env.get_rand_node() platon = Eth(node.web3) account = global_running_env.account addr = account.account_with_money["address"] from_addr = Web3.toChecksumAddress(addr) # balance = platon.getBalance(from_addr) balance = platon.getBalance(node.web3.pipAddress) assert balance == 0
def test_platon_estimateGas(global_running_env): node = global_running_env.get_rand_node() account = global_running_env.account platon = Eth(node.web3) address = account.account_with_money["address"] nCount = platon.getTransactionCount(Web3.toChecksumAddress(address)) nonce = hex(nCount) # 获取交易的预估值 estimateGas = transaction_func(node=node, from_addr=address, to_addr=to_address, nonce=nonce, gas='') gas = estimateGas print("\n交易预估gas:{}".format(gas)) # 发送交易 tx_hash = transaction_func(node=node, from_addr=address, to_addr=to_address, nonce=nonce, gas=gas) assert len(tx_hash) == 32 print("\n使用预估的交易gas:【{}】,发送交易成功,交易hash:【{}】".format( gas, HexBytes(tx_hash).hex())) nCount = nCount + 1 nonce = hex(nCount) gas = int(estimateGas * 2) tx_hash = transaction_func(node=node, from_addr=address, to_addr=to_address, nonce=nonce, gas=gas) assert len(tx_hash) == 32 print("\n使用大于预估的交易gas:【{}】,发送交易成功,交易hash:【{}】".format( gas, HexBytes(tx_hash).hex())) nCount = nCount + 1 nonce = hex(nCount) gas = int(estimateGas / 2) # 异常测试场景 status = 0 try: transaction_func(node=node, from_addr=address, to_addr=to_address, nonce=nonce, gas=gas) status = 1 except Exception as e: print("\n使用小于预估的交易gas:【{}】,发送交易失败,error message:{}".format(gas, e)) assert status == 0
def __init__(self, url, address, privatekey, chainid=101): self.web3 = connect_web3(url) if not self.web3.isConnected(): raise Exception("node connection failed") self.eth = Eth(self.web3) self.address = Web3.toChecksumAddress(address) self.privatekey = privatekey self.gasPrice = 1000000000 self.gas = "0x6fffff" self.chainid = chainid
def test_platon_GetBalance(global_running_env): node = global_running_env.get_rand_node() platon = Eth(node.web3) account = global_running_env.account addr = account.account_with_money["address"] from_addr = Web3.toChecksumAddress(addr) balance = platon.getBalance(from_addr) print("\n当前账户【{}】的余额为:{}".format(from_addr, balance)) balance = platon.getBalance("0x1111111111111111111111111111111111111111") assert balance == 0 print("\n当前不存在的账户【{}】余额为:{}".format( "0x1111111111111111111111111111111111111111", balance))
def test_platon_getTransactionReceipt_unmined(self, unlocked_account): platon = Eth(unlocked_account['node'].web3) txn_hash = platon.sendTransaction({ 'from': unlocked_account['address'], 'to': unlocked_account['address'], 'value': 1, 'gas': 21000, 'gasPrice': platon.gasPrice, }) receipt = platon.getTransactionReceipt(txn_hash) assert receipt is None
def test_platon_sendTransaction_withWrongAddress(self, unlocked_account): platon = Eth(unlocked_account['node'].web3) txn_params = { 'from': UNKNOWN_ADDRESS, 'to': unlocked_account['address'], 'value': 1, 'gas': 21000, 'gasPrice': platon.gasPrice, } with pytest.raises(ValueError): platon.sendTransaction(txn_params)
def test_platon_gasPrice(global_running_env): node = global_running_env.get_rand_node() platon = Eth(node.web3) account = global_running_env.account from_address = account.account_with_money["address"] nCount = platon.getTransactionCount(Web3.toChecksumAddress(from_address)) nonce = hex(nCount) gasprice = node.eth.gasPrice tx_hash = transaction_func(node=node, from_addr=from_address, to_addr=to_address, nonce=nonce, gasPrice=gasprice) assert len(tx_hash) == 32 print("\n使用建议的交易gasprice:{},发送交易成功,交易hash:{}".format( gasprice, HexBytes(tx_hash).hex())) gasprice = node.eth.gasPrice * 2 nCount = nCount + 1 nonce = hex(nCount) tx_hash = transaction_func(node=node, from_addr=from_address, to_addr=to_address, nonce=nonce, gasPrice=gasprice) assert len(tx_hash) == 32 print("\n使用大于建议的交易gasprice,发送交易成功,交易hash:{}, gasprice:{}".format( HexBytes(tx_hash).hex(), gasprice)) gasprice = int(node.eth.gasPrice / 2) nCount = nCount + 1 nonce = hex(nCount) # 异常测试场景 status = 0 try: transaction_func(node=node, from_addr=from_address, to_addr=to_address, nonce=nonce, gasPrice=gasprice) status = 1 except Exception as e: print( "\n使用小于建议的交易gasprice:{}, nonce:{}, 发送交易失败,error message:{}".format( gasprice, nonce, e)) assert status == 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 test_platon_replaceTransaction_gas_price_too_low(self, unlocked_account): platon = Eth(unlocked_account['node'].web3) address = unlocked_account['address'] txn_params = { 'from': address, 'to': address, 'value': 1, 'gas': 21000, 'gasPrice': platon.gasPrice, } txn_hash = platon.sendTransaction(txn_params) txn_params['gasPrice'] = 9 with pytest.raises(ValueError): platon.replaceTransaction(txn_hash, txn_params)
def test_platon_replaceTransaction_non_existing_transaction(self, unlocked_account): platon = Eth(unlocked_account['node'].web3) txn_params = { 'from': unlocked_account['address'], 'to': unlocked_account['address'], 'value': 1, 'gas': 21000, 'gasPrice': platon.gasPrice, } with pytest.raises(ValueError): platon.replaceTransaction( '0x98e8cc09b311583c5079fa600f6c2a3bea8611af168c52e4b60b5b243a441997', txn_params )
def test_accounts(self, global_test_env): env = global_test_env node = env.get_rand_node() platon = Eth(node.web3) accounts_before = platon.accounts i = 0 while i < 10: env.account.generate_account_in_node(node, '123456') i += 1 accounts_after = platon.accounts assert is_list_like(accounts_after) assert len(accounts_after) == len(accounts_before) + 10 assert all((account for account in accounts_after))
def sendTransaction(self, connect, data, from_address, to_address, gasPrice, gas, value, check_address=True): platon = Eth(connect) account = self.accounts[from_address] if check_address: to_address = Web3.toChecksumAddress(to_address) tmp_from_address = Web3.toChecksumAddress(from_address) nonce = platon.getTransactionCount(tmp_from_address) # if nonce < account['nonce']: # nonce = account['nonce'] transaction_dict = { "to": to_address, "gasPrice": gasPrice, "gas": gas, "nonce": nonce, "data": data, "chainId": self.chain_id, "value": value, 'from': tmp_from_address, } # log.debug("account['prikey']:::::::{}".format(account['prikey'])) signedTransactionDict = platon.account.signTransaction( transaction_dict, account['prikey']) # log.debug("signedTransactionDict:::::::{},nonce::::::::::{}".format(signedTransactionDict, nonce)) data = signedTransactionDict.rawTransaction result = HexBytes(platon.sendRawTransaction(data)).hex() # log.debug("result:::::::{}".format(result)) res = platon.waitForTransactionReceipt(result) account['nonce'] = nonce + 1 self.accounts[from_address] = account return res
def test_platon_replaceTransaction_incorrect_nonce(self, unlocked_account): platon = Eth(unlocked_account['node'].web3) address = unlocked_account['address'] txn_params = { 'from': address, 'to': address, 'value': 1, 'gas': 21000, 'gasPrice': platon.gasPrice, } txn_hash = platon.sendTransaction(txn_params) txn = platon.getTransaction(txn_hash) txn_params['gasPrice'] = platon.gasPrice * 2 txn_params['nonce'] = int(txn['nonce'], 16) + 1 with pytest.raises(ValueError): platon.replaceTransaction(txn_hash, txn_params)
def test_platon_replaceTransaction_already_mined(self, unlocked_account): platon = Eth(unlocked_account['node'].web3) address = unlocked_account['address'] txn_params = { 'from': address, 'to': address, 'value': 76, 'gas': 21000, 'gasPrice': platon.gasPrice * 4, } txn_hash = platon.sendTransaction(txn_params) txn_params['gasPrice'] = platon.gasPrice * 5 platon.waitForTransactionReceipt(txn_hash) with pytest.raises(ValueError): platon.replaceTransaction(txn_hash, txn_params)
def test_platon_replaceTransaction_gas_price_defaulting_minimum(self, unlocked_account): platon = Eth(unlocked_account['node'].web3) address = unlocked_account['address'] txn_params = { 'from': address, 'to': address, 'value': 1, 'gas': 21000, 'gasPrice': platon.gasPrice, } txn_hash = platon.sendTransaction(txn_params) txn_params.pop('gasPrice') replace_txn_hash = platon.replaceTransaction(txn_hash, txn_params) replace_txn = platon.getTransaction(replace_txn_hash) # todo minimum gas price is what assert replace_txn['gasPrice'] == 110000000