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 connect_web3(url, chain_id=100): """ Connect to the web3 service, add block query middleware, use to implement eth_getBlockByHash, eth_getBlockByNumber, etc. :param url: :param chain_id: :return: """ if "ws" in url: w3 = Web3(WebsocketProvider(url), chain_id=chain_id) else: w3 = Web3(HTTPProvider(url), chain_id=chain_id) w3.middleware_stack.inject(geth_poa_middleware, layer=0) return w3
def w3(open_port, start_websocket_server): # need new event loop as the one used by server is already running event_loop = asyncio.new_event_loop() endpoint_uri = 'ws://127.0.0.1:{}'.format(open_port) event_loop.run_until_complete(wait_for_ws(endpoint_uri, event_loop)) provider = WebsocketProvider(endpoint_uri, websocket_timeout=0.01) return Web3(provider)
def transfer_sign(from_address, to_address, value, nonce, gas_price, from_prikey, chain_id) -> dict: transaction_dict = { "to": Web3.toChecksumAddress(to_address), "gasPrice": gas_price, "gas": 21000, "nonce": nonce, "chainId": chain_id, "value": value, 'from': Web3.toChecksumAddress(from_address), } ret = Eth.account.signTransaction(transaction_dict, from_prikey) transaction_dict.update( {'rawTransaction': HexBytes(ret.rawTransaction).hex()}) return transaction_dict
def test_set_address(ens, name, full_name, namehash_hex, TEST_ADDRESS): assert ens.address(name) is None owner = ens.owner('tester') ens.setup_address(name, TEST_ADDRESS) assert is_same_address(ens.address(name), TEST_ADDRESS) # check that .eth is only appended if guess_tld is True namehash = Web3.toBytes(hexstr=namehash_hex) normal_name = ens.nameprep(full_name) if ens.nameprep(name) == normal_name: assert is_same_address(ens.address(name, guess_tld=False), TEST_ADDRESS) else: assert ens.address(name, guess_tld=False) is None # check that the correct namehash is set: assert is_same_address( ens.resolver(normal_name).addr(namehash), TEST_ADDRESS) # check that the correct owner is set: assert ens.owner(name) == owner ens.setup_address(name, None) assert ens.address(name) is None
def test_identifier_quit_delegate(self): """ 委托验证节点,验证节点退出后,再成为验证节点,再去委托:预期有2个委托消息 """ log.info("转账到钱包3") self.transaction(self.w3_list[0], self.address, to_address=self.account_list[2]) log.info("转账到钱包4") self.transaction(self.w3_list[0], self.address, to_address=self.account_list[3]) log.info("质押节点3:{}成为验证节点".format(self.nodeid_list2[2])) self.ppos_noconsensus_3.createStaking(0, self.account_list[2], self.nodeid_list2[2], self.externalId, self.nodeName, self.website, self.details, self.amount, self.programVersion) log.info("钱包4:{}进行委托".format(self.account_list[3])) self.ppos_noconsensus_4.delegate(0,self.nodeid_list2[2],50) log.info("质押节点3退出验证人{}".format(self.nodeid_list2[2])) self.ppos_noconsensus_3.unStaking(self.nodeid_list2[2]) log.info("{}再次成为验证人".format(self.nodeid_list2[2])) self.ppos_noconsensus_3.createStaking(0, self.account_list[2],self.nodeid_list2[2],self.externalId, self.nodeName, self.website, self.details,self.amount,self.programVersion) log.info("钱包4:{}再次进行委托".format(self.account_list[3])) msg = self.ppos_noconsensus_4.delegate(0,self.nodeid_list2[2],100) print(msg) log.info("查询钱包的委托情况") msg = self.ppos_noconsensus_4.getDelegateListByAddr(self.account_list[3]) log.info(msg) log.info(msg["Data"]) print(len(msg["Data"])) assert len(msg["Data"]) == 2 for i in msg["Data"]: assert Web3.toChecksumAddress(i["Addr"]) == self.account_list[3] assert i["NodeId"] == self.nodeid_list2[2]
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 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_verify_transaction(self): ''' @Description: 切换验证人后,测试交易是否成功,所有节点块高是否一致 @param {type} @@@@ @return: @@@@ ''' tx_hash = self.platon_dpos1.eth.sendTransaction(self.send_data) self.platon_dpos1.eth.waitForTransactionReceipt(tx_hash) block_list = [] for w in self.w3_list: block_list.append(w.eth.blockNumber) assert min(block_list) > 60, "区块没有正常增加" assert max(block_list) - min(block_list) < 5, "各节点区块高度差距过高" time.sleep(60) w3 = Web3(Web3.HTTPProvider(self.rpc_dict["node6"])) assert w3.net.peerCount >= 3, "节点node6连接的节点数少于3个"
def test_personal_unlockAccount(test_personal_newAccount): listWallet = test_personal_newAccount.personal.listWallets if len(listWallet) > 0: addr1 = Web3.toChecksumAddress(listWallet[0]["accounts"][0]["address"]) assert True == test_personal_newAccount.personal.unlockAccount(addr1, password) listWallet = test_personal_newAccount.personal.listWallets assert "Unlocked" == listWallet[0]["status"]
def test_personal_lockAccount(test_personal_newAccount): listWallet = test_personal_newAccount.personal.listWallets addr1 = Web3.toChecksumAddress(listWallet[0]["accounts"][0]["address"]) assert True == test_personal_newAccount.personal.lockAccount(addr1) listWallet = test_personal_newAccount.personal.listWallets assert "Locked" == listWallet[0]["status"] print("\n锁钱包成功,钱包地址:{},状态:{}".format(addr1, listWallet[0]["status"]))
def generate_account(self, web3, balance=0): extra_entropy = '' extra_key_bytes = text_if_str(to_bytes, extra_entropy) key_bytes = keccak(os.urandom(32) + extra_key_bytes) privatekey = keys.PrivateKey(key_bytes) address = privatekey.public_key.to_address() address = Web3.toChecksumAddress(address) prikey = privatekey.to_hex()[2:] if balance != 0: self.sendTransaction(web3, '', self.account_with_money['address'], address, web3.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_isConnected_disconnected(): """ Web3.isConnected() returns False when configured with a provider that's not connected to a node. """ web3 = Web3(DisconnectedProvider()) assert web3.isConnected() is False
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_unDelegate_iff(self): """ 验证 大于委托金额赎回 """ msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[2]) if msg['Data'] == "": log.info("质押节点3成为验证节点") self.ppos_noconsensus_3.createStaking(0, self.account_list[2], self.nodeid_list2[2], self.externalId, self.nodeName, self.website, self.details, self.amount, self.programVersion) log.info("钱包4 委托到3 {}") value = 100 self.ppos_noconsensus_4.delegate(0, self.nodeid_list2[2], value) msg = self.ppos_noconsensus_3.getCandidateInfo(self.nodeid_list2[2]) stakingBlockNum = msg["Data"]["StakingBlockNum"] msg = self.ppos_noconsensus_4.getDelegateInfo(stakingBlockNum, self.account_list[3], self.nodeid_list2[2]) data = msg["Data"] """不清楚msg["Data"]对应value是str类型,需要再转字典""" data = json.loads(data) releasedHes = data["ReleasedHes"] releasedHes = Web3.fromWei(releasedHes, 'ether') log.info("委托钱包可赎回的金额单位eth:{}".format(releasedHes)) delegate_value = releasedHes + 20 msg = self.ppos_noconsensus_4.unDelegate(stakingBlockNum, self.nodeid_list2[2], delegate_value) assert msg["Status"] == False err_msg = "withdrewDelegate err: The von of delegate is not enough" assert err_msg in msg["ErrMsg"]
def test_auto_provider_none(): # init without provider succeeds, even when no provider available w3 = Web3() # non-node requests succeed w3.toHex(0) == '0x0' type(w3.providers[0]) == AutoProvider
def test_loukupplan(self): from_address = Web3.toChecksumAddress(conf.ADDRESS) to_address = Web3.toChecksumAddress( self.ppos_link(self.rpc_list).web3.personal.newAccount(self.pwd)) send_data = self.transfer_parameters(to_address, from_address) self.platon_ppos.eth.sendTransaction(send_data) toaddressbalace = self.platon_dpos1.eth.getBalance(to_address) loukupbalace = toaddressbalace / 4 plan = [{ 'Epoch': 3, 'Amount': loukupbalace }, { 'Epoch': 3, 'Amount': loukupbalace }] Ppos.CreateRestrictingPlan(to_address, plan, to_address) result = Ppos.GetRestrictingInfo(to_address, to_address)
def test_loukupplan(self): ''' 验证正常锁仓功能 参数输入: Epoch:1 Amount:50 ether :return: ''' url = CommonMethod.link_list(self) platon_ppos = Ppos(url, self.address, self.chainid) address1, private_key1 = CommonMethod.read_private_key_list() # 签名转账 result = platon_ppos.send_raw_transaction( '', Web3.toChecksumAddress(self.address), Web3.toChecksumAddress(address1), self.base_gas_price, self.base_gas, self.value, self.privatekey) return_info = platon_ppos.eth.waitForTransactionReceipt(result) assert return_info is not None, "转账:{}失败".format(self.value) #查询锁仓账户的余额 lockup_before = platon_ppos.eth.getBalance( conf.FOUNDATIONLOCKUPADDRESS) log.info("发起锁仓账户的余额:{}".format(lockup_before)) #创建锁仓计划 loukupbalace = Web3.toWei(50, 'ether') plan = [{'Epoch': 1, 'Amount': loukupbalace}] result = platon_ppos.CreateRestrictingPlan( address1, plan, privatekey=private_key1, from_address=address1, gasPrice=self.base_gas_price, gas=self.staking_gas) assert result['Status'] == True, "创建锁仓计划返回状态为:{} 有误".format( result['Status']) lockup_after = platon_ppos.eth.getBalance(conf.FOUNDATIONLOCKUPADDRESS) assert lockup_after == lockup_before + loukupbalace, "锁仓账户金额:{}有误".format( lockup_after) #查看锁仓计划明细 detail = platon_ppos.GetRestrictingInfo(address1) assert detail['Status'] == True, "查询锁仓计划信息返回状态为:{}".format( result['Status']) RestrictingInfo = json.loads(detail['Data']) assert RestrictingInfo[ 'balance'] == loukupbalace, "创建锁仓计划金额:{}有误".format(lockup_after)
def transaction_func(node, from_addr="", to_addr=to_address, value=1000, data='', gasPrice='100000000', gas='21068', nonce=0, password=password): transaction_dict = { "from": Web3.toChecksumAddress(from_addr), "to": Web3.toChecksumAddress(to_addr), "value": value, "data": data, "gasPrice": gasPrice, "nonce": nonce, } if gas == '': gas = node.eth.estimateGas(transaction_dict) return gas transaction_dict["gas"] = gas global g_txHash g_txHash = node.personal.sendTransaction(transaction_dict, password) return g_txHash
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_IT_IA_002_to_007(new_genesis_env): """ IT_IA_002:链初始化-查看token发行总量账户初始值 IT_IA_003:链初始化-查看platON基金会账户初始值 IT_IA_004:链初始化-查看激励池账户 IT_IA_005:链初始化-查看剩余总账户 IT_IA_006:链初始化-查看锁仓账户余额 IT_IA_007:链初始化-查看质押账户余额 :return:验证链初始化后token各内置账户初始值 """ # Initialization genesis file Initial amount node_count = len(new_genesis_env.consensus_node_list) default_pledge_amount = Web3.toWei(node_count * 1500000, 'ether') node = new_genesis_env.get_rand_node() community_amount = default_pledge_amount + 259096239000000000000000000 + 62215742000000000000000000 genesis = from_dict(data_class=Genesis, data=new_genesis_env.genesis_config) genesis.economicModel.innerAcc.cdfBalance = community_amount surplus_amount = str(EconomicConfig.TOKEN_TOTAL - community_amount - 200000000000000000000000000) genesis.alloc = { "1000000000000000000000000000000000000003": { "balance": "200000000000000000000000000" }, "0x2e95E3ce0a54951eB9A99152A6d5827872dFB4FD": { "balance": surplus_amount } } new_file = new_genesis_env.cfg.env_tmp + "/genesis.json" genesis.to_file(new_file) new_genesis_env.deploy_all(new_file) # Verify the amount of each built-in account foundation_louckup = node.eth.getBalance(EconomicConfig.FOUNDATION_LOCKUP_ADDRESS) log.info('Initial lock up contract address: {} amount:{}'.format(EconomicConfig.FOUNDATION_LOCKUP_ADDRESS, foundation_louckup)) incentive_pool = node.eth.getBalance(EconomicConfig.INCENTIVEPOOL_ADDRESS) log.info('Incentive pool address:{} amount:{}'.format(EconomicConfig.INCENTIVEPOOL_ADDRESS, incentive_pool)) staking = node.eth.getBalance(EconomicConfig.STAKING_ADDRESS) log.info('Address of pledge contract:{} amount:{}'.format(EconomicConfig.STAKING_ADDRESS, staking)) foundation = node.eth.getBalance(node.web3.toChecksumAddress(EconomicConfig.FOUNDATION_ADDRESS)) log.info('PlatON Foundation address:{} amount:{}'.format(EconomicConfig.FOUNDATION_ADDRESS, foundation)) remain = node.eth.getBalance(node.web3.toChecksumAddress(EconomicConfig.REMAIN_ACCOUNT_ADDRESS)) log.info('Remaining total account address:{} amount:{}'.format(EconomicConfig.REMAIN_ACCOUNT_ADDRESS, remain)) develop = node.eth.getBalance(node.web3.toChecksumAddress(EconomicConfig.DEVELOPER_FOUNDATAION_ADDRESS)) log.info('Community developer foundation address:{} amount:{}'.format(EconomicConfig.DEVELOPER_FOUNDATAION_ADDRESS, develop)) reality_total = foundation_louckup + incentive_pool + staking + foundation + remain + develop log.info("Total issuance of Chuangshi block:{}".format(reality_total)) log.info("--------------Dividing line---------------") assert foundation == 0, "ErrMsg:Initial amount of foundation {}".format(foundation) assert foundation_louckup == 259096239000000000000000000, "ErrMsg:Initial lock up amount of foundation {}".format( foundation_louckup) assert staking == default_pledge_amount, "ErrMsg:Amount of initial pledge account: {}".format(staking) assert incentive_pool == 262215742000000000000000000, "ErrMsg:Initial amount of incentive pool {}".format( incentive_pool) assert remain == int(surplus_amount), "ErrMsg:Initial amount of remaining total account {}".format(remain) assert develop == 0, "ErrMsg:Community developer foundation account amount {}".format(develop) assert reality_total == EconomicConfig.TOKEN_TOTAL, "ErrMsg:Initialize release value {}".format(reality_total)
def bytes32(val): if isinstance(val, int): result = Web3.toBytes(val) else: raise TypeError('val %r could not be converted to bytes') if len(result) < 32: return result.rjust(32, b'\0') else: return result
def test_labelhash(ens, label, expected_hash): if isinstance(expected_hash, type): with pytest.raises(expected_hash): ens.labelhash(label) else: labelhash = ens.labelhash(label) assert isinstance(labelhash, bytes) hash_hex = Web3.toHex(labelhash) assert hash_hex == expected_hash
def test_IP_PR_006_1(reset_cfg_env_node): value = Web3.toWei(100, 'ether') genesis = reset_cfg_env_node.genesis genesis.economicModel.staking.operatingThreshold = value new_file = reset_cfg_env_node.genesis_path genesis.to_file(new_file) reset_cfg_env_node.deploy_me(new_file) config = reset_cfg_env_node.debug.economicConfig() assert value == config["staking"]["operatingThreshold"]
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_transfer_normal(self): ''' 验证初始化之后账户之间转账 :return: ''' platon_ppos = self.ppos_link() address1 = '0x684b43Cf53C78aA567840174a55442d7a9282679' privatekey1 = 'a5ac52e828e2656309933339cf12d30755f918e368fffc7c265b55da718ff893' try: platon_ppos.send_raw_transaction( '', Web3.toChecksumAddress(conf.ADDRESS), Web3.toChecksumAddress(address1), self.gasPrice, self.gas, self.value, conf.PRIVATE_KEY) Balance1 = platon_ppos.eth.getBalance('address1') assert Web3.toWei(self.value, 'ether') == Balance1 except: status = 1 assert status == 0, '账号余额不足,无法发起转账'
def test_personal_signTransaction(global_running_env): node = global_running_env.get_rand_node() account = global_running_env.account platon = Eth(node.web3) addr = account.account_with_money["address"] nonce = hex(platon.getTransactionCount(Web3.toChecksumAddress(addr))) transaction_dict = { "from": Web3.toChecksumAddress(addr), "to": Web3.toChecksumAddress(to_address), "value": "0x10000000000000", "data": "0x11", "gasPrice": "0x8250de00", "gas": "0x6fffffff", "nonce": nonce, } ret = node.personal.signTransaction(transaction_dict, password) assert ret is not None
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_back_unStaking_commissioned(self): """ 用例id 82 验证人申请退回质押金,委托金额还生效 用例id 83 验证人退出后,委托人信息还存在 """ log.info("转账到钱包1") self.transaction(self.w3_list[0], self.address, to_address=self.account_list[0]) log.info("转账到钱包2") self.transaction(self.w3_list[0], self.address, to_address=self.account_list[1]) msg = self.ppos_noconsensus_1.getCandidateInfo(self.nodeid_list2[0]) if msg['Data']== "": log.info("节点1再次成为验证人") self.ppos_noconsensus_1.createStaking(0, self.account_list[0], self.nodeid_list2[0], self.externalId, self.nodeName, self.website, self.details, self.amount, self.programVersion) log.info("钱包2进行委托100") self.ppos_noconsensus_2.delegate(0, self.nodeid_list2[0], 100) log.info("节点1退出验证人") self.ppos_noconsensus_1.unStaking(self.nodeid_list2[0]) msg = self.ppos_noconsensus_2.getDelegateListByAddr(self.account_list[1]) log.info(msg) StakingBlockNum = msg["Data"][0]["StakingBlockNum"] msg = self.ppos_noconsensus_2.getDelegateInfo(StakingBlockNum,self.account_list[1],self.nodeid_list2[0]) log.info(msg) data = msg["Data"] data = json.loads(data) log.info(data) assert Web3.toChecksumAddress(data["Addr"]) == self.account_list[1] assert data["NodeId"] == self.nodeid_list2[0] else: log.info("钱包2进行委托100") self.ppos_noconsensus_2.delegate(0, self.nodeid_list2[0], 100) log.info("节点1退出验证人") self.ppos_noconsensus_1.unStaking(self.nodeid_list2[0]) msg = self.ppos_noconsensus_2.getDelegateListByAddr(self.account_list[1]) log.info(msg) StakingBlockNum = msg["Data"][0]["StakingBlockNum"] msg = self.ppos_noconsensus_2.getDelegateInfo(StakingBlockNum,self.account_list[1],self.nodeid_list2[0]) log.info(msg) data = msg["Data"] data = json.loads(data) log.info(data) assert Web3.toChecksumAddress(data["Addr"]) == self.account_list[1] assert data["NodeId"] == self.nodeid_list2[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