diff --git a/dev-support/dep_pip3.sh b/dev-support/dep_pip3.sh index 2d2e6fe938..da40ab3401 100755 --- a/dev-support/dep_pip3.sh +++ b/dev-support/dep_pip3.sh @@ -2,7 +2,7 @@ set -e -pip3 install cfx-account eth-utils py-ecc rlp trie coincurve safe-pysha3 web3==7.4.0 py-solc-x jsonrpcclient==3.3.6 asyncio websockets pyyaml numpy +pip3 install cfx-account eth-utils py-ecc rlp trie coincurve safe-pysha3 conflux-web3==1.4.0b5 web3 py-solc-x jsonrpcclient==3.3.6 asyncio websockets pyyaml numpy python3 -m solcx.install v0.5.17 diff --git a/tests/admin_at_creation_test.py b/tests/admin_at_creation_test.py index b3d35539c2..e2ef132c61 100755 --- a/tests/admin_at_creation_test.py +++ b/tests/admin_at_creation_test.py @@ -1,14 +1,12 @@ #!/usr/bin/env python3 -from test_framework.block_gen_thread import BlockGenThread -from test_framework.contracts import ConfluxTestFrameworkForContract, ZERO_ADDRESS, Contract +from test_framework.test_framework import ConfluxTestFramework from test_framework.mininode import * from test_framework.util import * -from web3 import Web3 -class ClearAdminTest(ConfluxTestFrameworkForContract): +class ClearAdminTest(ConfluxTestFramework): def set_test_params(self): - super().set_test_params() self.num_nodes = 8 + self._add_genesis_secrets(1, "core") def setup_network(self): self.setup_nodes() @@ -16,40 +14,42 @@ def setup_network(self): sync_blocks(self.nodes) def run_test(self): - block_gen_thread = BlockGenThread(self.nodes, self.log) - block_gen_thread.start() + self.start_block_gen() + self.deploy_create2() - genesis_addr = self.genesis_addr - test_account_key = self.genesis_key2 - test_account_addr = self.genesis_addr2 + genesis_addr = self.core_accounts[0].address + test_account = self.core_accounts[1] + test_account_addr = self.core_accounts[1].address create2factory_addr = self.create2factory.address # Clear admin by non-admin (fail) self.log.info("Test unable to clear admin by non-admin.") - self.adminControl.functions.setAdmin(create2factory_addr, ZERO_ADDRESS).cfx_transact(priv_key=test_account_key) - assert_equal(self.client.get_admin(create2factory_addr), genesis_addr.lower()) + self.internal_contract("AdminControl").functions.setAdmin(create2factory_addr, ZERO_ADDRESS).transact({ + "from": test_account.address + }) + assert_equal(self.cfx.get_admin(create2factory_addr), genesis_addr) self.log.info("Test contract creation by itself") - clear_admin_test_contract: Contract = self.cfx_contract("AdminTestContract").deploy() + clear_admin_test_contract = self.deploy_contract("AdminTestContract") self.log.info(" contract created at %s" % clear_admin_test_contract.address) self.log.info("Test clear admin at contract creation through create2factory") # Deploy the contract. - clear_admin_test_contract2: Contract = self.cfx_contract("AdminTestContract").deploy2(seed = 0) - assert_equal(self.client.get_admin(clear_admin_test_contract2.address), ZERO_ADDRESS) + clear_admin_test_contract2 = self.deploy_contract_2("AdminTestContract", 0) + assert_equal(self.cfx.get_admin(clear_admin_test_contract2.address).hex_address, ZERO_ADDRESS) # type: ignore # The owner of create2factory_addr isn't hijacked. self.log.info("Test unable to hijack set admin.") - assert_equal(self.client.get_admin(create2factory_addr), genesis_addr.lower()) + assert_equal(self.cfx.get_admin(create2factory_addr), genesis_addr) self.log.info("Test unable to hijack owner through deployAndHijackAdmin") # Create a new contract through deployAndHijackAdmin. - create_data = self.cfx_contract("BlackHole").constructor().data() + create_data = self.cfx_contract("BlackHole").constructor()._encode_data_in_transaction() fn_call = clear_admin_test_contract.functions.deployAndHijackAdmin(create_data) - created_address = fn_call.cfx_call(sender = test_account_addr) - fn_call.cfx_transact(priv_key = test_account_key, value = 123, decimals = 1) - assert_equal(self.client.get_admin(created_address), test_account_addr.lower()) + created_address = fn_call.call({"from": test_account_addr}) + fn_call.transact({"from": test_account.address, "value": 123}).executed() + assert_equal(self.cfx.get_admin(created_address), test_account_addr) self.log.info("Pass") diff --git a/tests/admin_control_test.py b/tests/admin_control_test.py index edde92139e..7940e04d18 100755 --- a/tests/admin_control_test.py +++ b/tests/admin_control_test.py @@ -1,68 +1,89 @@ #!/usr/bin/env python3 +from cfx_utils import CFX, Drip from conflux.transactions import CONTRACT_DEFAULT_GAS, charged_of_huge_gas -from test_framework.contracts import ConfluxTestFrameworkForContract +from test_framework.test_framework import ConfluxTestFramework from test_framework.util import assert_equal -from web3 import Web3 -from web3.contract import Contract -class AdminControlTest(ConfluxTestFrameworkForContract): +class AdminControlTest(ConfluxTestFramework): def set_test_params(self): - super().set_test_params() self.num_nodes = 1 def run_test(self): + self.w3 = self.cw3 pay_contract = self.cfx_contract("CheckPay") admin_control_contract = self.internal_contract("AdminControl") self.log.info("Initializing contract") - client = self.client gas = CONTRACT_DEFAULT_GAS - - # Setup balance for node 0 - (addr, priv_key) = client.rand_account() - self.log.info("addr=%s priv_key=%s", addr, priv_key) - self.cfx_transfer(addr, value = 5) - assert_equal(client.get_balance(addr), 5000000000000000000) + # Setup balance for node 0 + acct1 = self.cfx.account.create() + self.log.info("addr=%s priv_key=%s", acct1.address, acct1.key.hex()) + self.cfx_transfer(acct1.hex_address, value = 5) + assert_equal(self.cfx.get_balance(acct1.address).to("CFX"), CFX(5)) + self.w3.wallet.add_account(acct1) - (addr2, priv_key2) = client.rand_account() - self.log.info("addr2=%s priv_key2=%s", addr2, priv_key2) - self.cfx_transfer(addr2, value = 5) - assert_equal(client.get_balance(addr2), 5000000000000000000) + acct2 = self.cfx.account.create() + self.log.info("addr2=%s priv_key2=%s", acct2.address, acct2.key.hex()) + self.cfx_transfer(acct2.hex_address, value = 5) + assert_equal(self.cfx.get_balance(acct2.address).to("CFX"), CFX(5)) + self.w3.wallet.add_account(acct2) # deploy pay contract - pay_contract: Contract = self.cfx_contract("CheckPay").deploy(transact_args=dict(priv_key=priv_key, storage_limit=512, gas=gas)) + pay_contract = self.deploy_contract(name="CheckPay", transact_args={ + "from": acct1.address, + "storageLimit": 512, + "gas": gas, + "gasPrice": 1 + }) contract_addr = pay_contract.address self.log.info("contract_addr={}".format(pay_contract.address)) - assert_equal(client.get_collateral_for_storage(addr), 512 * 976562500000000) - assert_equal(client.get_balance(contract_addr), 0) + assert_equal(self.cfx.get_collateral_for_storage(acct1.address), 512 * 976562500000000) + assert_equal(self.cfx.get_balance(contract_addr), 0) # deposit 10**18 - b0 = client.get_balance(addr) - pay_contract.functions.recharge().cfx_transact(priv_key=priv_key, value = 1, gas=gas) - assert_equal(client.get_balance(contract_addr), 10 ** 18) - assert_equal(client.get_balance(addr), b0 - 10 ** 18 - charged_of_huge_gas(gas)) - assert_equal(client.get_admin(contract_addr), addr.lower()) + b0 = self.cfx.get_balance(acct1.address) + pay_contract.functions.recharge().transact({ + "from": acct1.address, + "value": CFX(1), + "gas": gas, + "gasPrice": 1, + }).executed() + assert_equal(self.cfx.get_balance(contract_addr), CFX(1)) + assert_equal(self.cfx.get_balance(acct1.address), b0 - CFX(1) - Drip(charged_of_huge_gas(gas))) + assert_equal(self.cfx.get_admin(contract_addr), acct1.address.lower()) # transfer admin (fail) - admin_control_contract.functions.setAdmin(contract_addr, addr2).cfx_transact(priv_key=priv_key2, gas=gas) - assert_equal(client.get_admin(contract_addr), addr.lower()) - assert_equal(client.get_balance(addr2), 5 * 10 ** 18 - charged_of_huge_gas(gas)) + admin_control_contract.functions.setAdmin(contract_addr, acct2.address).transact({ + "from": acct2.address, + "gas": gas, + "gasPrice": 1 + }).executed() + assert_equal(self.cfx.get_admin(contract_addr), acct1.address.lower()) + assert_equal(self.cfx.get_balance(acct2.address), CFX(5) - Drip(charged_of_huge_gas(gas))) # transfer admin (success) - admin_control_contract.functions.setAdmin(contract_addr, addr2).cfx_transact(priv_key=priv_key, gas=gas) - assert_equal(client.get_admin(contract_addr), addr2.lower()) + admin_control_contract.functions.setAdmin(contract_addr, acct2.address).transact({ + "from": acct1.address, + "gas": gas, + "gasPrice": 1, + }).executed() + assert_equal(self.cfx.get_admin(contract_addr), acct2.address.lower()) # destroy - b0 = client.get_balance(addr) - admin_control_contract.functions.destroy(contract_addr).cfx_transact(priv_key=priv_key2, gas=gas) - assert_equal(client.get_balance(contract_addr), 0) - assert_equal(client.get_balance(addr2), 6 * 10 ** 18 - charged_of_huge_gas(gas) * 2) - assert_equal(client.get_collateral_for_storage(addr), 0) - assert_equal(client.get_balance(addr), b0 + 512 * 976562500000000) + b0 = self.cfx.get_balance(acct1.address) + admin_control_contract.functions.destroy(contract_addr).transact({ + "from": acct2.address, + "gas": gas, + "gasPrice": 1, + }).executed() + assert_equal(self.cfx.get_balance(contract_addr), 0) + assert_equal(self.cfx.get_balance(acct2.address), CFX(6) - Drip(charged_of_huge_gas(gas) * 2)) + assert_equal(self.cfx.get_collateral_for_storage(acct1.address), 0) + assert_equal(self.cfx.get_balance(acct1.address), b0 + Drip(512 * 976562500000000)) self.log.info("Pass") diff --git a/tests/blockhash_test.py b/tests/blockhash_test.py index 410100f07d..234fbebce3 100644 --- a/tests/blockhash_test.py +++ b/tests/blockhash_test.py @@ -1,10 +1,13 @@ from conflux.utils import * -from test_framework.contracts import ConfluxTestFrameworkForContract +from test_framework.test_framework import ConfluxTestFramework from test_framework.util import * from test_framework.mininode import * -class BlockHashFromStateTest(ConfluxTestFrameworkForContract): +class BlockHashFromStateTest(ConfluxTestFramework): + def set_test_params(self): + self.num_nodes = 1 + def run_test(self): genesis_hash = self.client.block_by_epoch(0)["hash"] for _ in range(5): @@ -12,19 +15,19 @@ def run_test(self): self.wait_for_block(1000) - test_contract = self.cfx_contract("BlockHash").deploy() - context_contract = self.internal_contract("ConfluxContext"); + test_contract = self.deploy_contract("BlockHash") + context_contract = self.internal_contract("ConfluxContext") for i in range(100, 1001, 100): - assert_equal(test_contract.functions.getBlockHash(i).cfx_call().hex(), self.client.block_by_block_number(i)["hash"][2:]) - assert_equal(context_contract.functions.epochHash(i).cfx_call().hex(), self.client.block_by_epoch(i)["hash"][2:]) + assert_equal(test_contract.functions.getBlockHash(i).call().hex(), self.client.block_by_block_number(i)["hash"][2:]) + assert_equal(context_contract.functions.epochHash(i).call().hex(), self.client.block_by_epoch(i)["hash"][2:]) self.log.info("Generate 65536+ blocks") for i in range(5000, 66000, 5000): self.wait_for_block(i) self.wait_for_block(66000) - assert_equal(test_contract.functions.getBlockHash(100).cfx_call().hex(), "0" * 64) - assert_equal(context_contract.functions.epochHash(100).cfx_call().hex(), "0" * 64) + assert_equal(test_contract.functions.getBlockHash(100).call().hex(), "0" * 64) + assert_equal(context_contract.functions.epochHash(100).call().hex(), "0" * 64) def wait_for_block(self, block_number, have_not_reach=False): diff --git a/tests/cip107_test.py b/tests/cip107_test.py index 6c14b5b7f0..e93e87b3e9 100644 --- a/tests/cip107_test.py +++ b/tests/cip107_test.py @@ -1,8 +1,9 @@ -from conflux.rpc import RpcClient +from decimal import Decimal +from cfx_utils import CFX from conflux.utils import * from test_framework.util import * from test_framework.mininode import * -from test_framework.contracts import ConfluxTestFrameworkForContract +from test_framework.test_framework import ConfluxTestFramework BASE = int(1e18) CIP107_NUMBER = 100 @@ -11,7 +12,7 @@ class CheckCollateral: - def __init__(self, framework: ConfluxTestFrameworkForContract, account): + def __init__(self, framework: "CIP107Test", account): self.framework = framework self.account = account @@ -30,26 +31,25 @@ def __init__(self, framework: ConfluxTestFrameworkForContract, account): def tick(self): client = self.framework.client - collateralInfo = client.get_collateral_info() - self.total_storage_point = int( - collateralInfo["convertedStoragePoints"], 0) - self.total_collateral = int(collateralInfo["totalStorageTokens"], 0) - self.total_used_storage_point = int( - collateralInfo["usedStoragePoints"], 0) - - self.account_used_storage_point = client.get_used_storage_points( - self.account) - self.account_unused_storage_point = client.get_unused_storage_points( - self.account) - self.account_used_collateral = client.get_collateral_for_storage( - self.account) - self.account_unused_collateral = client.get_sponsor_balance_for_collateral( - self.account) + cfx = self.framework.cfx + collateralInfo = cfx.get_collateral_info() + self.total_storage_point = collateralInfo["convertedStoragePoints"] + self.total_collateral = collateralInfo["totalStorageTokens"] + self.total_used_storage_point = collateralInfo["usedStoragePoints"] + + self.account_used_storage_point = cfx.get_sponsor_info( + self.account)["usedStoragePoints"] + self.account_unused_storage_point = cfx.get_sponsor_info( + self.account)["availableStoragePoints"] + self.account_used_collateral = int(cfx.get_collateral_for_storage( + self.account)) + self.account_unused_collateral = cfx.get_sponsor_info( + self.account)["sponsorBalanceForCollateral"].value # Compute adjusted total_issued, elimating influence from block reward and storage interest - supplyInfo = client.get_supply_info() + supplyInfo = cfx.get_supply_info() - x = int(supplyInfo["totalIssued"], 0) // (BASE//160) * (BASE//160) + x = supplyInfo["totalIssued"].value // (BASE//160) * (BASE//160) x -= client.epoch_number() * 2 * BASE self.total_issued = x @@ -75,12 +75,12 @@ def checked_tick(self, **kwargs): else: expect_diff = kwargs.get(attr, 0) * BASE / 16 - if actual_diff != expect_diff: + if int(actual_diff) != int(expect_diff): raise AssertionError( - f"Assert attribute {attr} failed: expected {expect_diff}, actual {actual_diff}: {old[attr]} --> {getattr(self, attr)}") + f"Assert attribute {attr} failed: expected {int(expect_diff)}, actual {int(actual_diff)}: {old[attr]} --> {getattr(self, attr)}") actual_value = self.framework.sponsorControl.functions.getAvailableStoragePoints( - self.account).cfx_call() + self.account).call() assert_equal(self.account_unused_storage_point, actual_value) def __str__(self): @@ -95,40 +95,50 @@ def __str__(self): class StorageContract: - def __init__(self, framework: ConfluxTestFrameworkForContract, seed=0): + def __init__(self, framework: "CIP107Test", seed=0): self.framework = framework - self.storage = framework.cfx_contract("Storage").deploy2(seed).functions + self.storage = framework.deploy_contract_2("Storage", seed).functions def set_sponsor(self, value): sponsorContract = self.framework.sponsorControl.functions sponsorContract.addPrivilegeByAdmin( - self.storage.address, [ZERO_ADDRESS]).cfx_transact() + self.storage.address, [ZERO_ADDRESS]).transact().executed() sponsorContract.setSponsorForCollateral( - self.storage.address).cfx_transact(value=value) + self.storage.address).transact({ + "value": CFX(Decimal(value)) + }).executed() def set_entry(self, index): if isinstance(index, list): for i in index: - self.storage.change(i).cfx_transact(storage_limit=64) + self.storage.change(i).transact({ + "storageLimit": 64 + }).executed() else: - self.storage.change(index).cfx_transact(storage_limit=64) + self.storage.change(index).transact({ + "storageLimit": 64 + }).executed() def reset_entry(self, index): if isinstance(index, list): for i in index: - self.storage.reset(i).cfx_transact(storage_limit=64) + self.storage.reset(i).transact({ + "storageLimit": 64 + }).executed() else: - self.storage.reset(index).cfx_transact(storage_limit=64) + self.storage.reset(index).transact({ + "storageLimit": 64 + }).executed() def suicide(self): - adminControl = self.framework.adminControl.functions - adminControl.destroy(self.storage.address).cfx_transact() + adminControl = self.framework.internal_contract("AdminControl").functions + adminControl.destroy(self.storage.address).transact().executed() def address(self): return self.storage.address -class CIP107Test(ConfluxTestFrameworkForContract): +class CIP107Test(ConfluxTestFramework): def set_test_params(self): self.num_nodes = 1 self.conf_parameters["executive_trace"] = "true" @@ -139,6 +149,9 @@ def set_test_params(self): self.conf_parameters["dao_vote_transition_height"] = 1 def run_test(self): + self.w3 = self.cw3 + self.sponsorControl = self.internal_contract(name="SponsorWhitelistControl") + self.deploy_create2() # Task 1: test if the collateral can be maintained correctly self.test_collateral_maintain() @@ -155,8 +168,14 @@ def test_change_sponsor(self): storage.set_sponsor(0.25) check.checked_tick( total_storage_point=2, total_collateral=None, total_issued=-2, account_unused_collateral=2, account_unused_storage_point=2) - - self.sponsorControl.functions.setSponsorForCollateral(storage.address()).cfx_transact(value=0.5, priv_key=-1) + + acct = self.cfx.account.from_key(self.evm_accounts[0].key) + self.w3.wallet.add_account(acct) + + self.sponsorControl.functions.setSponsorForCollateral(storage.address()).transact({ + "value": CFX(Decimal(0.5)), + "from": acct.address + }).executed() check.checked_tick( total_storage_point=3, total_collateral=None, total_issued=-3, account_unused_collateral=3, account_unused_storage_point=3) @@ -169,11 +188,11 @@ def test_params_update(self): paramsControl = self.internal_contract("ParamsControl").functions # Obtain DAO Votes - stakingControl.deposit(1_000_000 * BASE).cfx_transact() + stakingControl.deposit(1_000_000 * BASE).transact().executed() current_block_number = int(self.client.get_status()["blockNumber"], 0) locked_time = 5 * 15_768_000 # MINED_BLOCK_COUNT_PER_QUARTER stakingControl.voteLock( - 1_000_000 * BASE, current_block_number + locked_time).cfx_transact() + 1_000_000 * BASE, current_block_number + locked_time).transact().executed() # Set block number to the middle of a voting period vote_tick = int((self.client.epoch_number() + CIP104_PERIOD / 2) // @@ -181,9 +200,9 @@ def test_params_update(self): self.wait_for_block(vote_tick) # Vote - current_round = paramsControl.currentRound().cfx_call() + current_round = paramsControl.currentRound().call() paramsControl.castVote(current_round, [{"topic_index": 2, "votes": [ - 0, 1_000_000 * BASE, 0]}]).cfx_transact() + 0, 1_000_000 * BASE, 0]}]).transact().executed() storage.set_sponsor(3.75) check.checked_tick( @@ -191,31 +210,31 @@ def test_params_update(self): self.wait_for_block(vote_tick + CIP104_PERIOD * 1, have_not_reach=True) paramsControl.castVote( - current_round + 1, [{"topic_index": 2, "votes": [0, 1_000_000 * BASE, 0]}]).cfx_transact() + current_round + 1, [{"topic_index": 2, "votes": [0, 1_000_000 * BASE, 0]}]).transact().executed() storage.set_sponsor(3.75) check.checked_tick( total_storage_point=30, total_issued=-30, total_collateral=None, account_unused_collateral=30, account_unused_storage_point=30) self.wait_for_block(vote_tick + CIP104_PERIOD * 2, have_not_reach=True) paramsControl.castVote( - current_round + 2, [{"topic_index": 2, "votes": [0, 0, 1_000_000 * BASE]}]).cfx_transact() + current_round + 2, [{"topic_index": 2, "votes": [0, 0, 1_000_000 * BASE]}]).transact().executed() storage.set_sponsor(3.75) check.checked_tick( total_storage_point=40, total_issued=-40, total_collateral=None, account_unused_collateral=20, account_unused_storage_point=40) self.wait_for_block(vote_tick + CIP104_PERIOD * 3, have_not_reach=True) paramsControl.castVote( - current_round + 3, [{"topic_index": 2, "votes": [0, 0, 1_000_000 * BASE]}]).cfx_transact() + current_round + 3, [{"topic_index": 2, "votes": [0, 0, 1_000_000 * BASE]}]).transact().executed() storage.set_sponsor(3.75) check.checked_tick( total_storage_point=48, total_issued=-48, total_collateral=None, account_unused_collateral=12, account_unused_storage_point=48) self.wait_for_block(vote_tick + CIP104_PERIOD * 4, have_not_reach=True) paramsControl.castVote( - current_round + 4, [{"topic_index": 2, "votes": [0, 0, 1_000_000 * BASE]}]).cfx_transact() + current_round + 4, [{"topic_index": 2, "votes": [0, 0, 1_000_000 * BASE]}]).transact().executed() self.wait_for_block(vote_tick + CIP104_PERIOD * 5, have_not_reach=True) paramsControl.castVote( - current_round + 5, [{"topic_index": 2, "votes": [0, 0, 1_000_000 * BASE]}]).cfx_transact() + current_round + 5, [{"topic_index": 2, "votes": [0, 0, 1_000_000 * BASE]}]).transact().executed() self.wait_for_block(vote_tick + CIP104_PERIOD * 7, have_not_reach=True) storage.set_sponsor(3.75) diff --git a/tests/cip118_activation_test.py b/tests/cip118_activation_test.py index 201cbc9168..b8f1b9fcfc 100644 --- a/tests/cip118_activation_test.py +++ b/tests/cip118_activation_test.py @@ -1,26 +1,28 @@ from conflux.utils import * -from test_framework.contracts import ConfluxTestFrameworkForContract, ZERO_ADDRESS +from test_framework.test_framework import ConfluxTestFramework from test_framework.util import * from test_framework.mininode import * +from web3.exceptions import Web3RPCError CIP118_NUMBER = 100 -class CIP118ActivationTest(ConfluxTestFrameworkForContract): +class CIP118ActivationTest(ConfluxTestFramework): def set_test_params(self): self.num_nodes = 1 self.conf_parameters["cip118_transition_number"] = CIP118_NUMBER self.conf_parameters["executive_trace"] = "true" def run_test(self): + self.sponsorControl = self.internal_contract(name="SponsorWhitelistControl") try: - self.sponsorControl.functions.getAvailableStoragePoints(ZERO_ADDRESS).cfx_call() + self.sponsorControl.functions.getAvailableStoragePoints(ZERO_ADDRESS).call() raise Exception("Should fail") - except Exception as e: - assert_equal(e.response.data, 'VmError(InternalContract("unsupported function"))') + except Web3RPCError as e: + assert_equal(e.rpc_response['error']["data"], 'VmError(InternalContract("unsupported function"))') # type: ignore self.wait_for_block(CIP118_NUMBER + 5) - self.sponsorControl.functions.getAvailableStoragePoints(ZERO_ADDRESS).cfx_call() + self.sponsorControl.functions.getAvailableStoragePoints(ZERO_ADDRESS).call() def wait_for_block(self, block_number, have_not_reach=False): if have_not_reach: diff --git a/tests/cip97_test.py b/tests/cip97_test.py index 8d510df4c1..0735ce48bd 100644 --- a/tests/cip97_test.py +++ b/tests/cip97_test.py @@ -1,16 +1,12 @@ -from conflux.rpc import RpcClient from conflux.utils import * -from test_framework.contracts import ConfluxTestFrameworkForContract, BASE +from test_framework.test_framework import ConfluxTestFramework from test_framework.util import * from test_framework.mininode import * -from os.path import dirname, realpath, join - CFX = 10 ** 18 -class CIP97Test(ConfluxTestFrameworkForContract): +class CIP97Test(ConfluxTestFramework): def set_test_params(self): - super().set_test_params() self.num_nodes = 1 self.conf_parameters["dao_vote_transition_number"] = 100 self.conf_parameters["hydra_transition_number"] = 90 @@ -22,15 +18,15 @@ def run_test(self): staking = self.internal_contract("Staking").functions def get_current_epoch(): - return int(self.rpc.cfx_getBlockByEpochNumber("latest_mined", False)["epochNumber"], 16) + return int(self.client.block_by_epoch("latest_mined", False)["epochNumber"], 16) def deposit(): - receipt = staking.deposit(1 * BASE).cfx_transact() - return int(receipt["gasUsed"], 16) + receipt = staking.deposit(1 * CFX).transact().executed() + return receipt["gasUsed"] def withdraw(): - receipt = staking.withdraw(int(1.1 * BASE)).cfx_transact() - return int(receipt["gasUsed"], 16) + receipt = staking.withdraw(int(1.1 * CFX)).transact().executed() + return receipt["gasUsed"] for i in range(5): self.log.debug(f"deposit {i}") diff --git a/tests/commission_privilege_test.py b/tests/commission_privilege_test.py index 1cb1cf8230..c4ea0ba5fd 100755 --- a/tests/commission_privilege_test.py +++ b/tests/commission_privilege_test.py @@ -1,35 +1,37 @@ #!/usr/bin/env python3 -from conflux.rpc import RpcClient from conflux.transactions import CONTRACT_DEFAULT_GAS, COLLATERAL_UNIT_IN_DRIP, charged_of_huge_gas -from test_framework.block_gen_thread import BlockGenThread -from test_framework.contracts import ConfluxTestFrameworkForContract, Contract, ZERO_ADDRESS +from test_framework.test_framework import ConfluxTestFramework from test_framework.mininode import * from test_framework.util import * -class CommissionPrivilegeTest(ConfluxTestFrameworkForContract): +class CommissionPrivilegeTest(ConfluxTestFramework): def set_test_params(self): - super().set_test_params() self.num_nodes = 1 def run_test(self): + self.w3 = self.cw3 + self.sponsorControl = self.internal_contract(name="SponsorWhitelistControl") bytes_per_key = 64 collateral_per_storage_key = COLLATERAL_UNIT_IN_DRIP * 64 # change upper tx gas limit to (GENESIS_GAS_LIMIT/2 - 1); -1 because below gas is set to upper_bound + 1 - tx_gas_upper_bound = int(default_config["GENESIS_GAS_LIMIT"] / 2 - 1) + tx_gas_upper_bound = int(default_config["GENESIS_GAS_LIMIT"] / 2 - 1) # type: ignore self.log.info("Initializing contract") - genesis_addr = self.genesis_addr + genesis_addr = self.core_accounts[0].hex_address self.log.info("genesis_addr={}".format(genesis_addr)) gas_price = 1 gas = CONTRACT_DEFAULT_GAS - block_gen_thread = BlockGenThread(self.nodes, self.log) - block_gen_thread.start() + self.start_block_gen() client = self.client (addr1, priv_key1) = client.rand_account() (addr2, priv_key2) = client.rand_account() (addr3, priv_key3) = client.rand_account() (addr4, priv_key4) = client.rand_account() + self.w3.wallet.add_account(priv_key1) + self.w3.wallet.add_account(priv_key2) + self.w3.wallet.add_account(priv_key3) + self.w3.wallet.add_account(priv_key4) self.cfx_transfer(addr1, value = 1) assert_equal(client.get_balance(addr1), 10 ** 18) @@ -41,17 +43,25 @@ def run_test(self): # setup contract before_setup_collateral = client.get_collateral_for_storage(genesis_addr) - test_contract: Contract = self.cfx_contract("CommissionPrivilegeTest").deploy() + test_contract = self.deploy_contract("CommissionPrivilegeTest") after_setup_collateral = client.get_collateral_for_storage(genesis_addr) - contract_addr = test_contract.address + contract_addr = test_contract.address.hex_address assert_equal(client.get_balance(contract_addr), 0) assert_equal(after_setup_collateral - before_setup_collateral, 1024 * COLLATERAL_UNIT_IN_DRIP) # sponsor the contract failed due to sponsor_balance < 1000 * upper_bound b0 = client.get_balance(genesis_addr) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), 0) - self.sponsorControl.functions.setSponsorForGas(contract_addr, tx_gas_upper_bound).cfx_transact( - value = tx_gas_upper_bound * 1000 - 1, decimals = 0, err_msg='VmError(InternalContract("sponsor should at least sponsor upper_bound * 1000"))') + + assert_tx_exec_error(client, self.sponsorControl.functions.setSponsorForGas(contract_addr, tx_gas_upper_bound).transact({ + "value": tx_gas_upper_bound * 1000 - 1, + "gas": gas, + "storageLimit": 0, + "gasPrice": 1, + }).to_0x_hex(), + 'VmError(InternalContract("sponsor should at least sponsor upper_bound * 1000"))' + ) + assert_equal(client.get_sponsor_balance_for_gas(contract_addr), 0) assert_equal(client.get_sponsor_for_gas(contract_addr), ZERO_ADDRESS) assert_equal(client.get_sponsor_gas_bound(contract_addr), 0) @@ -59,7 +69,11 @@ def run_test(self): # sponsor the contract succeed b0 = client.get_balance(genesis_addr) - self.sponsorControl.functions.setSponsorForGas(contract_addr, tx_gas_upper_bound).cfx_transact(value = 1, gas = gas) + self.sponsorControl.functions.setSponsorForGas(contract_addr, tx_gas_upper_bound).transact({ + "value": 10**18, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_sponsor_balance_for_gas(contract_addr), 10 ** 18) assert_equal(client.get_sponsor_for_gas(contract_addr), genesis_addr.lower()) assert_equal(client.get_sponsor_gas_bound(contract_addr), tx_gas_upper_bound) @@ -78,7 +92,11 @@ def run_test(self): # set privilege for addr4 b0 = client.get_balance(genesis_addr) c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.add(addr4).cfx_transact(storage_limit = 64) + test_contract.functions.add(addr4).transact({ + "storageLimit": 64, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_balance(genesis_addr), b0 - charged_of_huge_gas(gas) - collateral_per_storage_key) assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + collateral_per_storage_key) @@ -90,71 +108,119 @@ def run_test(self): # remove privilege for addr4 b0 = client.get_balance(genesis_addr) c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.remove(addr4).cfx_transact(storage_limit = 0) + test_contract.functions.remove(addr4).transact({ + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(genesis_addr), c0 - collateral_per_storage_key) assert_equal(client.get_balance(genesis_addr), b0 - charged_of_huge_gas(gas) + collateral_per_storage_key) # set privilege for addr1 b0 = client.get_balance(genesis_addr) c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.add(addr1).cfx_transact(storage_limit=64) + test_contract.functions.add(addr1).transact({ + "storageLimit": 64, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_balance(genesis_addr), b0 - charged_of_huge_gas(gas) - collateral_per_storage_key) assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + collateral_per_storage_key) # addr1 call contract with privilege sb = client.get_sponsor_balance_for_gas(contract_addr) b1 = client.get_balance(addr1) - test_contract.functions.foo().cfx_transact(priv_key=priv_key1, storage_limit=0) + test_contract.functions.foo().transact({ + "from": self.cfx.address(addr1), + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_balance(addr1), b1) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sb - charged_of_huge_gas(gas)) # addr1 call contract with privilege and large tx fee b1 = client.get_balance(addr1) sb = client.get_sponsor_balance_for_gas(contract_addr) - test_contract.functions.foo().cfx_transact(priv_key=priv_key1, gas=tx_gas_upper_bound+1, storage_limit=0) + test_contract.functions.foo().transact({ + "from": self.cfx.address(addr1), + "gas": tx_gas_upper_bound+1, + "storageLimit": 0, + "gasPrice": 1, + }).executed() assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sb) assert_equal(client.get_balance(addr1), b1 - charged_of_huge_gas(tx_gas_upper_bound + 1)) # addr2 call contract without privilege b2 = client.get_balance(addr2) sb = client.get_sponsor_balance_for_gas(contract_addr) - test_contract.functions.foo().cfx_transact(priv_key=priv_key2, storage_limit=0) + test_contract.functions.foo().transact({ + "from": self.cfx.address(addr2), + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sb) assert_equal(client.get_balance(addr2), b2 - charged_of_huge_gas(gas)) # set privilege for addr2 b0 = client.get_balance(genesis_addr) c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.add(addr2).cfx_transact(storage_limit = 64) + test_contract.functions.add(addr2).transact({ + "storageLimit": 64, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_balance(genesis_addr), b0 - charged_of_huge_gas(gas) - collateral_per_storage_key) assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + collateral_per_storage_key) # now, addr2 call contract with privilege sb = client.get_sponsor_balance_for_gas(contract_addr) b2 = client.get_balance(addr2) - test_contract.functions.foo().cfx_transact(priv_key = priv_key2, storage_limit = 0) + test_contract.functions.foo().transact({ + "from": self.cfx.address(addr2), + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sb - charged_of_huge_gas(gas)) assert_equal(client.get_balance(addr2), b2) # remove privilege for addr1 b0 = client.get_balance(genesis_addr) c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.remove(addr1).cfx_transact(storage_limit = 0) + test_contract.functions.remove(addr1).transact({ + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(genesis_addr), c0 - collateral_per_storage_key) assert_equal(client.get_balance(genesis_addr), b0 - charged_of_huge_gas(gas) + collateral_per_storage_key) # addr1 call contract without privilege sb = client.get_sponsor_balance_for_gas(contract_addr) b1 = client.get_balance(addr1) - test_contract.functions.foo().cfx_transact(priv_key = priv_key1, storage_limit = 0) + test_contract.functions.foo().transact({ + "from": self.cfx.address(addr1), + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sb) assert_equal(client.get_balance(addr1), b1 - charged_of_huge_gas(gas)) # new sponsor failed due to small sponsor_balance b3 = client.get_balance(addr3) sb = client.get_sponsor_balance_for_gas(contract_addr) - self.sponsorControl.functions.setSponsorForGas(contract_addr, tx_gas_upper_bound).cfx_transact( - value = 0.5, storage_limit = 0, priv_key = priv_key3, err_msg = 'VmError(InternalContract("sponsor_balance is not exceed previous sponsor"))') + assert_tx_exec_error(client, self.sponsorControl.functions.setSponsorForGas(contract_addr, tx_gas_upper_bound).transact({ + "value": int(0.5 * 10**18), + "storageLimit": 0, + "from": self.cfx.address(addr3), + "gas": gas, + "gasPrice": 1, + }).to_0x_hex(), + 'VmError(InternalContract("sponsor_balance is not exceed previous sponsor"))' + ) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sb) assert_equal(client.get_sponsor_for_gas(contract_addr), genesis_addr.lower()) assert_equal(client.get_balance(addr3), b3 - gas) @@ -162,8 +228,17 @@ def run_test(self): # new sponsor failed due to small upper bound b3 = client.get_balance(addr3) sb = client.get_sponsor_balance_for_gas(contract_addr) - self.sponsorControl.functions.setSponsorForGas(contract_addr, tx_gas_upper_bound - 1).cfx_transact( - value = 1, storage_limit = 0, priv_key = priv_key3, err_msg = 'VmError(InternalContract("upper_bound is not exceed previous sponsor"))') + assert_tx_exec_error( + client, + self.sponsorControl.functions.setSponsorForGas(contract_addr, tx_gas_upper_bound - 1).transact({ + "value": 10**18, + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + "from": self.cfx.address(addr3), + }).to_0x_hex(), + 'VmError(InternalContract("upper_bound is not exceed previous sponsor"))' + ) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sb) assert_equal(client.get_sponsor_for_gas(contract_addr), genesis_addr.lower()) assert_equal(client.get_balance(addr3), b3 - gas) @@ -172,7 +247,13 @@ def run_test(self): b0 = client.get_balance(genesis_addr) b3 = client.get_balance(addr3) sb = client.get_sponsor_balance_for_gas(contract_addr) - self.sponsorControl.functions.setSponsorForGas(contract_addr, tx_gas_upper_bound + 1).cfx_transact(value = 1, storage_limit = 0, priv_key = priv_key3) + self.sponsorControl.functions.setSponsorForGas(contract_addr, tx_gas_upper_bound + 1).transact({ + "value": 10**18, + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + "from": self.cfx.address(addr3), + }).executed() assert_equal(client.get_sponsor_balance_for_gas(contract_addr), 10 ** 18) assert_equal(client.get_sponsor_gas_bound(contract_addr), tx_gas_upper_bound + 1) assert_equal(client.get_sponsor_for_gas(contract_addr), addr3.lower()) @@ -181,16 +262,30 @@ def run_test(self): # sponsor the contract for collateral failed due to zero sponsor balance b3 = client.get_balance(addr3) - self.sponsorControl.functions.setSponsorForCollateral(contract_addr).cfx_transact( - priv_key = priv_key3, storage_limit = 0, err_msg = 'VmError(InternalContract("zero sponsor balance is not allowed"))') + assert_tx_exec_error( + client, + self.sponsorControl.functions.setSponsorForCollateral(contract_addr).transact({ + "value": 0, + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + "from": self.cfx.address(addr3), + }).to_0x_hex(), + 'VmError(InternalContract("zero sponsor balance is not allowed"))' + ) assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), 0) assert_equal(client.get_sponsor_for_collateral(contract_addr), ZERO_ADDRESS) assert_equal(client.get_balance(addr3), b3 - gas) # sponsor the contract for collateral succeed b3 = client.get_balance(addr3) - self.sponsorControl.functions.setSponsorForCollateral(contract_addr).cfx_transact( - value = 10 ** 18 - 1, decimals = 0, storage_limit = 0, priv_key = priv_key3) + self.sponsorControl.functions.setSponsorForCollateral(contract_addr).transact({ + "value": 10 ** 18 - 1, + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + "from": self.cfx.address(addr3), + }).executed() assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), 10 ** 18 - 1) assert_equal(client.get_sponsor_for_collateral(contract_addr), addr3.lower()) assert_equal(client.get_balance(addr3), b3 - charged_of_huge_gas(gas) - 10 ** 18 + 1) @@ -204,21 +299,40 @@ def run_test(self): b1 = client.get_balance(addr1) assert_equal(client.get_collateral_for_storage(contract_addr), 0) assert_equal(client.get_collateral_for_storage(addr1), 0) - test_contract.functions.par_add(0,2).cfx_transact(priv_key = priv_key1, storage_limit = bytes_per_key, err_msg="VmError(ExceedStorageLimit)") + assert_tx_exec_error( + client, + test_contract.functions.par_add(0,2).transact({ + "from": self.cfx.address(addr1), + "storageLimit": bytes_per_key, + "gas": gas, + "gasPrice": 1, + }).to_0x_hex(), + "VmError(ExceedStorageLimit)" + ) assert_equal(client.get_collateral_for_storage(contract_addr), 0) assert_equal(client.get_collateral_for_storage(addr1), 0) assert_equal(client.get_balance(addr1), b1 - gas) # addr1 create 2 keys without privilege, and storage limit is 2, should succeed b1 = client.get_balance(addr1) - test_contract.functions.par_add(0,2).cfx_transact(priv_key = priv_key1, storage_limit=bytes_per_key * 2) + test_contract.functions.par_add(0,2).transact({ + "from": self.cfx.address(addr1), + "storageLimit": bytes_per_key * 2, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(contract_addr), 0) assert_equal(client.get_collateral_for_storage(addr1), collateral_per_storage_key * 2) assert_equal(client.get_balance(addr1), b1 - charged_of_huge_gas(gas) - collateral_per_storage_key * 2) # remove 1 key create by addr1 b1 = client.get_balance(addr1) - test_contract.functions.par_del(0,1).cfx_transact(priv_key = priv_key1, storage_limit=bytes_per_key * 2) + test_contract.functions.par_del(0,1).transact({ + "from": self.cfx.address(addr1), + "storageLimit": bytes_per_key * 2, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(contract_addr), 0) assert_equal(client.get_collateral_for_storage(addr1), collateral_per_storage_key) assert_equal(client.get_balance(addr1), b1 - charged_of_huge_gas(gas) + collateral_per_storage_key) @@ -237,7 +351,12 @@ def run_test(self): sbc = client.get_sponsor_balance_for_collateral(contract_addr) sbg = client.get_sponsor_balance_for_gas(contract_addr) b2 = client.get_balance(addr2) - test_contract.functions.par_add(2,4).cfx_transact(priv_key = priv_key2, storage_limit=bytes_per_key) + test_contract.functions.par_add(2,4).transact({ + "from": self.cfx.address(addr2), + "storageLimit": bytes_per_key, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(contract_addr), collateral_per_storage_key * 2) assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), sbc - collateral_per_storage_key * 2) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sbg - charged_of_huge_gas(gas)) @@ -248,7 +367,12 @@ def run_test(self): sbc = client.get_sponsor_balance_for_collateral(contract_addr) sbg = client.get_sponsor_balance_for_gas(contract_addr) b2 = client.get_balance(addr2) - test_contract.functions.par_add(4,17).cfx_transact(priv_key=priv_key2, storage_limit=0) + test_contract.functions.par_add(4,17).transact({ + "from": self.cfx.address(addr2), + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(contract_addr), collateral_per_storage_key * 15) assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), sbc - collateral_per_storage_key * 13) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sbg - charged_of_huge_gas(gas)) @@ -265,7 +389,16 @@ def run_test(self): sbc = client.get_sponsor_balance_for_collateral(contract_addr) sbg = client.get_sponsor_balance_for_gas(contract_addr) b2 = client.get_balance(addr2) - test_contract.functions.par_add(17,18).cfx_transact(priv_key=priv_key2, storage_limit=0, err_msg = "VmError(NotEnoughBalanceForStorage { required: 62500000000000000, got: 62499999999999999 })") + assert_tx_exec_error( + client, + test_contract.functions.par_add(17,18).transact({ + "from": self.cfx.address(addr2), + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + }).to_0x_hex(), + "VmError(NotEnoughBalanceForStorage { required: 62500000000000000, got: 62499999999999999 })" + ) assert_equal(client.get_collateral_for_storage(contract_addr), collateral_per_storage_key * 15) assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), sbc) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sbg - gas) @@ -276,7 +409,12 @@ def run_test(self): sbc = client.get_sponsor_balance_for_collateral(contract_addr) sbg = client.get_sponsor_balance_for_gas(contract_addr) b2 = client.get_balance(addr2) - test_contract.functions.par_add(17, 18).cfx_transact(priv_key = priv_key2, storage_limit=bytes_per_key * 2) + test_contract.functions.par_add(17, 18).transact({ + "from": self.cfx.address(addr2), + "storageLimit": bytes_per_key * 2, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(contract_addr), collateral_per_storage_key * 15) assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), sbc) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sbg - charged_of_huge_gas(gas)) @@ -287,7 +425,12 @@ def run_test(self): sbc = client.get_sponsor_balance_for_collateral(contract_addr) sbg = client.get_sponsor_balance_for_gas(contract_addr) b2 = client.get_balance(addr2) - test_contract.functions.par_del(2,12).cfx_transact(priv_key=priv_key2, storage_limit=bytes_per_key) + test_contract.functions.par_del(2,12).transact({ + "from": self.cfx.address(addr2), + "storageLimit": bytes_per_key, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(contract_addr), collateral_per_storage_key * 5) assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), sbc + collateral_per_storage_key * 10) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sbg - charged_of_huge_gas(gas)) @@ -297,7 +440,13 @@ def run_test(self): # addr3 sponsor more, treat as transfer b3 = client.get_balance(addr3) sb = client.get_sponsor_balance_for_collateral(contract_addr) - self.sponsorControl.functions.setSponsorForCollateral(contract_addr).cfx_transact(value = sb, decimals = 0, priv_key = priv_key3, storage_limit = 0) + self.sponsorControl.functions.setSponsorForCollateral(contract_addr).transact({ + "value": sb, + "storageLimit": 0, + "from": self.cfx.address(addr3), + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), sb * 2) assert_equal(client.get_sponsor_for_collateral(contract_addr), addr3.lower()) assert_equal(client.get_balance(addr3), b3 - charged_of_huge_gas(gas) - sb) @@ -306,7 +455,16 @@ def run_test(self): b0 = client.get_balance(genesis_addr) sb = client.get_sponsor_balance_for_collateral(contract_addr) err_msg = 'VmError(InternalContract("sponsor_balance is not enough to cover previous sponsor\'s sponsor_balance and collateral_for_storage"))' - self.sponsorControl.functions.setSponsorForCollateral(contract_addr).cfx_transact(value = sb +1, decimals= 0, err_msg = err_msg) + assert_tx_exec_error( + client, + self.sponsorControl.functions.setSponsorForCollateral(contract_addr).transact({ + "value": sb + 1, + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + }).to_0x_hex(), + err_msg + ) assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), sb) assert_equal(client.get_sponsor_for_collateral(contract_addr), addr3.lower()) assert_equal(client.get_balance(genesis_addr), b0 - gas) @@ -316,7 +474,12 @@ def run_test(self): b3 = client.get_balance(addr3) cfs = client.get_collateral_for_storage(contract_addr) sb = client.get_sponsor_balance_for_collateral(contract_addr) - self.sponsorControl.functions.setSponsorForCollateral(contract_addr).cfx_transact(value = sb + cfs + 1, decimals = 0) + self.sponsorControl.functions.setSponsorForCollateral(contract_addr).transact({ + "value": sb + cfs + 1, + "storageLimit": 0, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(contract_addr), cfs) assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), sb + 1) assert_equal(client.get_sponsor_for_collateral(contract_addr), genesis_addr.lower()) @@ -326,34 +489,62 @@ def run_test(self): # storage change test c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.par(10,20,30,41).cfx_transact(storage_limit=bytes_per_key * 30) + test_contract.functions.par(10,20,30,41).transact({ + "storageLimit": bytes_per_key * 30, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + 11 * collateral_per_storage_key) c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.par_add_del(110,120,110,120).cfx_transact(storage_limit = bytes_per_key * 30) + test_contract.functions.par_add_del(110,120,110,120).transact({ + "storageLimit": bytes_per_key * 30, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + 10 * collateral_per_storage_key) c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.par_add_del(210,220,215,220).cfx_transact(storage_limit=bytes_per_key * 30) + test_contract.functions.par_add_del(210,220,215,220).transact({ + "storageLimit": bytes_per_key * 30, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + 5 * collateral_per_storage_key) c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.par_add_del(310,320,320,330).cfx_transact(storage_limit = bytes_per_key * 30) + test_contract.functions.par_add_del(310,320,320,330).transact({ + "storageLimit": bytes_per_key * 30, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + 10 * collateral_per_storage_key) c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.par_add_del(410, 420, 409, 430).cfx_transact(storage_limit = bytes_per_key * 300) + test_contract.functions.par_add_del(410, 420, 409, 430).transact({ + "storageLimit": bytes_per_key * 300, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + 21 * collateral_per_storage_key) # test recurrence c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.rec(510, 520, 3).cfx_transact(storage_limit = bytes_per_key * 30) + test_contract.functions.rec(510, 520, 3).transact({ + "storageLimit": bytes_per_key * 30, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + 4 * collateral_per_storage_key) c0 = client.get_collateral_for_storage(genesis_addr) - test_contract.functions.par_del(510, 520).cfx_transact(storage_limit = bytes_per_key * 30) + test_contract.functions.par_del(510, 520).transact({ + "storageLimit": bytes_per_key * 30, + "gas": gas, + "gasPrice": 1, + }).executed() assert_equal(client.get_collateral_for_storage(genesis_addr), c0 - 4 * collateral_per_storage_key) self.log.info("Pass") diff --git a/tests/contract_remove_test.py b/tests/contract_remove_test.py index 05a3ba058f..0cf04a7aae 100644 --- a/tests/contract_remove_test.py +++ b/tests/contract_remove_test.py @@ -1,11 +1,10 @@ -from web3 import Web3 -from web3.contract import Contract +from conflux_web3 import Web3 import itertools from conflux.utils import * from test_framework.util import * from test_framework.mininode import * -from test_framework.contracts import ConfluxTestFrameworkForContract, Account +from test_framework.test_framework import ConfluxTestFramework SNAPSHOT_EPOCH = 60 @@ -13,7 +12,7 @@ def temp_address(number: int): return Web3.to_checksum_address("{:#042x}".format(number + 100)) -class ContractRemoveTest(ConfluxTestFrameworkForContract): +class ContractRemoveTest(ConfluxTestFramework): def __init__(self): super().__init__() self.has_range_delete_bug = False @@ -28,7 +27,7 @@ def correct_wl_collateral(self): return not (self.has_collateral_bug or self.has_range_delete_bug) def set_test_params(self): - super().set_test_params() + self.num_nodes = 1 self.conf_parameters["adaptive_weight_beta"] = "1" self.conf_parameters["timer_chain_block_difficulty_ratio"] = "3" @@ -40,11 +39,15 @@ def set_test_params(self): self.conf_parameters["next_hardfork_transition_number"] = 9999999 def run_test(self): - accounts: List[Account] = self.initialize_accounts(2, value = 1000) - self.genesis_addr3 = accounts[0].address + self.w3 = self.cw3 + self.genesis_addr = self.core_accounts[0].address + accounts = self.initialize_accounts(2, value = 1000) + self.genesis_addr3 = self.w3.cfx.address(accounts[0].address) self.genesis_key3 = accounts[0].key - self.genesis_addr4 = accounts[1].address + self.genesis_addr4 = self.w3.cfx.address(accounts[1].address) self.genesis_key4 = accounts[1].key + + self.w3.wallet.add_accounts([self.genesis_key3, self.genesis_key4]) self.test_range_deletion_on_contract_remove(False) @@ -83,15 +86,20 @@ def test_sponsor_whitelist_clear_on_contract_remove(self, is_sponsored, has_rang def test_change_storage_and_kill(self): storage_contract = self.deploy_contract_and_init(5) multi_calldata = [ - storage_contract.functions.change(3).data(), - storage_contract.functions.change(4).data(), - storage_contract.functions.selfDestruct(self.genesis_addr3).data() + storage_contract.functions.change(3).encode_transaction_data(), + storage_contract.functions.change(4).encode_transaction_data(), + storage_contract.functions.selfDestruct(self.genesis_addr3).encode_transaction_data() ] if not self.is_sponsored: # The check of storage limit is earlier than kill contract. So even if the occupied entry is released in kill process, we still need enough storage_limit. - storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 0, err_msg = "VmError(ExceedStorageLimit)") - receipt = storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 64 * 2) + assert_tx_exec_error(self.client, storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 0, + "gas": 3000000 + }).to_0x_hex(), "VmError(ExceedStorageLimit)") + receipt = storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 64 * 2 + }).executed() assert_storage_released(receipt, self.genesis_addr4, 64 * 5) assert_storage_released(receipt, self.storage_owner, 0) assert_storage_occupied(receipt, self.storage_owner, 0) @@ -102,11 +110,13 @@ def test_change_storage_and_kill(self): def test_reset_storage_and_kill(self): storage_contract = self.deploy_contract_and_init(5) multi_calldata = [ - storage_contract.functions.reset(3).data(), - storage_contract.functions.reset(4).data(), - storage_contract.functions.selfDestruct(self.genesis_addr3).data() + storage_contract.functions.reset(3).encode_transaction_data(), + storage_contract.functions.reset(4).encode_transaction_data(), + storage_contract.functions.selfDestruct(self.genesis_addr3).encode_transaction_data() ] - receipt = storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 0) + receipt = storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 0 + }).executed() assert_storage_released(receipt, self.genesis_addr4, 64 * 5) assert_storage_released(receipt, self.storage_owner, 0) assert_storage_occupied(receipt, self.storage_owner, 0) @@ -117,11 +127,13 @@ def test_reset_storage_and_kill(self): def test_unchange_storage_and_kill(self): storage_contract = self.deploy_contract_and_init(5) multi_calldata = [ - storage_contract.functions.set(3).data(), - storage_contract.functions.set(4).data(), - storage_contract.functions.selfDestruct(self.genesis_addr3).data() + storage_contract.functions.set(3).encode_transaction_data(), + storage_contract.functions.set(4).encode_transaction_data(), + storage_contract.functions.selfDestruct(self.genesis_addr3).encode_transaction_data() ] - receipt = storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 0) + receipt = storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 0 + }).executed() assert_storage_released(receipt, self.genesis_addr4, 64 * 5) assert_storage_released(receipt, self.storage_owner, 0) assert_storage_occupied(receipt, self.storage_owner, 0) @@ -132,14 +144,19 @@ def test_unchange_storage_and_kill(self): def test_set_new_storage_and_kill(self): storage_contract = self.deploy_contract_and_init(5) multi_calldata = [ - storage_contract.functions.set(5).data(), - storage_contract.functions.set(6).data(), - storage_contract.functions.selfDestruct(self.genesis_addr3).data() + storage_contract.functions.set(5).encode_transaction_data(), + storage_contract.functions.set(6).encode_transaction_data(), + storage_contract.functions.selfDestruct(self.genesis_addr3).encode_transaction_data() ] if not self.is_sponsored: # The check of storage limit is earlier than kill contract. So even if the occupied entry is released in kill process, we still need enough storage_limit. - storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 0, err_msg = "VmError(ExceedStorageLimit)") - receipt = storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 64 * 2) + assert_tx_exec_error(self.client, storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 0, + "gas": 3000000 + }).to_0x_hex(), "VmError(ExceedStorageLimit)") + receipt = storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 64 * 2, + }).executed() assert_storage_released(receipt, self.genesis_addr4, 64 * 5) assert_storage_released(receipt, self.storage_owner, 0) assert_storage_occupied(receipt, self.storage_owner, 0) @@ -150,11 +167,13 @@ def test_set_new_storage_and_kill(self): def test_set_new_storage_and_later_kill(self): storage_contract = self.deploy_contract_and_init(5) multi_calldata = [ - storage_contract.functions.change(4).data(), - storage_contract.functions.set(5).data(), - storage_contract.functions.set(6).data(), + storage_contract.functions.change(4).encode_transaction_data(), + storage_contract.functions.set(5).encode_transaction_data(), + storage_contract.functions.set(6).encode_transaction_data(), ] - receipt = storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 64 * 3) + receipt = storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 64 * 3 + }).executed() assert_storage_released(receipt, self.genesis_addr4, 64) assert_storage_released(receipt, self.storage_owner, 0) assert_storage_occupied(receipt, self.storage_owner, 3 * 64) @@ -162,7 +181,9 @@ def test_set_new_storage_and_later_kill(self): assert_equal(self.exist_storage_at(4), True) assert_equal(self.exist_storage_at(6), True) - receipt = storage_contract.functions.selfDestruct(self.genesis_addr3).cfx_transact(storage_limit = 0) + receipt = storage_contract.functions.selfDestruct(self.genesis_addr3).transact({ + "storageLimit": 0 + }).executed() assert_storage_released(receipt, self.genesis_addr4, 4 * 64) assert_storage_released(receipt, self.storage_owner, 3 * 64) assert_storage_occupied(receipt, self.storage_owner, 0) @@ -174,11 +195,13 @@ def test_set_new_storage_and_later_kill(self): def test_touch_whitelist_and_kill(self): storage_contract = self.deploy_contract_and_set_whitelist(5) multi_calldata = [ - storage_contract.functions.getSponsored(temp_address(3)).data(), - storage_contract.functions.getSponsored(temp_address(4)).data(), - storage_contract.functions.selfDestruct(self.genesis_addr3).data() + storage_contract.functions.getSponsored(temp_address(3)).encode_transaction_data(), + storage_contract.functions.getSponsored(temp_address(4)).encode_transaction_data(), + storage_contract.functions.selfDestruct(self.genesis_addr3).encode_transaction_data() ] - receipt = storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 0) + receipt = storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 0 + }).executed() # print(receipt) assert_storage_released(receipt, self.genesis_addr4, 64 * 5 if self.correct_wl_collateral else 64 * 2) assert_storage_released(receipt, self.storage_owner, 0) @@ -191,15 +214,20 @@ def test_touch_whitelist_and_kill(self): def test_set_again_whitelist_and_kill(self): storage_contract = self.deploy_contract_and_set_whitelist(5) multi_calldata = [ - storage_contract.functions.setSponsored(temp_address(3)).data(), - storage_contract.functions.setSponsored(temp_address(4)).data(), - storage_contract.functions.selfDestruct(self.genesis_addr3).data() + storage_contract.functions.setSponsored(temp_address(3)).encode_transaction_data(), + storage_contract.functions.setSponsored(temp_address(4)).encode_transaction_data(), + storage_contract.functions.selfDestruct(self.genesis_addr3).encode_transaction_data() ] if not self.is_sponsored: # The check of storage limit is earlier than kill contract. So even if the occupied entry is released in kill process, we still need enough storage_limit. # For sponsor whitelist, the storage owner is changed even if the value does not change. This is a special case of storage owner behaviour - storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 0, err_msg = "VmError(ExceedStorageLimit)") - receipt = storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 64 * 2) + assert_tx_exec_error(self.client, storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 0, + "gas": 3000000 + }).to_0x_hex(), "VmError(ExceedStorageLimit)") + receipt = storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 64 * 2 + }).executed() assert_storage_released(receipt, self.genesis_addr4, 64 * 5 if self.correct_wl_collateral else 64 * 2) assert_storage_released(receipt, self.storage_owner, 0) assert_storage_occupied(receipt, self.storage_owner, 0) @@ -210,11 +238,13 @@ def test_set_again_whitelist_and_kill(self): def test_reset_whitelist_and_kill(self): storage_contract = self.deploy_contract_and_set_whitelist(5) multi_calldata = [ - storage_contract.functions.resetSponsored(temp_address(3)).data(), - storage_contract.functions.resetSponsored(temp_address(4)).data(), - storage_contract.functions.selfDestruct(self.genesis_addr3).data() + storage_contract.functions.resetSponsored(temp_address(3)).encode_transaction_data(), + storage_contract.functions.resetSponsored(temp_address(4)).encode_transaction_data(), + storage_contract.functions.selfDestruct(self.genesis_addr3).encode_transaction_data() ] - receipt = storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 0) + receipt = storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 0 + }).executed() assert_storage_released(receipt, self.genesis_addr4, 64 * 5 if self.correct_wl_collateral else 64 * 2) assert_storage_released(receipt, self.storage_owner, 0) assert_storage_occupied(receipt, self.storage_owner, 0) @@ -225,14 +255,19 @@ def test_reset_whitelist_and_kill(self): def test_set_new_whitelist_and_kill(self): storage_contract = self.deploy_contract_and_set_whitelist(5) multi_calldata = [ - storage_contract.functions.setSponsored(temp_address(5)).data(), - storage_contract.functions.setSponsored(temp_address(6)).data(), - storage_contract.functions.selfDestruct(self.genesis_addr3).data() + storage_contract.functions.setSponsored(temp_address(5)).encode_transaction_data(), + storage_contract.functions.setSponsored(temp_address(6)).encode_transaction_data(), + storage_contract.functions.selfDestruct(self.genesis_addr3).encode_transaction_data() ] if not self.is_sponsored: # The check of storage limit is earlier than kill contract. So even if the occupied entry is released in kill process, we still need enough storage_limit. - storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 0, err_msg = "VmError(ExceedStorageLimit)") - receipt = storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 64 * 2) + assert_tx_exec_error(self.client, storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 0, + "gas": 3000000 + }).to_0x_hex(), "VmError(ExceedStorageLimit)") + receipt = storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 64 * 2 + }).executed() assert_storage_released(receipt, self.genesis_addr4, 64 * 5 if self.correct_wl_collateral else 0) assert_storage_released(receipt, self.storage_owner, 0) assert_storage_occupied(receipt, self.storage_owner, 0) @@ -245,11 +280,13 @@ def test_set_new_whitelist_and_later_kill(self): storage_contract = self.deploy_contract_and_set_whitelist(5) multi_calldata = [ - storage_contract.functions.setSponsored(temp_address(4)).data(), - storage_contract.functions.setSponsored(temp_address(5)).data(), - storage_contract.functions.setSponsored(temp_address(6)).data(), + storage_contract.functions.setSponsored(temp_address(4)).encode_transaction_data(), + storage_contract.functions.setSponsored(temp_address(5)).encode_transaction_data(), + storage_contract.functions.setSponsored(temp_address(6)).encode_transaction_data(), ] - receipt = storage_contract.functions.multiCall(multi_calldata).cfx_transact(storage_limit = 64 * 3) + receipt = storage_contract.functions.multiCall(multi_calldata).transact({ + "storageLimit": 64 * 3 + }).executed() assert_storage_released(receipt, self.genesis_addr4, 64) assert_storage_released(receipt, self.storage_owner, 0) assert_storage_occupied(receipt, self.storage_owner, 3 * 64) @@ -261,12 +298,14 @@ def test_set_new_whitelist_and_later_kill(self): self.client.generate_blocks(SNAPSHOT_EPOCH * 2 + 1) - receipt = storage_contract.functions.selfDestruct(self.genesis_addr3).cfx_transact(storage_limit = 0) + receipt = storage_contract.functions.selfDestruct(self.genesis_addr3).transact({ + "storageLimit": 0 + }).executed() assert_storage_released(receipt, self.genesis_addr4, 4 * 64 if self.correct_wl_collateral else 0) assert_storage_released(receipt, self.storage_owner, 3 * 64 if self.correct_wl_collateral else 0) assert_storage_occupied(receipt, self.storage_owner, 0) if self.has_range_delete_bug: - end_epoch = int(receipt["epochNumber"],0) // SNAPSHOT_EPOCH + end_epoch = receipt["epochNumber"] // SNAPSHOT_EPOCH # If the test fails here, consider increase SNAPSHOT_EPOCH assert_greater_than(2, end_epoch - start_epoch) self.assert_address_sponsored(storage_contract.address, 2, False if self.correct_wl_value else True) @@ -275,31 +314,49 @@ def test_set_new_whitelist_and_later_kill(self): def deploy_contract_and_init(self, num_entries): - storage_contract: Contract = self.cfx_contract("StorageExt").deploy(transact_args=dict(priv_key = self.genesis_key3)) - - multi_calldata = [storage_contract.functions.set(i).data() for i in range(num_entries)] - storage_contract.functions.multiCall(multi_calldata).cfx_transact(priv_key = self.genesis_key4, storage_limit = 64 * num_entries) - self.exist_storage_at = lambda x: self.client.get_storage_at(storage_contract.address.lower(), "{:#066x}".format(x)) is not None + storage_contract = self.deploy_contract("StorageExt", transact_args={"from": self.genesis_addr3}) + + multi_calldata = [storage_contract.functions.set(i).encode_transaction_data() for i in range(num_entries)] + storage_contract.functions.multiCall(multi_calldata).transact({ + "from": self.genesis_addr4, + "storageLimit": 64 * num_entries + }).executed() + self.exist_storage_at = lambda x: self.cfx.get_storage_at(storage_contract.address, x) is not None assert_equal(self.exist_storage_at(num_entries - 1), True) assert_equal(self.exist_storage_at(num_entries), False) if self.is_sponsored: - storage_contract.functions.setSponsored(self.genesis_addr).cfx_transact(priv_key = self.genesis_key3, storage_limit = 64) - self.internal_contract("SponsorWhitelistControl").functions.setSponsorForCollateral(storage_contract.address).cfx_transact(priv_key = self.genesis_key3, value = 100) + storage_contract.functions.setSponsored(self.genesis_addr).transact({ + "from": self.genesis_addr3, + "storageLimit": 64 + }).executed() + self.internal_contract("SponsorWhitelistControl").functions.setSponsorForCollateral(storage_contract.address).transact({ + "from": self.genesis_addr3, + "value": 100 * 10 ** 18 + }).executed() self.storage_owner = storage_contract.address return storage_contract def deploy_contract_and_set_whitelist(self, num_entries): - storage_contract: Contract = self.cfx_contract("StorageExt").deploy(transact_args=dict(priv_key = self.genesis_key3)) + storage_contract = self.deploy_contract("StorageExt", transact_args={"from": self.genesis_addr3}) - multi_calldata = [storage_contract.functions.setSponsored(temp_address(i)).data() for i in range(num_entries)] - storage_contract.functions.multiCall(multi_calldata).cfx_transact(priv_key = self.genesis_key4, storage_limit = 64 * num_entries) + multi_calldata = [storage_contract.functions.setSponsored(temp_address(i)).encode_transaction_data() for i in range(num_entries)] + storage_contract.functions.multiCall(multi_calldata).transact({ + "from": self.genesis_addr4, + "storageLimit": 64 * num_entries + }).executed() self.assert_address_sponsored(storage_contract.address, num_entries - 1, True) self.assert_address_sponsored(storage_contract.address, num_entries, False) if self.is_sponsored: - storage_contract.functions.setSponsored(self.genesis_addr).cfx_transact(priv_key = self.genesis_key3, storage_limit = 64) - self.internal_contract("SponsorWhitelistControl").functions.setSponsorForCollateral(storage_contract.address).cfx_transact(priv_key = self.genesis_key3, value = 100) + storage_contract.functions.setSponsored(self.genesis_addr).transact({ + "from": self.genesis_addr3, + "storageLimit": 64 + }).executed() + self.internal_contract("SponsorWhitelistControl").functions.setSponsorForCollateral(storage_contract.address).transact({ + "from": self.genesis_addr3, + "value": 100 * 10 ** 18 + }).executed() self.storage_owner = storage_contract.address if not self.has_range_delete_bug: @@ -308,7 +365,7 @@ def deploy_contract_and_set_whitelist(self, num_entries): return storage_contract def assert_address_sponsored(self, contract_address, sponsored_index: int, expected: bool): - actual = self.internal_contract("SponsorWhitelistControl").functions.isWhitelisted(contract_address, temp_address(sponsored_index)).cfx_call() + actual = self.internal_contract("SponsorWhitelistControl").functions.isWhitelisted(contract_address, temp_address(sponsored_index)).call() assert_equal(expected, actual) diff --git a/tests/erc20_test.py b/tests/erc20_test.py index 7c5ec74d47..da73701505 100755 --- a/tests/erc20_test.py +++ b/tests/erc20_test.py @@ -41,7 +41,6 @@ def run_test(self): raw_create = erc20_contract.constructor().build_transaction(self.tx_conf) tx_data = decode_hex(raw_create["data"]) tx_create = create_transaction(pri_key=genesis_key, receiver=b'', nonce=nonce, gas_price=gas_price, data=tx_data, gas=gas, value=0, storage_limit=1920) - self.client = RpcClient(self.nodes[0]) c0 = self.client.get_collateral_for_storage(genesis_addr) self.client.send_tx(tx_create, True) receipt = self.client.get_transaction_receipt(tx_create.hash_hex()) diff --git a/tests/evm_space/base.py b/tests/evm_space/base.py index bb48788dbb..a1fb676ef3 100644 --- a/tests/evm_space/base.py +++ b/tests/evm_space/base.py @@ -14,6 +14,8 @@ class Web3Base(ConfluxTestFramework): DEFAULT_TEST_ACCOUNT_KEY = "0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" TEST_CHAIN_ID = 10 + + w3: Web3 def set_test_params(self): self.num_nodes = 1 @@ -26,9 +28,8 @@ def setup_network(self): self.start_node(0, ["--archive"]) self.rpc = RpcClient(self.nodes[0]) - ip = self.nodes[0].ip - port = self.nodes[0].ethrpcport - self.w3 = Web3(Web3.HTTPProvider(f'http://{ip}:{port}/')) + self.setup_w3() + self.w3 = self.ew3 assert_equal(self.w3.is_connected(), True) def cross_space_transfer(self, to, value): diff --git a/tests/issue2483_test.py b/tests/issue2483_test.py index d811bccb9f..69526dd692 100644 --- a/tests/issue2483_test.py +++ b/tests/issue2483_test.py @@ -22,7 +22,6 @@ def setup_network(self): self.setup_nodes() def run_test(self): - self.w3 = web3.Web3() self.rpc = RpcClient(self.nodes[0]) priv_key = default_config["GENESIS_PRI_KEY"] sender = eth_utils.encode_hex(priv_to_addr(priv_key)) @@ -38,7 +37,7 @@ def run_test(self): receipt = self.rpc.get_transaction_receipt(tx.hash_hex()) contract_address = receipt["contractCreated"] - contract = self.w3.eth.contract(abi=abi) + contract = web3.Web3().eth.contract(abi=abi) call_data = contract.encode_abi("setFresh") tx = self.rpc.new_contract_tx(receiver=contract_address, data_hex=call_data) diff --git a/tests/light/rpc_test.py b/tests/light/rpc_test.py index bcf5dd3f59..90324dad18 100755 --- a/tests/light/rpc_test.py +++ b/tests/light/rpc_test.py @@ -9,8 +9,7 @@ from eth_utils import decode_hex from conflux.rpc import RpcClient from test_framework.test_framework import ConfluxTestFramework -from test_framework.util import assert_equal, assert_greater_than, assert_is_hex_string, assert_raises_rpc_error, connect_nodes, sync_blocks, get_contract_instance -from test_framework.contracts import cfx_contract +from test_framework.util import assert_equal, assert_greater_than, assert_is_hex_string, assert_raises_rpc_error, connect_nodes, sync_blocks, get_contract_instance, load_contract_metadata from web3 import Web3 FULLNODE0 = 0 @@ -163,7 +162,7 @@ def setup_network(self): self.block_d = block_d # deploy contract - bytecode = cfx_contract("CommissionPrivilegeTest").bytecode.hex() + bytecode = load_contract_metadata("CommissionPrivilegeTest")["bytecode"] receipt, contractAddr = self.deploy_contract(bytecode) self.log.info(f"contract deployed: {contractAddr}") self._setup_sponsor(contractAddr) diff --git a/tests/overlay_account_storage_test.py b/tests/overlay_account_storage_test.py index 2cf6da43f8..58290e9297 100644 --- a/tests/overlay_account_storage_test.py +++ b/tests/overlay_account_storage_test.py @@ -1,93 +1,117 @@ -from web3.contract.contract import ContractFunction, Contract +from cfx_utils import CFX +from conflux_web3.contract import ConfluxContract +from conflux_web3.contract.function import ConfluxContractFunction from conflux.utils import * from test_framework.util import * from test_framework.mininode import * -from test_framework.contracts import ConfluxTestFrameworkForContract, Account +from test_framework.test_framework import ConfluxTestFramework -class OverlayAccountStorageTest(ConfluxTestFrameworkForContract): +class OverlayAccountStorageTest(ConfluxTestFramework): + def set_test_params(self): + self.num_nodes = 1 + def run_test(self): - accounts: List[Account] = self.initialize_accounts(2, value = 1000) + self.w3 = self.cw3 + self.genesis_key1 = self.core_accounts[0].key + self.genesis_addr1 = self.core_accounts[0].address + self.genesis_key2 = self.evm_accounts[0].key + self.genesis_addr2 = self.cfx.account.from_key(self.evm_accounts[0].key).address + + accounts = self.initialize_accounts(2, value = 1000) + self.genesis_key3 = accounts[0].key - self.genesis_addr3 = accounts[0].address + self.genesis_addr3 = self.cfx.address(accounts[0].address) self.genesis_key4 = accounts[1].key - self.genesis_addr4 = accounts[1].address + self.genesis_addr4 = self.cfx.address(accounts[1].address) + + self.w3.wallet.add_accounts([self.genesis_key2, self.genesis_key3, self.genesis_key4]) def direct_call(call_fn, storage_contract, priv_key, before_value, after_value): - return call_fn.cfx_transact(priv_key=priv_key) + return call_fn.transact({ + "from": self.cfx.account.from_key(priv_key).address, + }).executed() self.run_task_group(direct_call) - def read_then_call(call_fn: ContractFunction, storage_contract: Contract, priv_key, before_value, after_value): - call_contract: Contract = self.cfx_contract("StorageExt").at(call_fn.address) + def read_then_call(call_fn: ConfluxContractFunction, storage_contract: ConfluxContract, priv_key, before_value, after_value): + call_contract = self.cfx_contract("StorageExt")(call_fn.address) return call_contract.functions.multiCallExternal([ - storage_contract.functions.assertValue(0, before_value).data(), - call_fn.data(), + storage_contract.functions.assertValue(0, before_value).encode_transaction_data(), + call_fn.encode_transaction_data(), ], [ storage_contract.address, call_fn.address, - ]).cfx_transact(priv_key=priv_key) + ]).transact({ + "from": self.cfx.account.from_key(priv_key).address, + }).executed() self.run_task_group(read_then_call) - def read_revert_then_call(call_fn: ContractFunction, storage_contract: Contract, priv_key, before_value, after_value): - call_contract: Contract = self.cfx_contract("StorageExt").at(call_fn.address) + def read_revert_then_call(call_fn: ConfluxContractFunction, storage_contract: ConfluxContract, priv_key, before_value, after_value): + call_contract = self.cfx_contract("StorageExt")(call_fn.address) return call_contract.functions.multiCallExternalWithFlag([ - storage_contract.functions.assertValue(0, 999).data(), - call_fn.data(), + storage_contract.functions.assertValue(0, 999).encode_transaction_data(), + call_fn.encode_transaction_data(), ], [ storage_contract.address, call_fn.address, - ], [2, 0]).cfx_transact(priv_key=priv_key) + ], [2, 0]).transact({ + "from": self.cfx.account.from_key(priv_key).address, + }).executed() self.run_task_group(read_revert_then_call) - def revert_on_first_call(call_fn: ContractFunction, storage_contract: Contract, priv_key, before_value, after_value): - call_contract: Contract = self.cfx_contract("StorageExt").at(call_fn.address) - call_data = call_fn.data() - reverted_call = call_contract.functions.callAnother(call_fn.address, call_data, 4).data() + def revert_on_first_call(call_fn: ConfluxContractFunction, storage_contract: ConfluxContract, priv_key, before_value, after_value): + call_contract = self.cfx_contract("StorageExt")(call_fn.address) + call_data = call_fn.encode_transaction_data() + reverted_call = call_contract.functions.callAnother(call_fn.address, call_data, 4).encode_transaction_data() return call_contract.functions.multiCallExternalWithFlag([ - storage_contract.functions.assertValue(0, before_value).data(), + storage_contract.functions.assertValue(0, before_value).encode_transaction_data(), reverted_call, - storage_contract.functions.assertValue(0, before_value).data(), + storage_contract.functions.assertValue(0, before_value).encode_transaction_data(), call_data, - storage_contract.functions.assertValue(0, after_value).data(), + storage_contract.functions.assertValue(0, after_value).encode_transaction_data(), ], [ storage_contract.address, call_fn.address, storage_contract.address, call_fn.address, storage_contract.address, - ], [0, 2, 0, 0, 0]).cfx_transact(priv_key=priv_key) + ], [0, 2, 0, 0, 0]).transact({ + "from": self.cfx.account.from_key(priv_key).address, + }).executed() self.run_task_group(revert_on_first_call) - def revert_on_second_call(call_fn: ContractFunction, storage_contract: Contract, priv_key, before_value, after_value): - call_contract: Contract = self.cfx_contract("StorageExt").at(call_fn.address) - call_data = call_fn.data() - reverted_call = call_contract.functions.callAnother(call_fn.address, call_data, 4).data() + def revert_on_second_call(call_fn: ConfluxContractFunction, storage_contract: ConfluxContract, priv_key, before_value, after_value): + call_contract = self.cfx_contract("StorageExt")(call_fn.address) + call_data = call_fn.encode_transaction_data() + reverted_call = call_contract.functions.callAnother(call_fn.address, call_data, 4).encode_transaction_data() return call_contract.functions.multiCallExternalWithFlag([ - storage_contract.functions.assertValue(0, before_value).data(), + storage_contract.functions.assertValue(0, before_value).encode_transaction_data(), call_data, - storage_contract.functions.assertValue(0, after_value).data(), + storage_contract.functions.assertValue(0, after_value).encode_transaction_data(), reverted_call, - storage_contract.functions.assertValue(0, after_value).data(), + storage_contract.functions.assertValue(0, after_value).encode_transaction_data(), ], [ storage_contract.address, call_fn.address, storage_contract.address, call_fn.address, storage_contract.address, - ], [0, 0, 0, 2, 0]).cfx_transact(priv_key=priv_key) + ], [0, 0, 0, 2, 0]).transact({ + "from": self.cfx.account.from_key(priv_key).address, + }).executed() self.run_task_group(revert_on_second_call) def run_task_group(self, customized_enactor): - self.storage_contract: Contract = self.cfx_contract("StorageExt").deploy() - self.another_contract: Contract = self.cfx_contract("StorageExt").deploy() + self.storage_contract = self.deploy_contract("StorageExt") + self.another_contract = self.deploy_contract("StorageExt") storage_contract = self.storage_contract another_contract = self.another_contract @@ -110,8 +134,10 @@ def run_task_group(self, customized_enactor): assert_storage_released(receipt, self.genesis_addr2, 64) assert_equal(len(receipt["storageReleased"]), 1) - self.internal_contract("SponsorWhitelistControl").functions.setSponsorForCollateral(storage_contract.address).cfx_transact(value = 1000) - storage_contract.functions.setSponsored(self.genesis_addr3).cfx_transact() + self.internal_contract("SponsorWhitelistControl").functions.setSponsorForCollateral(storage_contract.address).transact({ + "value": CFX(1000) + }).executed() + storage_contract.functions.setSponsored(self.genesis_addr3).transact().executed() fn = storage_contract.functions.change(0) receipt = self.customized_call(fn, priv_key = self.genesis_key3, task_index = 3) @@ -126,15 +152,17 @@ def run_task_group(self, customized_enactor): assert_equal(len(receipt["storageReleased"]), 1) - fn = another_contract.functions.callAnother(storage_contract.address, storage_contract.functions.change(0).data(), 0) + fn = another_contract.functions.callAnother(storage_contract.address, storage_contract.functions.change(0).encode_transaction_data(), 0) receipt = self.customized_call(fn, priv_key = self.genesis_key4, task_index = 5) assert_storage_occupied(receipt, self.genesis_addr4, 0) assert_equal(len(receipt["storageReleased"]), 0) - self.internal_contract("SponsorWhitelistControl").functions.setSponsorForCollateral(another_contract.address).cfx_transact(value = 1000) - another_contract.functions.setSponsored(self.genesis_addr4).cfx_transact() + self.internal_contract("SponsorWhitelistControl").functions.setSponsorForCollateral(another_contract.address).transact({ + "value": CFX(1000) + }).executed() + another_contract.functions.setSponsored(self.genesis_addr4).transact().executed() - fn = another_contract.functions.callAnother(storage_contract.address, storage_contract.functions.change(0).data(), 0) + fn = another_contract.functions.callAnother(storage_contract.address, storage_contract.functions.change(0).encode_transaction_data(), 0) receipt = self.customized_call(fn, priv_key = self.genesis_key4, task_index = 6) assert_storage_occupied(receipt, another_contract.address, 64) assert_storage_released(receipt, self.genesis_addr4, 64) @@ -146,13 +174,13 @@ def run_task_group(self, customized_enactor): assert_storage_released(receipt, another_contract.address, 64) assert_equal(len(receipt["storageReleased"]), 1) - fn = another_contract.functions.callAnother(storage_contract.address, storage_contract.functions.reset(0).data(), 0) + fn = another_contract.functions.callAnother(storage_contract.address, storage_contract.functions.reset(0).encode_transaction_data(), 0) receipt = self.customized_call(fn, priv_key = self.genesis_key2, task_index = 8) assert_storage_occupied(receipt, self.genesis_addr2, 0) assert_storage_released(receipt, storage_contract.address, 64) assert_equal(len(receipt["storageReleased"]), 1) - def customized_call(self, call_fn: ContractFunction, priv_key, task_index): + def customized_call(self, call_fn: ConfluxContractFunction, priv_key, task_index): before_value = task_index after_value = (task_index + 1) % 9 assert_equal(self.storage_at(self.storage_contract.address, 0), before_value) @@ -162,11 +190,11 @@ def customized_call(self, call_fn: ContractFunction, priv_key, task_index): def storage_at(self, addr, key): - result = self.client.get_storage_at(addr.lower(), "{:#066x}".format(key)) + result = self.cfx.get_storage_at(addr, key) if result is None: return 0 else: - return int(result, 0) + return int.from_bytes(result, "big") diff --git a/tests/pubsub/eth_logs_test.py b/tests/pubsub/eth_logs_test.py index e67eda5e9c..60dcaaa418 100755 --- a/tests/pubsub/eth_logs_test.py +++ b/tests/pubsub/eth_logs_test.py @@ -78,10 +78,8 @@ async def run_async(self): # initialize Conflux account priv_key = default_config['GENESIS_PRI_KEY'] self.cfxAccount = self.rpc[FULLNODE0].GENESIS_ADDR - - ip = self.nodes[0].ip - port = self.nodes[0].ethrpcport - self.w3 = Web3(Web3.HTTPProvider(f'http://{ip}:{port}/')) + self.setup_w3() + self.w3 = self.ew3 assert_equal(self.w3.is_connected(), True) # initialize EVM account diff --git a/tests/send_large_nonce_test.py b/tests/send_large_nonce_test.py index 18b2cc0f20..bdfcc09158 100644 --- a/tests/send_large_nonce_test.py +++ b/tests/send_large_nonce_test.py @@ -1,8 +1,9 @@ -from test_framework.contracts import ConfluxTestFramework, RpcClient +from test_framework.test_framework import ConfluxTestFramework from test_framework.util import assert_equal, wait_until import jsonrpcclient from conflux.config import default_config from conflux.utils import priv_to_addr +from conflux.rpc import RpcClient from test_framework.blocktools import encode_hex_0x @@ -14,7 +15,6 @@ def set_test_params(self): def run_test(self): self.genesis_key = default_config["GENESIS_PRI_KEY"] self.genesis_addr = encode_hex_0x(priv_to_addr(self.genesis_key)) - self.client = RpcClient(self.nodes[0]) self.client2 = RpcClient(self.nodes[1]) tx = self.client.new_tx(receiver=self.genesis_addr, gas_price=1, nonce= 2 ** 129) diff --git a/tests/sponsored_tx_test.py b/tests/sponsored_tx_test.py index 1f50562db6..c5ad92c7e8 100755 --- a/tests/sponsored_tx_test.py +++ b/tests/sponsored_tx_test.py @@ -1,32 +1,24 @@ #!/usr/bin/env python3 -from eth_utils import decode_hex - -from conflux.address import hex_to_b32_address -from conflux.rpc import RpcClient, get_contract_function_data +from cfx_utils import CFX from conflux.transactions import CONTRACT_DEFAULT_GAS, COLLATERAL_UNIT_IN_DRIP, charged_of_huge_gas -from conflux.utils import priv_to_addr -from test_framework.block_gen_thread import BlockGenThread -from test_framework.blocktools import create_transaction, encode_hex_0x, wait_for_initial_nonce_for_address -from test_framework.contracts import ConfluxTestFrameworkForContract +from test_framework.test_framework import ConfluxTestFramework from test_framework.mininode import * from test_framework.util import * -from web3 import Web3 -from web3.contract import Contract -class SponsoredTxTest(ConfluxTestFrameworkForContract): +class SponsoredTxTest(ConfluxTestFramework): def __init__(self): super().__init__() self.nonce_map = {} - self.genesis_priv_key = default_config['GENESIS_PRI_KEY'] - self.genesis_addr = priv_to_addr(self.genesis_priv_key) + self.genesis_priv_key = self.core_accounts[0].key + self.genesis_addr = self.core_accounts[0].address self.balance_map = {self.genesis_priv_key: default_config['TOTAL_COIN']} def set_test_params(self): - super().set_test_params() self.num_nodes = 1 def run_test(self): + self.w3 = self.cw3 collateral_per_storage_key = COLLATERAL_UNIT_IN_DRIP * 64 upper_bound = 5 * 10 ** 7 gas = CONTRACT_DEFAULT_GAS @@ -34,10 +26,9 @@ def run_test(self): self.log.info("Initializing contract") control_contract = self.internal_contract("SponsorWhitelistControl") - test_contract = self.cfx_contract("CommissionPrivilegeTest") client = self.client - genesis_addr = self.genesis_addr + genesis_addr = self.genesis_addr.hex_address # Setup balance for node 0 @@ -45,17 +36,21 @@ def run_test(self): self.log.info("addr1={}".format(addr1)) self.cfx_transfer(addr1, 10 ** 6, decimals=0) assert_equal(client.get_balance(addr1), 10 ** 6) + self.w3.wallet.add_account(priv_key1) # setup contract - test_contract: Contract = test_contract.deploy() - contract_addr = test_contract.address + test_contract = self.deploy_contract("CommissionPrivilegeTest") + contract_addr = test_contract.address.hex_address self.log.info("contract_addr={}".format(test_contract.address)) assert_equal(client.get_balance(contract_addr), 0) # sponsor the contract succeed b0 = client.get_balance(genesis_addr) - control_contract.functions.setSponsorForGas(contract_addr, upper_bound).cfx_transact(value = 1, gas = gas) + control_contract.functions.setSponsorForGas(contract_addr, upper_bound).transact({ + "value": CFX(1), + "gas": gas, + }).executed() assert_equal(client.get_sponsor_balance_for_gas(contract_addr), 10 ** 18) assert_equal(client.get_sponsor_for_gas(contract_addr), genesis_addr.lower()) assert_equal(client.get_sponsor_gas_bound(contract_addr), upper_bound) @@ -64,7 +59,10 @@ def run_test(self): # set privilege for addr1 b0 = client.get_balance(genesis_addr) c0 = client.get_collateral_for_storage(genesis_addr) - receipt = test_contract.functions.add(addr1).cfx_transact(storage_limit = 64, gas = gas) + receipt = test_contract.functions.add(addr1).transact({ + "storageLimit": 64, + "gas": gas, + }).executed() assert_equal(client.get_balance(genesis_addr), b0 - charged_of_huge_gas(gas) - collateral_per_storage_key) assert_equal(client.get_collateral_for_storage(genesis_addr), c0 + collateral_per_storage_key) assert_equal(receipt['gasCoveredBySponsor'], False) @@ -73,7 +71,11 @@ def run_test(self): # addr1 call contract with privilege without enough cfx for gas fee sb = client.get_sponsor_balance_for_gas(contract_addr) b1 = client.get_balance(addr1) - receipt = test_contract.functions.foo().cfx_transact(priv_key = priv_key1, storage_limit = 0, gas = gas) + receipt = test_contract.functions.foo().transact({ + "storageLimit": 0, + "gas": gas, + "from": self.cfx.address(addr1), + }).executed() assert_equal(client.get_balance(addr1), b1) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sb - charged_of_huge_gas(gas)) assert_equal(receipt['gasCoveredBySponsor'], True) @@ -81,7 +83,10 @@ def run_test(self): # sponsor collateral for the contract succeed b0 = client.get_balance(genesis_addr) - control_contract.functions.setSponsorForCollateral(contract_addr).cfx_transact(value = 1, gas = gas) + control_contract.functions.setSponsorForCollateral(contract_addr).transact({ + "value": 10 ** 18, + "gas": gas, + }).executed() assert_equal(client.get_sponsor_balance_for_collateral(contract_addr), 10 ** 18) assert_equal(client.get_sponsor_for_collateral(contract_addr), genesis_addr.lower()) assert_equal(client.get_balance(genesis_addr), b0 - 10 ** 18 - charged_of_huge_gas(gas)) @@ -90,13 +95,17 @@ def run_test(self): # addr1 call contract with privilege without enough cfx for storage sb = client.get_sponsor_balance_for_gas(contract_addr) b1 = client.get_balance(addr1) - receipt = test_contract.functions.foo().cfx_transact(priv_key = priv_key1, storage_limit = 1024, gas = gas) + receipt = test_contract.functions.foo().transact({ + "storageLimit": 1024, + "gas": gas, + "from": self.cfx.address(addr1), + }).executed() assert_equal(client.get_balance(addr1), b1) assert_equal(client.get_sponsor_balance_for_gas(contract_addr), sb - charged_of_huge_gas(gas)) assert_equal(receipt['storageCoveredBySponsor'], True) # addr1 call with larger storage limit, should be rejected for not enough balance - data = test_contract.functions.foo().data() + data = test_contract.functions.foo().encode_transaction_data() transaction = client.new_contract_tx(receiver=contract_addr, data_hex=encode_hex(data), priv_key=priv_key1, storage_limit=1025) # rejected for not enough balance diff --git a/tests/storage_value_unchange_test.py b/tests/storage_value_unchange_test.py index 79f6f10b88..a4cc6d7296 100644 --- a/tests/storage_value_unchange_test.py +++ b/tests/storage_value_unchange_test.py @@ -1,32 +1,48 @@ from conflux.utils import * from test_framework.util import * from test_framework.mininode import * -from test_framework.contracts import ConfluxTestFrameworkForContract +from test_framework.test_framework import ConfluxTestFramework -class StorageValueUnchangeTest(ConfluxTestFrameworkForContract): +class StorageValueUnchangeTest(ConfluxTestFramework): + def set_test_params(self): + self.num_nodes = 1 + def run_test(self): - storage_contract: Contract = self.cfx_contract("StorageExt").deploy() + self.w3 = self.cw3 + self.genesis_addr = self.core_accounts[0].address + self.genesis_addr2 = self.cfx.account.from_key(self.evm_secrets[0]).address + self.w3.wallet.add_account(self.evm_secrets[0]) + + storage_contract = self.deploy_contract("StorageExt") # If the storage value does not change, the storage owner remains unchanged - receipt = storage_contract.functions.set(0).cfx_transact(storage_limit = 64) + receipt = storage_contract.functions.set(0).transact().executed() assert_storage_occupied(receipt, self.genesis_addr, 64) - receipt = storage_contract.functions.set(0).cfx_transact(priv_key = self.genesis_key2, storage_limit = 0) + receipt = storage_contract.functions.set(0).transact({ + "from": self.genesis_addr2, + }).executed() assert_equal(receipt["storageCollateralized"], 0) assert_equal(len(receipt["storageReleased"]), 0) - receipt = storage_contract.functions.reset(0).cfx_transact(storage_limit = 0) + receipt = storage_contract.functions.reset(0).transact({ + "from": self.genesis_addr2, + }).executed() assert_storage_released(receipt, self.genesis_addr, 64) # However, the sponsor whitelist does not follow this rule - receipt = storage_contract.functions.setSponsored(self.genesis_addr).cfx_transact(storage_limit = 64) + receipt = storage_contract.functions.setSponsored(self.genesis_addr).transact().executed() assert_storage_occupied(receipt, self.genesis_addr, 64) - receipt = storage_contract.functions.setSponsored(self.genesis_addr).cfx_transact(priv_key = self.genesis_key2, storage_limit = 64) + receipt = storage_contract.functions.setSponsored(self.genesis_addr).transact({ + "from": self.genesis_addr2, + }).executed() assert_storage_occupied(receipt, self.genesis_addr2, 64) assert_storage_released(receipt, self.genesis_addr, 64) - receipt = storage_contract.functions.resetSponsored(self.genesis_addr).cfx_transact(storage_limit = 0) + receipt = storage_contract.functions.resetSponsored(self.genesis_addr).transact({ + "from": self.genesis_addr2, + }).executed() assert_storage_released(receipt, self.genesis_addr2, 64) diff --git a/tests/test_framework/contracts.py b/tests/test_framework/contracts.py deleted file mode 100644 index 7bc92cde2d..0000000000 --- a/tests/test_framework/contracts.py +++ /dev/null @@ -1,281 +0,0 @@ -from os.path import dirname, join -from pathlib import Path -import json -from dataclasses import dataclass - -from typing import Literal, Dict -import types - -from eth_utils.abi import get_abi_output_types -from web3 import Web3 -from web3.contract.contract import ContractFunction, Contract, ContractConstructor -from conflux.address import b32_address_to_hex -from conflux.config import default_config -from conflux.utils import priv_to_addr -from test_framework.blocktools import encode_hex_0x -from test_framework.test_framework import ConfluxTestFramework, RpcClient, start_p2p_connection -from test_framework.util import * -from eth_utils.hexadecimal import decode_hex - - -BASE = int(1e18) -ZERO_ADDRESS = f"0x{'0'*40}" - -InternalContractName = Literal["AdminControl", "SponsorWhitelistControl", - "Staking", "ConfluxContext", "PoSRegister", "CrossSpaceCall", "ParamsControl"] - -INTERNAL_CONTRACT_MAP: Dict[InternalContractName, str] = { - "AdminControl": "0x0888000000000000000000000000000000000000", - "SponsorWhitelistControl": "0x0888000000000000000000000000000000000001", - "Staking": "0x0888000000000000000000000000000000000002", - "ConfluxContext": "0x0888000000000000000000000000000000000004", - "PoSRegister": "0x0888000000000000000000000000000000000005", - "CrossSpaceCall": "0x0888000000000000000000000000000000000006", - "ParamsControl": "0x0888000000000000000000000000000000000007", -} - - -def _load_contract_metadata(name: str): - path = Path(join(dirname(__file__), "..", "test_contracts", "artifacts")) - try: - found_file = next(path.rglob(f"{name}.json")) - return json.loads(open(found_file, "r").read()) - except StopIteration: - raise Exception(f"Cannot found contract {name}'s metadata") - - -def cfx_contract(name: str, framework: ConfluxTestFramework = None) -> Contract: - metadata = _load_contract_metadata(name) - w3 = Web3() - contract = w3.eth.contract( - abi=metadata["abi"], bytecode=metadata["bytecode"]) - - contract.framework = framework - _enact_contract(contract) - return contract - - -def cfx_internal_contract(name: InternalContractName, framework: ConfluxTestFramework = None) -> Contract: - contract_addr = INTERNAL_CONTRACT_MAP[name] - return cfx_contract(name, framework).at(contract_addr) - - -def _add_address(self: Contract, address: str) -> Contract: - w3 = Web3() - new_contract = w3.eth.contract( - abi=self.abi, bytecode=self.bytecode, address=Web3.to_checksum_address(address)) - - new_contract.framework = self.framework - _enact_contract(new_contract) - return new_contract - - -def _deploy_contract(self: Contract, transact_args = None, *args, **kwargs) -> Contract: - if not hasattr(self, "framework"): - raise Exception("Contract does not hold Conflux framework") - - if transact_args is None: - transact_args = {} - - receipt = _cfx_transact(self.constructor( - *args, **kwargs), framework=self.framework, **transact_args) - return _add_address(self, receipt["contractCreated"]) - - -def _deploy_create2_contract(self: Contract, seed, *args, **kwargs) -> Contract: - if not hasattr(self, "framework"): - raise Exception("Contract does not hold Conflux framework") - - if not hasattr(self.framework, "create2factory"): - raise Exception("Create2Factory is not deployed") - - deployCode = _cfx_data(self.constructor(*args, **kwargs)) - receipt = self.framework.create2factory.functions.callCreate2( - seed, deployCode).cfx_transact() - - trace = self.framework.rpc.trace_transaction(receipt["transactionHash"]) - deploy_item = [t for t in trace if t["type"] == "create_result"][0] - created_address = b32_address_to_hex(deploy_item["action"]["addr"]) - - return _add_address(self, created_address) - - -def _enact_contract(contract: Contract): - framework = contract.framework - - contract.at = types.MethodType(_add_address, contract) - contract.deploy = types.MethodType(_deploy_contract, contract) - contract.deploy2 = types.MethodType(_deploy_create2_contract, contract) - - for _, obj in contract.functions.__dict__.items(): - if isinstance(obj, ContractFunction): - obj.framework = framework - - -def _get_framework(fn: ContractFunction) -> ConfluxTestFramework: - if hasattr(fn, "framework") and isinstance(fn.framework, ConfluxTestFramework): - pass - else: - raise Exception( - f"Not bind test framework when making call for {fn.function_identifier}") - - return fn.framework - - -def _cfx_transact(self: ContractFunction, value=None, decimals: int = 18, gas=None, storage_limit=None, priv_key=None, err_msg = None, framework=None): - if framework is None: - framework = _get_framework(self) - - tx = self.build_transaction( - {"gas": 3000000, "gasPrice": 1, "chainId": 1}) - data = bytes.fromhex(tx["data"][2:]) - - if value is not None: - value = int(value * (10**decimals)) - else: - value = 0 - - if storage_limit is None: - if len(tx["to"]) == 0: - storage_limit = 30000 - else: - storage_limit = 1024 - - if gas is None: - if len(tx["to"]) == 0: - gas = 10_000_000 - else: - gas = 3_000_000 - - if len(tx["to"]) == 0: - receiver = None - else: - receiver = tx["to"] - - if gas is None: - if len(data) > 0: - gas = 3000000 - else: - gas = 21000 - - tx = framework.client.new_contract_tx( - receiver=receiver, value=value, data_hex=tx["data"], priv_key=priv_key, gas=gas, storage_limit=storage_limit) - framework.client.send_tx(tx, True) - framework.wait_for_tx([tx], err_msg is None) - receipt = framework.client.get_transaction_receipt(tx.hash_hex()) - if err_msg is not None: - assert_equal(receipt["txExecErrorMsg"], err_msg) - # self.log.info(receipt) - return receipt - - - -def _cfx_call(self: ContractFunction, framework=None, sender=None, raw_output=False): - if framework is None: - framework = _get_framework(self) - - tx = self.build_transaction( - {"gas": 3000000, "gasPrice": 1, "chainId": 1}) - result = framework.client.call(tx["to"], tx["data"], sender=sender) - - if not raw_output: - output_types = get_abi_output_types(self.abi) - ans = self.w3.codec.decode(output_types, decode_hex(result)) - if len(ans) == 0: - return - elif len(ans) == 1: - return ans[0] - else: - return ans - else: - return result - - -def _cfx_data(self: ContractFunction): - tx = self.build_transaction( - {"gas": 3000000, "gasPrice": 1, "chainId": 1}) - return tx["data"] - - -setattr(ContractFunction, 'cfx_transact', _cfx_transact) -setattr(ContractFunction, 'cfx_call', _cfx_call) -setattr(ContractFunction, 'data', _cfx_data) - -setattr(ContractConstructor, 'cfx_transact', _cfx_transact) -setattr(ContractConstructor, 'cfx_call', _cfx_call) -setattr(ContractConstructor, 'data', _cfx_data) - - -@dataclass -class Account: - address: str - key: str - -class ConfluxTestFrameworkForContract(ConfluxTestFramework): - def __init__(self): - super().__init__() - - def set_test_params(self): - self.num_nodes = 1 - self.conf_parameters["executive_trace"] = "true" - - def before_test(self): - if "executive_trace" not in self.conf_parameters or not bool(self.conf_parameters["executive_trace"]): - raise AssertionError( - "Trace should be enabled for contract toolkit") - super().before_test() - self.rpc = self.nodes[0].rpc - self.client = RpcClient(self.nodes[0]) - ip = self.nodes[0].ip - port = self.nodes[0].ethrpcport - self.w3 = Web3(Web3.HTTPProvider(f'http://{ip}:{port}/')) - start_p2p_connection(self.nodes) - self.deploy_create2() - - self.genesis_key = default_config["GENESIS_PRI_KEY"] - self.genesis_addr = Web3.to_checksum_address(encode_hex_0x(priv_to_addr(self.genesis_key))) - self.genesis_key2 = default_config["GENESIS_PRI_KEY_2"] - self.genesis_addr2 = Web3.to_checksum_address(encode_hex_0x(priv_to_addr(self.genesis_key2))) - - def cfx_contract(self, name): - return cfx_contract(name, self) - - def internal_contract(self, name: InternalContractName): - return cfx_internal_contract(name, self) - - def cfx_transfer(self, receiver, value=None, gas_price=1, priv_key=None, decimals: int = 18, nonce = None, execute: bool = True): - if value is not None: - value = int(value * (10**decimals)) - else: - value = 0 - - tx = self.client.new_tx( - receiver=receiver, gas_price=gas_price, priv_key=priv_key, value=value, nonce=nonce) - self.client.send_tx(tx, execute) - if execute: - self.wait_for_tx([tx], True) - receipt = self.client.get_transaction_receipt(tx.hash_hex()) - # self.log.info(receipt) - return receipt - else: - return tx.hash_hex() - - def initialize_accounts(self, number = 10, value = 100) -> List[Account]: - def initialize_new_account() -> (str, bytes): - (address, priv) = self.client.rand_account() - if value > 0: - self.cfx_transfer(address, value = value) - return Account(address, priv) - - return [initialize_new_account() for _ in range(number)] - - @property - def adminControl(self): - return self.internal_contract("AdminControl") - - @property - def sponsorControl(self): - return self.internal_contract("SponsorWhitelistControl") - - def deploy_create2(self): - self.create2factory: Contract = self.cfx_contract("Create2Factory").deploy() diff --git a/tests/test_framework/test_framework.py b/tests/test_framework/test_framework.py index 755c960fa0..f465544192 100644 --- a/tests/test_framework/test_framework.py +++ b/tests/test_framework/test_framework.py @@ -3,7 +3,8 @@ # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Base class for RPC testing.""" -from typing import List, Literal, Union +from typing import List, Literal, Union, Any, Type, cast +from functools import cached_property from conflux.config import DEFAULT_PY_TEST_CHAIN_ID from conflux.messages import Transactions from conflux.rpc import RpcClient, default_config @@ -20,6 +21,16 @@ from typing import Union import random +from conflux_web3 import Web3 as CWeb3 +from conflux_web3.middleware.base import ConfluxWeb3Middleware +from conflux_web3._utils.rpc_abi import ( + RPC +) +from conflux_web3.contract import ConfluxContract +from web3 import Web3 +from web3.middleware.signing import SignAndSendRawMiddlewareBuilder +from web3.types import RPCEndpoint +from cfx_account import Account as CoreAccount from eth_account import Account from .authproxy import JSONRPCException @@ -44,7 +55,10 @@ sync_blocks, sync_mempools, wait_until, + load_contract_metadata, + InternalContractName, ) +from .block_gen_thread import BlockGenThread class TestStatus(Enum): PASSED = 1 @@ -56,6 +70,7 @@ class TestStatus(Enum): TEST_EXIT_FAILED = 1 TEST_EXIT_SKIPPED = 77 +Web3NotSetupError = ValueError("w3 is not initialized, please call self.setup_w3() first") class ConfluxTestFramework: """Base class for a bitcoin test script. @@ -73,6 +88,10 @@ class ConfluxTestFramework: This class also contains various public and private helper methods.""" + _cw3: Union[CWeb3, None] = None + _ew3: Union[Web3, None] = None + num_nodes: int = 0 + def __init__(self): """Sets test framework defaults. Do not override this method. Instead, override the set_test_params() method""" self.core_secrets: list[str] = [default_config["GENESIS_PRI_KEY"].hex()] # type: ignore @@ -96,21 +115,96 @@ def __init__(self): self, "num_nodes"), "Test must set self.num_nodes in set_test_params()" - # add random secrets to self.secrets - # when node starts, self.secrets will be used - # to generate genesis account for both EVM and Core - # each with 10000 CFX (10^21 drip) + def _add_genesis_secrets( self, additional_secrets: int, space: Union[List[Literal["evm", "core"]], Literal["evm", "core"]]=["evm", "core"] ): + """ + Add random secrets to `self.core_secrets` and `self.evm_secrets`. + When node starts, `self.core_secrets` and `self.evm_secrets` will be used + to generate genesis account for both EVM and Core + each with 10000 CFX (10^21 drip). + + The generated accounts can be used from `self.core_accounts` or `self.evm_accounts`. + """ for _ in range(additional_secrets): if "evm" in space or "evm" == space: self.evm_secrets.append(Account.create().key.hex()) if "core" in space or "core" == space: self.core_secrets.append(Account.create().key.hex()) - + + @cached_property + def client(self) -> RpcClient: + """Get the RPC client, using the first node. + The RPC client is + + Returns: + RpcClient: used to send RPC requests to the node. + For example, self.client.cfx_getBalance(...) or self.client.eth_getBalance(...) + It should be noticed that the parameters are usually not formatted. + Certain methods also provide formatted parameters, for example, self.client.epoch_number(). + Please check the source code for more details. + """ + return RpcClient(self.nodes[0]) + + @property + def cw3(self) -> CWeb3: + """Get the Conflux Web3 instance, initialized by self.setup_w3(). + + Raises: + Web3NotSetupError: If the Web3 instance is not initialized. + + Returns: + CWeb3: The Conflux Web3 instance. + """ + if self._cw3 is None: + raise Web3NotSetupError + return self._cw3 + + @property + def ew3(self) -> Web3: + """Get the EVM Web3 instance, initialized by self.setup_w3(). + + Raises: + Web3NotSetupError: If the Web3 instance is not initialized. + + Returns: + Web3: The EVM Web3 instance. + """ + if self._ew3 is None: + raise Web3NotSetupError + return self._ew3 + + @property + def cfx(self): + if self._cw3 is None: + raise Web3NotSetupError + return self._cw3.cfx + + @property + def eth(self): + if self._ew3 is None: + raise Web3NotSetupError + return self._ew3.eth + + @property + def core_accounts(self): + """ + Get the core space genesis accounts. + Amount can be added by `self._add_genesis_secrets(additional_secrets_count)`. + """ + return [CoreAccount.from_key(key, network_id=DEFAULT_PY_TEST_CHAIN_ID) for key in self.core_secrets] + + @property + def evm_accounts(self): + """ + Get the eSpace genesis accounts. + Amount can be added by `self._add_genesis_secrets(additional_secrets_count)`. + """ + return [Account.from_key(key) for key in self.evm_secrets] + def main(self): """Main function. This should not be overridden by the subclass test scripts.""" @@ -236,7 +330,7 @@ def main(self): self.setup_chain() self.setup_network() self.before_test() - self.run_test() + self.run_test() # type: ignore success = TestStatus.PASSED except JSONRPCException as e: self.log.exception("JSONRPC error") @@ -337,6 +431,42 @@ def setup_nodes(self, genesis_nodes=None, binary=None, is_consortium=True): self.add_nodes(self.num_nodes, genesis_nodes=genesis_nodes, binary=binary, is_consortium=is_consortium) self.start_nodes() + def setup_w3(self): + """Setup w3 and ew3 for EVM and Conflux. + This method should be called before any test. + Use self.w3 and self.ew3 to access the web3 instances. + Use self.cfx and self.eth to access the Conflux and EVM RPC clients. + """ + client = RpcClient(self.nodes[0]) + log = self.log + self._cw3 = CWeb3(CWeb3.HTTPProvider(f'http://{self.nodes[0].ip}:{self.nodes[0].rpcport}/')) + self._ew3 = Web3(Web3.HTTPProvider(f'http://{self.nodes[0].ip}:{self.nodes[0].ethrpcport}/')) + self.cw3.wallet.add_accounts(self.core_accounts) + self.cw3.cfx.default_account = self.core_accounts[0].address + + self.ew3.middleware_onion.add(SignAndSendRawMiddlewareBuilder.build(self.evm_secrets)) # type: ignore + self.eth.default_account = self.evm_accounts[0].address + + class TestNodeMiddleware(ConfluxWeb3Middleware): + def request_processor(self, method: RPCEndpoint, params: Any) -> Any: + if method == RPC.cfx_sendRawTransaction or method == RPC.cfx_sendTransaction: + client.node.wait_for_phase(["NormalSyncPhase"]) + + if method == RPC.cfx_maxPriorityFeePerGas: + if client.epoch_number() == 0: + # enable cfx_maxPriorityFeePerGas + # or Error(Epoch number larger than the current pivot chain tip) would be raised + client.generate_blocks_to_state(num_txs=1) + return super().request_processor(method, params) + + def response_processor(self, method: RPCEndpoint, response: Any): + if method == RPC.cfx_getTransactionReceipt: + if "result" in response and response["result"] is None: + log.debug("Auto generate 5 blocks because did not get tx receipt") + client.generate_blocks_to_state(num_txs=1) # why num_txs=1? + return response + self.cw3.middleware_onion.add(TestNodeMiddleware) + def add_nodes(self, num_nodes, genesis_nodes=None, rpchost=None, binary=None, auto_recovery=False, recovery_timeout=30, is_consortium=True): """Instantiate TestNode objects""" @@ -486,7 +616,7 @@ def _initialize_chain_clean(self): self.extra_conf_files, self.core_secrets, self.evm_secrets) def before_test(self): - pass + self.setup_w3() # wait for core space tx def wait_for_tx(self, all_txs, check_status=False): @@ -519,6 +649,72 @@ def wait_for_tx(self, all_txs, check_status=False): raise AssertionError("Receipt states the execution failes: {}".format(i)) return receipts + def start_block_gen(self): + BlockGenThread(self.nodes, self.log).start() + + # def enable_max_priority_fee_per_gas(self): + # # enable cfx_maxPriorityFeePerGas + # # or Error(Epoch number larger than the current pivot chain tip) would be raised + # self.client.generate_blocks_to_state(num_txs=1) + + def cfx_contract(self, name) -> Type[ConfluxContract]: + metadata = load_contract_metadata(name) + return self.cfx.contract( + abi=metadata["abi"], bytecode=metadata["bytecode"]) + + def internal_contract(self, name: InternalContractName): + return self.cfx.contract(name=name, with_deployment_info=True) + + def deploy_contract(self, name, transact_args = {}) -> ConfluxContract: + tx_hash = self.cfx_contract(name).constructor().transact(transact_args) + receipt = tx_hash.executed(timeout=30) + return self.cfx_contract(name)(cast(str, receipt["contractCreated"])) + + def deploy_create2(self): + self.create2factory = self.deploy_contract("Create2Factory") + self.client.generate_blocks(5) + + def deploy_contract_2(self, name, seed, *args, **kwargs) -> ConfluxContract: + if self.create2factory is None: + raise Exception("Create2Factory is not deployed") + contract_factory = self.cfx_contract(name) + deploy_code = contract_factory.constructor(*args, **kwargs)._build_transaction()["data"] + dest_address = self.create2factory.functions.callCreate2(seed, deploy_code).call() + self.create2factory.functions.callCreate2(seed, deploy_code).transact().executed() + return contract_factory(dest_address) + + def cfx_transfer(self, receiver, value=None, gas_price=1, priv_key=None, decimals: int = 18, nonce = None, execute: bool = True): + if value is not None: + value = int(value * (10**decimals)) + else: + value = 0 + + tx = self.client.new_tx( + receiver=receiver, gas_price=gas_price, priv_key=priv_key, value=value, nonce=nonce) + self.client.send_tx(tx, execute) + if execute: + self.wait_for_tx([tx], True) + receipt = self.client.get_transaction_receipt(tx.hash_hex()) + return receipt + else: + return tx.hash_hex() + + def initialize_accounts(self, number = 10, value = 100): + """ + NOT RECOMMENDED. + It is now recommended to use `self._add_genesis_account` + in `set_test_params` to add genesis accounts. + + The generated accounts can be used from self.core_accounts or self.evm_accounts. + """ + def initialize_new_account(): + acct = self.cfx.account.create() + if value > 0: + self.cfx_transfer(acct.hex_address, value = value) + return acct + + return [initialize_new_account() for _ in range(number)] + class SkipTest(Exception): """This exception is raised to skip a test""" diff --git a/tests/test_framework/util.py b/tests/test_framework/util.py index 2fcf1eb134..45083233c6 100644 --- a/tests/test_framework/util.py +++ b/tests/test_framework/util.py @@ -11,11 +11,12 @@ import re from subprocess import CalledProcessError, check_output import time -from typing import Optional, Callable, List, TYPE_CHECKING, cast, Tuple, Union +from typing import Optional, Callable, List, TYPE_CHECKING, cast, Tuple, Union, Literal import socket import threading import jsonrpcclient.exceptions import solcx +import conflux_web3 # should be imported before web3 import web3 from cfx_account import Account as CfxAccount from cfx_account.signers.local import LocalAccount as CfxLocalAccount @@ -23,7 +24,8 @@ import yaml import shutil import math - +from os.path import dirname, join +from pathlib import Path from test_framework.simple_rpc_proxy import SimpleRpcProxy from . import coverage @@ -39,6 +41,8 @@ logger = logging.getLogger("TestFramework.utils") +ZERO_ADDRESS = f"0x{'0'*40}" + # Assert functions ################## @@ -64,7 +68,13 @@ def assert_storage_occupied(receipt, addr, expected): def assert_storage_released(receipt, addr, expected): - assert_equal(receipt["storageReleased"].get(addr.lower(), 0), expected) + for storage_change_object in receipt["storageReleased"]: + if storage_change_object["address"] == addr: + assert_equal(storage_change_object["collaterals"], expected) + return + # not found in receipt + if expected != 0: + raise AssertionError(f"Storage released for address {addr} not found in receipt: {receipt['storageReleased']}") def assert_equal(thing1, thing2, *args): @@ -931,3 +941,21 @@ def get_gas_charged(rpc: "RpcClient", tx_hash: str) -> int: assert is_in_pivot_block == False, "Transaction should be in non-pivot block" assert max_fee_per_gas >= burnt_fee_per_gas +def assert_tx_exec_error(client: "RpcClient", tx_hash: str, err_msg: str): + client.wait_for_receipt(tx_hash) + receipt = client.get_transaction_receipt(tx_hash) + assert_equal(receipt["txExecErrorMsg"], err_msg) + + +InternalContractName = Literal["AdminControl", "SponsorWhitelistControl", + "Staking", "ConfluxContext", "PoSRegister", "CrossSpaceCall", "ParamsControl"] + + + +def load_contract_metadata(name: str): + path = Path(join(dirname(__file__), "..", "test_contracts", "artifacts")) + try: + found_file = next(path.rglob(f"{name}.json")) + return json.loads(open(found_file, "r").read()) + except StopIteration: + raise Exception(f"Cannot found contract {name}'s metadata") diff --git a/tests/tx_pool_gc_test.py b/tests/tx_pool_gc_test.py index 2c6b2b6411..a62b0f5a53 100644 --- a/tests/tx_pool_gc_test.py +++ b/tests/tx_pool_gc_test.py @@ -1,17 +1,16 @@ -from test_framework.contracts import ConfluxTestFrameworkForContract +from test_framework.test_framework import ConfluxTestFramework from test_framework.util import assert_equal -class TxPoolGarbageCollectTest(ConfluxTestFrameworkForContract): +class TxPoolGarbageCollectTest(ConfluxTestFramework): def set_test_params(self): - super().set_test_params() self.num_nodes = 1 self.conf_parameters["tx_pool_size"] = "5" def run_test(self): accounts = self.initialize_accounts(number = 11) - addr = accounts[0].address + addr = accounts[0].hex_address for i in range(1, 11): self.cfx_transfer(addr, 1, (i+10) * (10**9), priv_key=accounts[i].key, execute=False) diff --git a/tests/tx_replace_test.py b/tests/tx_replace_test.py index 7db8557b69..7e4b365951 100644 --- a/tests/tx_replace_test.py +++ b/tests/tx_replace_test.py @@ -1,6 +1,4 @@ -from test_framework.contracts import ConfluxTestFramework, RpcClient -from test_framework.util import assert_equal, wait_until -import jsonrpcclient +from test_framework.test_framework import ConfluxTestFramework from conflux.config import default_config from conflux.utils import priv_to_addr from test_framework.blocktools import encode_hex_0x @@ -13,7 +11,6 @@ def set_test_params(self): def run_test(self): self.genesis_key = default_config["GENESIS_PRI_KEY"] self.genesis_addr = encode_hex_0x(priv_to_addr(self.genesis_key)) - self.client = RpcClient(self.nodes[0]) tx = self.client.new_tx(receiver=self.genesis_addr, gas_price=20, nonce=0) self.client.send_tx(tx, False) diff --git a/tests/vote_token_test.py b/tests/vote_token_test.py index eb8318dbe1..92bf7e098c 100755 --- a/tests/vote_token_test.py +++ b/tests/vote_token_test.py @@ -1,27 +1,21 @@ #!/usr/bin/env python3 -from conflux.utils import priv_to_addr -from eth_utils import decode_hex -from conflux.rpc import RpcClient from conflux.transactions import CONTRACT_DEFAULT_GAS -from test_framework.blocktools import create_transaction, encode_hex_0x -from test_framework.contracts import ConfluxTestFrameworkForContract, Account -from test_framework.block_gen_thread import BlockGenThread +from test_framework.test_framework import ConfluxTestFramework from test_framework.mininode import * from test_framework.util import * -from web3 import Web3 -from web3.contract import Contract +from conflux_web3.contract import ConfluxContract import random -class VoteTokenTest(ConfluxTestFrameworkForContract): +class VoteTokenTest(ConfluxTestFramework): def __init__(self): super().__init__() self.vote_address = "" self.token_address = "" - self.token_contract: Contract = None - self.vote_contract: Contract = None + self.token_contract: ConfluxContract = None + self.vote_contract: ConfluxContract = None self.accounts = [] self.num_of_options = 5 self.gas_price = 1 @@ -29,25 +23,27 @@ def __init__(self): self.tx_conf = {"gas":int_to_hex(self.gas), "gasPrice":int_to_hex(self.gas_price)} def set_test_params(self): - super().set_test_params() self.num_nodes = 1 + self._add_genesis_secrets(5, "core") def setup_contract(self): - self.token_contract = self.cfx_contract("DummyErc20").deploy() - self.vote_contract = self.cfx_contract("AdvancedTokenVote1202").deploy() + self.token_contract = self.deploy_contract("DummyErc20") + self.vote_contract = self.deploy_contract("AdvancedTokenVote1202") self.log.info("Initializing contract") def run_test(self): - self.token_contract = self.cfx_contract("DummyErc20").deploy() - self.vote_contract = self.cfx_contract("AdvancedTokenVote1202").deploy() - self.log.info("Initializing contract") - self.accounts: List[Account] = self.initialize_accounts(5) + self.setup_contract() + accounts = self.core_accounts[1:6] for i in range(1): - self.vote_contract.functions.createIssue(i, self.token_contract.address, list(range(self.num_of_options)), [acc.address for acc in self.accounts], "v").cfx_transact(storage_limit = 5120) + self.vote_contract.functions.createIssue(i, self.token_contract.address, list(range(self.num_of_options)), [acc.address for acc in accounts], "v").transact({ + "storageLimit": 5120, + }).executed() for _ in range(self.num_of_options): vote_choice = random.randint(0, self.num_of_options - 1) - self.vote_contract.functions.vote(i, vote_choice).cfx_transact(storage_limit = 5120) + self.vote_contract.functions.vote(i, vote_choice).transact({ + "storageLimit": 5120, + }).executed() diff --git a/tests/web3_test.py b/tests/web3_test.py index a26f848d6a..ce7c053da5 100644 --- a/tests/web3_test.py +++ b/tests/web3_test.py @@ -123,9 +123,8 @@ def test_deploy_1820(self): def run_test(self): time.sleep(3) - ip = self.nodes[0].ip - port = self.nodes[0].ethrpcport - self.w3 = Web3(Web3.HTTPProvider(f'http://{ip}:{port}/')) + self.setup_w3() + self.w3 = self.ew3 assert_equal(self.w3.is_connected(), True) account = self.w3.eth.account.from_key(