Exemple #1
0
    def testBallotContract(self):
        CONTRACT_PATH = "contracts/ballot_bytecode.dat"
        logs = self.rpc.get_logs(self.filter)
        l = len(logs)

        # construct contract object
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        contract = solc.get_contract_instance(
            abi_file=os.path.join(file_dir, "contracts/ballot_abi.json"),
            bytecode_file=os.path.join(file_dir, CONTRACT_PATH),
        )

        # deploy contract
        data = contract.constructor(10).buildTransaction(self.tx_conf)["data"]
        receipt, contractAddr = self.deploy_contract(self.sender,
                                                     self.priv_key, data)
        contractAddr = Web3.toChecksumAddress(contractAddr)
        self.tx_conf["to"] = contractAddr

        # interact with vote()
        data = contract.functions.vote(5).buildTransaction(
            self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data)
        logs = self.rpc.get_logs(self.filter)
        assert_equal(len(logs), l + 1)
        assert_equal(logs[-1]["data"], self.number_to_topic(5))

        # call const function winningProposal()
        data = contract.functions.winningProposal().buildTransaction(
            self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert_equal(result, self.number_to_topic(5))
Exemple #2
0
    def _deposit(self):
        # lock tokens in bank
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        staking_contract = solc.get_contract_instance(
            abi_file=os.path.join(
                file_dir, "../contracts/storage_interest_staking_abi.json"),
            bytecode_file=os.path.join(
                file_dir,
                "../contracts/storage_interest_staking_bytecode.dat"),
        )

        gas_price = 1
        gas = 50000000
        self.tx_conf = {
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }
        staking_contract_addr = Web3.toChecksumAddress(
            "443c409373ffd5c0bec1dddb7bec830856757b65")
        self.tx_conf["to"] = staking_contract_addr
        tx_data = eth_utils.decode_hex(
            staking_contract.functions.deposit(
                10000 * 10**18).buildTransaction(self.tx_conf)["data"])
        tx = self.new_tx(value=0,
                         receiver=staking_contract_addr,
                         data=tx_data,
                         gas=gas,
                         gas_price=gas_price)
        self.send_tx(tx, True)
Exemple #3
0
    def run_test(self):
        # Prevent easysolc from configuring the root logger to print to stderr
        self.log.propagate = False

        solc = Solc()
        # erc20_contract = solc.get_contract_instance(source=os.path.dirname(os.path.realpath(__file__)) + "/erc20.sol", contract_name="FixedSupplyToken")
        file_dir = os.path.dirname(os.path.realpath(__file__))
        erc20_contract = solc.get_contract_instance(
            abi_file = os.path.join(file_dir, "contracts/erc20_abi.json"),
            bytecode_file = os.path.join(file_dir, "contracts/erc20_bytecode.dat"),
        )

        start_p2p_connection(self.nodes)

        self.log.info("Initializing contract")
        genesis_key = default_config["GENESIS_PRI_KEY"]
        genesis_addr = privtoaddr(genesis_key)
        nonce = 0
        gas_price = 1
        gas = 50000000
        block_gen_thread = BlockGenThread(self.nodes, self.log)
        block_gen_thread.start()
        self.tx_conf = {"from":Web3.toChecksumAddress(encode_hex_0x(genesis_addr)), "nonce":int_to_hex(nonce), "gas":int_to_hex(gas), "gasPrice":int_to_hex(gas_price), "chainId":0}
        raw_create = erc20_contract.constructor().buildTransaction(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)
        self.nodes[0].p2p.send_protocol_msg(Transactions(transactions=[tx_create]))
        self.wait_for_tx([tx_create])
        self.log.info("Contract created, start transfering tokens")

        tx_n = 10
        self.tx_conf["to"] = Web3.toChecksumAddress(encode_hex_0x(sha3_256(rlp.encode([genesis_addr, nonce]))[-20:]))
        nonce += 1
        balance_map = {genesis_key: 1000000 * 10**18}
        sender_key = genesis_key
        all_txs = []
        for i in range(tx_n):
            value = int((balance_map[sender_key] - ((tx_n - i) * 21000 * gas_price)) * random.random())
            receiver_sk, _ = ec_random_keys()
            balance_map[receiver_sk] = value
            tx_data = decode_hex(erc20_contract.functions.transfer(Web3.toChecksumAddress(encode_hex(privtoaddr(receiver_sk))), value).buildTransaction(self.tx_conf)["data"])
            tx = create_transaction(pri_key=sender_key, receiver=decode_hex(self.tx_conf["to"]), value=0, nonce=nonce, gas=gas,
                                    gas_price=gas_price, data=tx_data)
            r = random.randint(0, self.num_nodes - 1)
            self.nodes[r].p2p.send_protocol_msg(Transactions(transactions=[tx]))
            nonce += 1
            balance_map[sender_key] -= value
            all_txs.append(tx)
        self.log.info("Wait for transactions to be executed")
        self.wait_for_tx(all_txs)
        self.log.info("Check final token balance")
        for sk in balance_map:
            addr = privtoaddr(sk)
            assert_equal(self.get_balance(erc20_contract, addr, nonce), balance_map[sk])
        block_gen_thread.stop()
        block_gen_thread.join()
        sync_blocks(self.nodes)
        self.log.info("Pass")
    def setup_contract(self):
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        self.contract = solc.get_contract_instance(
            source=os.path.join(file_dir, "contracts/fixed_supply_token.sol"),
            contract_name="FixedSupplyToken")
        self.log.info("Initializing contract")

        transaction = self.call_contract_function(self.contract, "constructor",
                                                  [], self.default_account_key)
        self.contract_address = self.wait_for_tx([transaction],
                                                 True)[0]['contractCreated']
        self.accounts = [a[0] for a in self.new_address_and_transfer(2)]
Exemple #5
0
    def compile_contract(cls, contract_path, contract_name, solc_path='', save=True):
        solc = Solc(solc_path)

        logger.info('Compiling contract from path "%s", named "%s" ...',
                    contract_path, contract_name)
        compiled_contract = solc.get_contract_instance(source=contract_path, 
                                                       contract_name=contract_name)
        logger.info('Compiled contract!')

        if save:
            contract_build_path = cls.get_contract_build_path(contract_path)
            cls.save_contract_build(compiled_contract.abi, compiled_contract.bytecode, contract_build_path)

        return compiled_contract
def s_compile():
    solc = Solc()
    # 编译智能合约并放在当前目录
    solc.compile('sign.sol', output_dir='.')
    #return
    
    w3 = Web3(HTTPProvider("http://localhost:8545")) #有疑问请看web3.py官网
    w3.eth.defaultAccount = w3.eth.accounts[0]    #使用账户0来部署。
    
    # 获取智能合约实例 其中abi和bin文件为编译后生成的文件,可以去你的项目目录下找。
    contract = solc.get_contract_instance(w3=w3, abi_file='sign.abi', bytecode_file='sign.bin') 
    # 部署智能合约
    tx_hash = contract.constructor().transact()
    tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)#等待挖矿过程
    # 获得智能合约部署在链上的地址
    contractAddr = tx_receipt.contractAddress
    def setup_contract(self):
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        staking_contract = solc.get_contract_instance(
            abi_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_abi.json"),
            bytecode_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_bytecode.dat"),
        )

        staking_contract_addr = Web3.toChecksumAddress(
            "443c409373ffd5c0bec1dddb7bec830856757b65")
        self.tx_conf["to"] = staking_contract_addr
        tx_data = decode_hex(
            staking_contract.functions.deposit(1000 * 10**18).buildTransaction(
                self.tx_conf)["data"])
        node = self.nodes[0]
        client = RpcClient(node)
        genesis_key = default_config["GENESIS_PRI_KEY"]
        genesis_addr = privtoaddr(genesis_key)
        tx = client.new_tx(value=0,
                           receiver=staking_contract_addr,
                           nonce=self.get_nonce(genesis_addr),
                           data=tx_data,
                           gas=self.gas,
                           gas_price=self.gas_price)
        client.send_tx(tx)
        self.wait_for_tx([tx], False)

        self.token_contract = solc.get_contract_instance(
            source=os.path.join(file_dir, "contracts/vote.sol"),
            contract_name="DummyErc20")
        self.vote_contract = solc.get_contract_instance(
            source=os.path.join(file_dir, "contracts/vote.sol"),
            contract_name="AdvancedTokenVote1202")
        self.log.info("Initializing contract")
        transaction = self.call_contract_function(self.token_contract,
                                                  "constructor", [],
                                                  self.default_account_key)
        self.token_address = self.wait_for_tx([transaction],
                                              True)[0]['contractCreated']
        transaction = self.call_contract_function(self.vote_contract,
                                                  "constructor", [],
                                                  self.default_account_key)
        self.vote_address = self.wait_for_tx([transaction],
                                             True)[0]['contractCreated']
        self.accounts = [a[0] for a in self.new_address_and_transfer(5)]
Exemple #8
0
    def testPayContract(self):
        CONTRACT_PATH = "contracts/pay_bytecode.dat"
        logs = self.rpc.get_logs(self.filter)
        l = len(logs)

        # construct contract object
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        contract = solc.get_contract_instance(
            abi_file=os.path.join(file_dir, "contracts/pay_abi.json"),
            bytecode_file=os.path.join(file_dir, CONTRACT_PATH),
        )

        # deploy contract
        data = contract.constructor().buildTransaction(self.tx_conf)["data"]
        receipt, contractAddr = self.deploy_contract(self.sender,
                                                     self.priv_key, data)
        contractAddr = Web3.toChecksumAddress(contractAddr)
        self.tx_conf["to"] = contractAddr
        logs = self.rpc.get_logs(self.filter)
        l = len(logs)

        b0 = self.rpc.get_balance(self.sender)
        # interact with recharge()
        data = contract.functions.recharge().buildTransaction(
            self.tx_conf)["data"]
        cost = 5000000000000000000
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data, cost)
        b1 = self.rpc.get_balance(self.sender)
        bc = self.rpc.get_balance(contractAddr)
        assert_equal(bc, cost)

        #interact with withdraw
        data = contract.functions.withdraw(
            self.sender_checksum).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data, 0)
        b2 = self.rpc.get_balance(self.sender)
        bc = self.rpc.get_balance(contractAddr)
        logs = self.rpc.get_logs(self.filter)
        assert_equal(bc, 0)
Exemple #9
0
    def testDaiJoinContract(self):
        solc = Solc()
        CONTRACT_PATH = "contracts/Dai_bytecode.dat"
        file_dir = os.path.dirname(os.path.realpath(__file__))
        dai = solc.get_contract_instance(
            abi_file=os.path.join(file_dir, "contracts/Dai_abi.json"),
            bytecode_file=os.path.join(file_dir, CONTRACT_PATH),
        )
        data = dai.constructor(1).buildTransaction(self.tx_conf)["data"]
        receipt, contractAddr = self.deploy_contract(self.sender,
                                                     self.priv_key, data)
        dai_addr = Web3.toChecksumAddress(contractAddr)

        CONTRACT_PATH = "contracts/Vat_bytecode.dat"
        file_dir = os.path.dirname(os.path.realpath(__file__))
        vat = solc.get_contract_instance(
            abi_file=os.path.join(file_dir, "contracts/Vat_abi.json"),
            bytecode_file=os.path.join(file_dir, CONTRACT_PATH),
        )
        data = vat.constructor().buildTransaction(self.tx_conf)["data"]
        receipt, contractAddr = self.deploy_contract(self.sender,
                                                     self.priv_key, data)
        vat_addr = Web3.toChecksumAddress(contractAddr)

        CONTRACT_PATH = "contracts/DaiJoin_bytecode.dat"
        file_dir = os.path.dirname(os.path.realpath(__file__))
        dai_join = solc.get_contract_instance(
            abi_file=os.path.join(file_dir, "contracts/DaiJoin_abi.json"),
            bytecode_file=os.path.join(file_dir, CONTRACT_PATH),
        )
        data = dai_join.constructor(vat_addr, dai_addr).buildTransaction(
            self.tx_conf)["data"]
        receipt, contractAddr = self.deploy_contract(self.sender,
                                                     self.priv_key, data)
        dai_join_addr = Web3.toChecksumAddress(contractAddr)

        # mint dai tokens & give approval
        self.tx_conf["to"] = dai_addr
        data = dai.functions.mint(Web3.toChecksumAddress(
            self.pub[0]), 100000).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, dai_addr, data,
                                    0)
        assert (result["outcomeStatus"] == 0)
        data = dai.functions.approve(dai_join_addr, 100000).buildTransaction(
            self.tx_conf)["data"]
        result = self.call_contract(self.pub[0], self.pri[0], dai_addr, data,
                                    0)
        assert (result["outcomeStatus"] == 0)
        data = dai.functions.allowance(Web3.toChecksumAddress(
            self.pub[0]), dai_join_addr).buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(dai_addr, data)
        assert_equal(int(result, 0), 100000)
        data = dai.functions.rely(dai_join_addr).buildTransaction(
            self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, dai_addr, data,
                                    0)
        assert (result["outcomeStatus"] == 0)

        # mint dai tokens for join_addr in vat & add approval
        self.tx_conf["to"] = vat_addr
        data = vat.functions.mint(
            dai_join_addr, 100000000000).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, vat_addr, data,
                                    0)
        assert (result["outcomeStatus"] == 0)
        data = vat.functions.hope(dai_join_addr).buildTransaction(
            self.tx_conf)["data"]
        result = self.call_contract(self.pub[0], self.pri[0], vat_addr, data,
                                    0)
        assert (result["outcomeStatus"] == 0)
        data = vat.functions.balanceOf(dai_join_addr).buildTransaction(
            self.tx_conf)["data"]
        result = self.rpc.call(vat_addr, data)
        assert_equal(int(result, 0), 100000000000)

        # join
        self.tx_conf["to"] = dai_join_addr
        data = dai_join.functions.join(Web3.toChecksumAddress(
            self.pub[0]), 50000).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.pub[0], self.pri[0], dai_join_addr,
                                    data, 0)
        assert (result["outcomeStatus"] == 0)

        # check
        self.tx_conf["to"] = dai_addr
        data = dai.functions.balanceOf(Web3.toChecksumAddress(
            self.pub[0])).buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(dai_addr, data)
        assert_equal(int(result, 0), 50000)

        self.tx_conf["to"] = vat_addr
        data = vat.functions.can(dai_join_addr,
                                 Web3.toChecksumAddress(
                                     self.pub[0])).buildTransaction(
                                         self.tx_conf)["data"]
        result = self.rpc.call(vat_addr, data)
        assert_equal(int(result, 0), 1)

        data = vat.functions.dai(Web3.toChecksumAddress(
            self.pub[0])).buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(vat_addr, data)
        assert_equal(int(result, 0), 50000000000000000000000000000000)

        # exit
        self.tx_conf["to"] = dai_join_addr
        data = dai_join.functions.exit(Web3.toChecksumAddress(
            self.pub[0]), 50000).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.pub[0], self.pri[0], dai_join_addr,
                                    data, 0)
        assert (result["outcomeStatus"] == 0)

        # check
        self.tx_conf["to"] = dai_addr
        data = dai.functions.balanceOf(Web3.toChecksumAddress(
            self.pub[0])).buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(dai_addr, data)
        assert_equal(int(result, 0), 100000)

        self.tx_conf["to"] = vat_addr
        data = vat.functions.can(dai_join_addr,
                                 Web3.toChecksumAddress(
                                     self.pub[0])).buildTransaction(
                                         self.tx_conf)["data"]
        result = self.rpc.call(vat_addr, data)
        assert_equal(int(result, 0), 0)

        data = vat.functions.dai(Web3.toChecksumAddress(
            self.pub[0])).buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(vat_addr, data)
        assert_equal(int(result, 0), 0)
Exemple #10
0
    def run_test(self):
        # Prevent easysolc from configuring the root logger to print to stderr
        self.log.propagate = False

        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        staking_contract = solc.get_contract_instance(
            abi_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_abi.json"),
            bytecode_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_bytecode.dat"),
        )

        start_p2p_connection(self.nodes)

        self.log.info("Initializing contract")
        genesis_key = default_config["GENESIS_PRI_KEY"]
        genesis_addr = privtoaddr(genesis_key)
        nonce = 0
        gas_price = 1
        gas = 50000000
        block_gen_thread = BlockGenThread(self.nodes, self.log)
        block_gen_thread.start()
        self.tx_conf = {
            "from": Web3.toChecksumAddress(encode_hex_0x(genesis_addr)),
            "nonce": int_to_hex(nonce),
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }

        # Setup balance for node 0
        node = self.nodes[0]
        client = RpcClient(node)
        (addr, priv_key) = client.rand_account()
        self.log.info("addr=%s priv_key=%s", addr, priv_key)
        tx = client.new_tx(value=5 * 10**18, receiver=addr, nonce=0)
        client.send_tx(tx)
        self.wait_for_tx([tx])
        assert_equal(node.cfx_getBalance(addr), hex(5000000000000000000))
        assert_equal(node.cfx_getBankBalance(addr), hex(0))

        self.tx_conf["to"] = Web3.toChecksumAddress(
            "443c409373ffd5c0bec1dddb7bec830856757b65")
        # deposit 10**18
        tx_data = decode_hex(
            staking_contract.functions.deposit(10**18).buildTransaction(
                self.tx_conf)["data"])
        tx = client.new_tx(value=0,
                           sender=addr,
                           receiver=self.tx_conf["to"],
                           nonce=0,
                           gas=gas,
                           data=tx_data,
                           priv_key=priv_key)
        client.send_tx(tx)
        self.wait_for_tx([tx])
        assert_equal(node.cfx_getBankBalance(addr), hex(10**18))

        # withdraw 5 * 10**17
        tx_data = decode_hex(
            staking_contract.functions.withdraw(5 * 10**17).buildTransaction(
                self.tx_conf)["data"])
        tx = client.new_tx(value=0,
                           sender=addr,
                           receiver=self.tx_conf["to"],
                           nonce=1,
                           gas=gas,
                           data=tx_data,
                           priv_key=priv_key)
        client.send_tx(tx)
        self.wait_for_tx([tx])
        assert_equal(node.cfx_getBankBalance(addr), hex(5 * 10**17))

        block_gen_thread.stop()
        block_gen_thread.join()
        sync_blocks(self.nodes)
        self.log.info("Pass")
    def run_test(self):
        self.log.propagate = False

        start_p2p_connection(self.nodes)
        block_gen_thread = BlockGenThread(self.nodes, self.log)
        block_gen_thread.start()

        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))

        self.log.info("Initializing contract")

        self.buggy_contract = solc.get_contract_instance(
            source=os.path.join(file_dir, "contracts/reentrancy.sol"),
            contract_name="Reentrance")
        self.exploit_contract = solc.get_contract_instance(
            source=os.path.join(file_dir, "contracts/reentrancy_exploit.sol"),
            contract_name="ReentranceExploit")

        user1, _ = ec_random_keys()
        user1_addr = privtoaddr(user1)
        user2, _ = ec_random_keys()
        user2_addr = privtoaddr(user2)
        # tx = create_transaction(
        #     pri_key=self.default_account_key,
        #     receiver=privtoaddr(buggy_contract_owner),
        #     value=1000000000000000000000000000000000,
        #     nonce=self.get_nonce(privtoaddr(self.default_account_key)),
        #     gas_price=ReentrancyTest.REQUEST_BASE['gas'])
        # self.send_transaction(tx, True, False)

        tx = create_transaction(pri_key=self.default_account_key,
                                receiver=user1_addr,
                                value=1000000000000000000000000000000000,
                                nonce=self.get_nonce(
                                    privtoaddr(self.default_account_key)),
                                gas_price=ReentrancyTest.REQUEST_BASE['gas'])
        self.send_transaction(tx, True, False)

        tx = create_transaction(pri_key=self.default_account_key,
                                receiver=user2_addr,
                                value=1000000000000000000000000000000000,
                                nonce=self.get_nonce(
                                    privtoaddr(self.default_account_key)),
                                gas_price=ReentrancyTest.REQUEST_BASE['gas'])
        self.send_transaction(tx, True, False)

        addr = eth_utils.encode_hex(user1_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_equal(balance, 1000000000000000000000000000000000)
        addr = eth_utils.encode_hex(user2_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_equal(balance, 1000000000000000000000000000000000)

        transaction = self.call_contract_function(self.buggy_contract,
                                                  "constructor", [],
                                                  self.default_account_key)
        contract_addr = self.wait_for_tx([transaction],
                                         True)[0]['contractCreated']

        transaction = self.call_contract_function(self.exploit_contract,
                                                  "constructor", [], user2)
        exploit_addr = self.wait_for_tx([transaction],
                                        True)[0]['contractCreated']

        transaction = self.call_contract_function(
            self.buggy_contract, "addBalance", [], user1,
            100000000000000000000000000000000, contract_addr, True, True)
        transaction = self.call_contract_function(
            self.exploit_contract, "deposit",
            [Web3.toChecksumAddress(contract_addr)], user2,
            100000000000000000000000000000000, exploit_addr, True, True)

        addr = eth_utils.encode_hex(user1_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_equal(balance, 899999999999999999999999950000000)
        addr = eth_utils.encode_hex(user2_addr)
        assert_equal(balance, 899999999999999999999999950000000)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(contract_addr))
        assert_equal(balance, 200000000000000000000000000000000)

        transaction = self.call_contract_function(self.exploit_contract,
                                                  "launch_attack", [], user2,
                                                  0, exploit_addr, True, True)
        transaction = self.call_contract_function(self.exploit_contract,
                                                  "get_money", [], user2, 0,
                                                  exploit_addr, True, True)

        addr = eth_utils.encode_hex(user1_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_equal(balance, 899999999999999999999999950000000)
        addr = eth_utils.encode_hex(user2_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_equal(balance, 1099999999999999999999999800000000)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(contract_addr))
        assert_equal(balance, 0)

        block_gen_thread.stop()
        block_gen_thread.join()
from solc import compile_standard, compile_source
import json
from easysolc import Solc
solc = Solc()


def compile_source_file(file_path):
    with open(file_path, 'r') as f:
        source = f.read()

    return compile_source(source)


class Contract:

    def __init__(self, web3):
        contract_interface = solc.compile("contract.sol")['Plasma']
        self._abi = contract_interface['abi']
        self._bytecode = contract_interface['bytecode']
        self._web3 = web3
        self._address = ""

    def get_byte_code(self):
        return self._bytecode

    def get_abi(self):
        return self._abi

    def get_address(self):
        return self._address
    def run_test(self):
        self.log.propagate = False

        start_p2p_connection(self.nodes)
        block_gen_thread = BlockGenThread(self.nodes, self.log)
        block_gen_thread.start()

        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))

        self.log.info("Initializing contract")

        self.buggy_contract = solc.get_contract_instance(
            source=os.path.join(file_dir, "contracts/reentrancy.sol"),
            contract_name="Reentrance")
        self.exploit_contract = solc.get_contract_instance(
            source=os.path.join(file_dir, "contracts/reentrancy_exploit.sol"),
            contract_name="ReentranceExploit")

        user1, _ = ec_random_keys()
        user1_addr = privtoaddr(user1)
        user2, _ = ec_random_keys()
        user2_addr = privtoaddr(user2)

        # setup balance
        value = (10**15 + 2000) * 10**18 + ReentrancyTest.REQUEST_BASE['gas']
        tx = create_transaction(pri_key=self.genesis_priv_key,
                                receiver=user1_addr,
                                value=value,
                                nonce=self.get_nonce(self.genesis_addr),
                                gas_price=ReentrancyTest.REQUEST_BASE['gas'])
        self.send_transaction(tx, True, False)

        tx = create_transaction(pri_key=self.genesis_priv_key,
                                receiver=user2_addr,
                                value=value,
                                nonce=self.get_nonce(self.genesis_addr),
                                gas_price=ReentrancyTest.REQUEST_BASE['gas'])
        self.send_transaction(tx, True, False)

        addr = eth_utils.encode_hex(user1_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_equal(balance, value)
        addr = eth_utils.encode_hex(user2_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_equal(balance, value)

        # lock balance in bank
        node = self.nodes[0]
        client = RpcClient(node)
        staking_contract = solc.get_contract_instance(
            abi_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_abi.json"),
            bytecode_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_bytecode.dat"),
        )
        staking_contract_addr = Web3.toChecksumAddress(
            "443c409373ffd5c0bec1dddb7bec830856757b65")
        tx_conf = copy.deepcopy(ReentrancyTest.REQUEST_BASE)
        tx_conf['to'] = staking_contract_addr
        tx_data = decode_hex(
            staking_contract.functions.deposit(
                2000 * 10**18).buildTransaction(tx_conf)["data"])
        tx1 = client.new_tx(value=0,
                            sender=eth_utils.encode_hex(user1_addr),
                            receiver=staking_contract_addr,
                            nonce=self.get_nonce(user1_addr),
                            data=tx_data,
                            gas=ReentrancyTest.REQUEST_BASE['gas'],
                            gas_price=ReentrancyTest.REQUEST_BASE['gasPrice'],
                            priv_key=eth_utils.encode_hex(user1))
        tx2 = client.new_tx(value=0,
                            sender=eth_utils.encode_hex(user2_addr),
                            receiver=staking_contract_addr,
                            nonce=self.get_nonce(user2_addr),
                            data=tx_data,
                            gas=ReentrancyTest.REQUEST_BASE['gas'],
                            gas_price=ReentrancyTest.REQUEST_BASE['gasPrice'],
                            priv_key=eth_utils.encode_hex(user2))
        client.send_tx(tx1)
        client.send_tx(tx2)
        self.wait_for_tx([tx1, tx2], False)

        transaction = self.call_contract_function(self.buggy_contract,
                                                  "constructor", [],
                                                  self.genesis_priv_key)
        contract_addr = self.wait_for_tx([transaction],
                                         True)[0]['contractCreated']

        transaction = self.call_contract_function(self.exploit_contract,
                                                  "constructor", [], user2)
        exploit_addr = self.wait_for_tx([transaction],
                                        True)[0]['contractCreated']

        transaction = self.call_contract_function(
            self.buggy_contract, "addBalance", [], user1,
            100000000000000000000000000000000, contract_addr, True, True)
        transaction = self.call_contract_function(
            self.exploit_contract, "deposit",
            [Web3.toChecksumAddress(contract_addr)], user2,
            100000000000000000000000000000000, exploit_addr, True, True)

        addr = eth_utils.encode_hex(user1_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_greater_than_or_equal(balance,
                                     899999999999999999999999950000000)
        addr = eth_utils.encode_hex(user2_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_greater_than_or_equal(balance,
                                     899999999999999999999999900000000)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(contract_addr))
        assert_equal(balance, 200000000000000000000000000000000)

        transaction = self.call_contract_function(self.exploit_contract,
                                                  "launch_attack", [], user2,
                                                  0, exploit_addr, True, True)
        transaction = self.call_contract_function(self.exploit_contract,
                                                  "get_money", [], user2, 0,
                                                  exploit_addr, True, True)

        addr = eth_utils.encode_hex(user1_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_greater_than_or_equal(balance,
                                     899999999999999999999999950000000)
        addr = eth_utils.encode_hex(user2_addr)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(addr))
        assert_greater_than_or_equal(balance,
                                     1099999999999999999999999800000000)
        balance = parse_as_int(self.nodes[0].cfx_getBalance(contract_addr))
        assert_equal(balance, 0)

        block_gen_thread.stop()
        block_gen_thread.join()
    def run_test(self):
        time.sleep(7)
        priv_key = default_config["GENESIS_PRI_KEY"]
        sender = eth_utils.encode_hex(privtoaddr(priv_key))

        self.rpc = RpcClient(self.nodes[0])

        # lock tokens in bank
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        staking_contract = solc.get_contract_instance(
            abi_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_abi.json"),
            bytecode_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_bytecode.dat"),
        )

        gas_price = 1
        gas = 50000000
        self.tx_conf = {
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }
        staking_contract_addr = Web3.toChecksumAddress(
            "443c409373ffd5c0bec1dddb7bec830856757b65")
        self.tx_conf["to"] = staking_contract_addr
        tx_data = eth_utils.decode_hex(
            staking_contract.functions.deposit(
                10000 * 10**18).buildTransaction(self.tx_conf)["data"])
        genesis_key = default_config["GENESIS_PRI_KEY"]
        genesis_addr = privtoaddr(genesis_key)
        tx = self.rpc.new_tx(value=0,
                             receiver=staking_contract_addr,
                             nonce=0,
                             data=tx_data,
                             gas=gas,
                             gas_price=gas_price)
        self.rpc.send_tx(tx, True)

        # apply filter, we expect no logs
        filter = Filter(from_epoch="earliest", to_epoch="latest_mined")
        result = self.rpc.get_logs(filter)
        assert_equal(result, [])

        # deploy contract
        bytecode_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), CONTRACT_PATH)
        assert (os.path.isfile(bytecode_file))
        bytecode = open(bytecode_file).read()
        _, contractAddr = self.deploy_contract(sender, priv_key, bytecode)

        # apply filter, we expect a single log with 2 topics
        filter = Filter(from_epoch="earliest", to_epoch="latest_mined")
        logs0 = self.rpc.get_logs(filter)

        self.assert_response_format_correct(logs0)
        assert_equal(len(logs0), 1)

        assert_equal(len(logs0[0]["topics"]), 2)
        assert_equal(logs0[0]["topics"][0], CONSTRUCTED_TOPIC)
        assert_equal(logs0[0]["topics"][1], self.address_to_topic(sender))
        assert_equal(logs0[0]["data"], self.address_to_topic(sender))

        # call method
        receipt = self.call_contract(sender, priv_key, contractAddr,
                                     encode_hex_0x(keccak(b"foo()")))

        # apply filter, we expect two logs with 2 and 3 topics respectively
        filter = Filter(from_epoch="earliest", to_epoch="latest_mined")
        logs1 = self.rpc.get_logs(filter)

        self.assert_response_format_correct(logs1)
        assert_equal(len(logs1), 2)
        assert_equal(logs1[0], logs0[0])

        assert_equal(len(logs1[1]["topics"]), 3)
        assert_equal(logs1[1]["topics"][0], CALLED_TOPIC)
        assert_equal(logs1[1]["topics"][1], self.address_to_topic(sender))
        assert_equal(logs1[1]["topics"][2], self.number_to_topic(1))

        # apply filter for specific block, we expect a single log with 3 topics
        filter = Filter(block_hashes=[receipt["blockHash"]])
        logs = self.rpc.get_logs(filter)

        self.assert_response_format_correct(logs)
        assert_equal(len(logs), 1)
        assert_equal(logs[0], logs1[1])

        # call many times
        for ii in range(0, NUM_CALLS - 2):
            self.call_contract(sender, priv_key, contractAddr,
                               encode_hex_0x(keccak(b"foo()")))

        # apply filter, we expect NUM_CALLS log entries with inreasing uint32 fields
        filter = Filter(from_epoch="earliest", to_epoch="latest_mined")
        logs = self.rpc.get_logs(filter)

        self.assert_response_format_correct(logs)
        assert_equal(len(logs), NUM_CALLS)

        for ii in range(2, NUM_CALLS):
            assert_equal(len(logs[ii]["topics"]), 3)
            assert_equal(logs[ii]["topics"][0], CALLED_TOPIC)
            assert (logs[ii]["topics"][1] == self.address_to_topic(sender))
            assert_equal(logs[ii]["topics"][2], self.number_to_topic(ii))

        # apply filter for specific topics
        filter = Filter(topics=[CONSTRUCTED_TOPIC])
        logs = self.rpc.get_logs(filter)
        self.assert_response_format_correct(logs)
        assert_equal(len(logs), 1)

        filter = Filter(topics=[CALLED_TOPIC])
        logs = self.rpc.get_logs(filter)
        self.assert_response_format_correct(logs)
        assert_equal(len(logs), NUM_CALLS - 1)

        filter = Filter(topics=[None, self.address_to_topic(sender)])
        logs = self.rpc.get_logs(filter)
        self.assert_response_format_correct(logs)
        assert_equal(len(logs), NUM_CALLS)

        # find logs with `CALLED_TOPIC` as 1st topic and `3` or `4` as 3rd topic
        filter = Filter(topics=[
            CALLED_TOPIC, None,
            [self.number_to_topic(3),
             self.number_to_topic(4)]
        ])
        logs = self.rpc.get_logs(filter)
        self.assert_response_format_correct(logs)
        assert_equal(len(logs), 2)

        # apply filter with limit
        filter = Filter(limit=("0x%x" % (NUM_CALLS // 2)))
        logs = self.rpc.get_logs(filter)

        self.assert_response_format_correct(logs)
        assert_equal(len(logs), NUM_CALLS // 2)

        # apply filter for specific contract address
        _, contractAddr2 = self.deploy_contract(sender, priv_key, bytecode)

        filter = Filter(address=[contractAddr])
        logs = self.rpc.get_logs(filter)
        self.assert_response_format_correct(logs)
        assert_equal(len(logs), NUM_CALLS)

        filter = Filter(address=[contractAddr2])
        logs = self.rpc.get_logs(filter)
        self.assert_response_format_correct(logs)
        assert_equal(len(logs), 1)

        # apply filter to very first epoch, we expect no logs
        filter = Filter(from_epoch="0x0", to_epoch="0x0")
        result = self.rpc.get_logs(filter)
        assert_equal(result, [])

        self.log.info("Pass")
Exemple #15
0
    def run_test(self):
        # Prevent easysolc from configuring the root logger to print to stderr
        self.log.propagate = False

        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        staking_contract = solc.get_contract_instance(
            abi_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_abi.json"),
            bytecode_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_bytecode.dat"),
        )

        commission_privilege_contract = solc.get_contract_instance(
            abi_file=os.path.join(
                file_dir, "contracts/commission_privilege_control_abi.json"),
            bytecode_file=os.path.join(
                file_dir,
                "contracts/commission_privilege_control_bytecode.dat"),
        )

        start_p2p_connection(self.nodes)

        self.log.info("Initializing contract")
        genesis_key = self.genesis_priv_key
        genesis_addr = self.genesis_addr
        self.log.info("genesis_addr={}".format(encode_hex_0x(genesis_addr)))
        nonce = 0
        gas_price = 1
        gas = 50000000
        block_gen_thread = BlockGenThread(self.nodes, self.log)
        block_gen_thread.start()
        self.tx_conf = {
            "from": Web3.toChecksumAddress(encode_hex_0x(genesis_addr)),
            "nonce": int_to_hex(nonce),
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }

        # Setup balance for node 0
        node = self.nodes[0]
        client = RpcClient(node)
        (addr, priv_key) = client.rand_account()
        self.log.info("addr=%s priv_key=%s", addr, priv_key)
        tx = client.new_tx(value=5 * 10**18,
                           receiver=addr,
                           nonce=self.get_nonce(genesis_addr))
        client.send_tx(tx, True)
        assert_equal(node.cfx_getBalance(addr), hex(5000000000000000000))
        assert_equal(node.cfx_getBankBalance(addr), hex(0))

        self.tx_conf["to"] = Web3.toChecksumAddress(
            "443c409373ffd5c0bec1dddb7bec830856757b65")
        # deposit 2 * 10**18 / 16
        tx_data = decode_hex(
            staking_contract.functions.deposit(
                2 * 10**18 // 16).buildTransaction(self.tx_conf)["data"])
        tx = client.new_tx(value=0,
                           receiver=self.tx_conf["to"],
                           nonce=self.get_nonce(genesis_addr),
                           gas=gas,
                           data=tx_data)
        client.send_tx(tx, True)
        assert_equal(node.cfx_getBankBalance(encode_hex(genesis_addr)),
                     hex(2 * 10**18 // 16))

        # setup contract
        transaction = self.call_contract_function(
            contract=commission_privilege_contract,
            name="constructor",
            args=[],
            sender_key=self.genesis_priv_key)
        contract_addr = self.wait_for_tx([transaction],
                                         True)[0]['contractCreated']
        self.log.info("contract_addr={}".format(contract_addr))
        assert_equal(node.cfx_getBalance(contract_addr), hex(0))

        # setup balance
        transaction = self.call_contract_function(
            contract=commission_privilege_contract,
            name="set",
            args=[],
            sender_key=genesis_key,
            contract_addr=contract_addr,
            value=10**18,
            wait=True,
            check_status=True)
        assert_equal(node.cfx_getBalance(contract_addr), hex(10**18))

        # call contract with privilege
        geneis_balance = node.cfx_getBalance(encode_hex(genesis_addr))
        transaction = self.call_contract_function(
            contract=commission_privilege_contract,
            name="foo",
            args=[],
            sender_key=genesis_key,
            contract_addr=contract_addr,
            wait=True,
            check_status=True)
        assert_equal(node.cfx_getBalance(contract_addr), hex(10**18 - gas))
        assert_equal(node.cfx_getBalance(encode_hex(genesis_addr)),
                     geneis_balance)

        # call contract without privilege and remove privilege of genesis
        transaction = self.call_contract_function(
            contract=commission_privilege_contract,
            name="remove",
            args=[],
            sender_key=priv_key,
            contract_addr=contract_addr,
            wait=True,
            check_status=True)
        assert_equal(node.cfx_getBalance(contract_addr), hex(10**18 - gas))
        assert_equal(node.cfx_getBalance(addr), hex(5 * 10**18 - gas))

        # call contract after removing privilege
        geneis_balance = int(node.cfx_getBalance(encode_hex(genesis_addr)), 16)
        transaction = self.call_contract_function(
            contract=commission_privilege_contract,
            name="foo",
            args=[],
            sender_key=genesis_key,
            contract_addr=contract_addr,
            wait=True,
            check_status=True)
        assert_equal(node.cfx_getBalance(contract_addr), hex(10**18 - gas))

        self.log.info("Pass")
Exemple #16
0
    def testHTLCContract(self):
        CONTRACT_PATH = "contracts/htlc_bytecode_new.dat"
        logs = self.rpc.get_logs(self.filter)
        l = len(logs)

        # construct contract object
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        contract = solc.get_contract_instance(
            abi_file=os.path.join(file_dir, "contracts/htlc_abi_new.json"),
            bytecode_file=os.path.join(file_dir, CONTRACT_PATH),
        )

        # deploy contract
        data = contract.constructor().buildTransaction(self.tx_conf)["data"]
        receipt, contractAddr = self.deploy_contract(self.sender,
                                                     self.priv_key, data)
        tx_hash = receipt['transactionHash']
        contractAddr = Web3.toChecksumAddress(contractAddr)
        self.tx_conf["to"] = contractAddr
        logs = self.rpc.get_logs(self.filter)
        assert_equal(len(logs), l + 1)
        assert_equal(logs[-1]["topics"][1], self.address_to_topic(self.sender))
        assert_equal(logs[-1]["topics"][2], self.number_to_topic(16))

        # call getNow()
        data = contract.functions.getNow().buildTransaction(
            self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert (int(result, 0) - int(time.time()) < 5)

        b0 = self.rpc.get_balance(self.sender)
        fee = 10000000
        # interact with newContract(), sender send conflux to himself
        time_lock = int(time.time()) + 7200
        data = contract.functions.newContract(
            self.sender_checksum, self.problem,
            time_lock).buildTransaction(self.tx_conf)["data"]
        cost = 5000000000000000000
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data, cost)
        logs = self.rpc.get_logs(self.filter)
        assert_equal(len(logs), l + 2)
        assert_equal(self.rpc.get_balance(contractAddr), cost)
        assert_greater_than_or_equal(self.rpc.get_balance(self.sender),
                                     b0 - cost - fee)
        contract_id = logs[-1]["topics"][1]

        # call getContract
        cid0 = contract_id
        data = contract.functions.getContract(contract_id).buildTransaction(
            self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        result = result[2:]
        res = ['0x' + result[i * 64:(i + 1) * 64] for i in range(8)]
        assert_equal(res[0][-20:], self.sender[-20:])
        assert_equal(res[1][-20:], self.sender[-20:])
        assert_equal(int(res[2], 0), cost)
        assert_equal(res[3], self.problem)
        assert_equal(int(res[4], 0), time_lock)
        assert_equal(int(res[5], 0), 0)
        assert_equal(int(res[6], 0), 0)
        assert_equal(int(res[7], 0), 0)

        # interact with withdraw()
        data = contract.functions.withdraw(
            contract_id, self.solution).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data)
        assert_equal(self.rpc.get_balance(contractAddr), 0)
        assert_greater_than_or_equal(self.rpc.get_balance(self.sender),
                                     b0 - fee * 2)
        logs = self.rpc.get_logs(self.filter)
        assert_equal(len(logs), l + 3)

        # call getContract
        data = contract.functions.getContract(contract_id).buildTransaction(
            self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        result = result[2:]
        res = ['0x' + result[i * 64:(i + 1) * 64] for i in range(8)]
        assert_equal(res[0][-20:], self.sender[-20:])
        assert_equal(res[1][-20:], self.sender[-20:])
        assert_equal(int(res[2], 0), cost)
        assert_equal(res[3], self.problem)
        assert_equal(int(res[4], 0), time_lock)
        assert_equal(int(res[5], 0), 1)
        assert_equal(int(res[6], 0), 0)
        assert_equal(res[7], self.solution)
        receipt = self.rpc.get_transaction_receipt(tx_hash)
Exemple #17
0
    def run_test(self):
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        staking_contract = solc.get_contract_instance(
            abi_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_abi.json"),
            bytecode_file=os.path.join(
                file_dir, "contracts/storage_interest_staking_bytecode.dat"),
        )
        staking_contract_addr = Web3.toChecksumAddress(
            "443c409373ffd5c0bec1dddb7bec830856757b65")

        self.problem = "0x2bc79b7514884ab00da924607d71542cc4fed3beb8518e747726ae30ab6c7944"
        self.solution = "0xc4d2751c52311d0d7efe44e5c4195e058ad5ef4bb89b3e1761b24dc277b132c2"
        self.priv_key = default_config["GENESIS_PRI_KEY"]
        self.sender = encode_hex_0x(privtoaddr(self.priv_key))
        self.sender_checksum = Web3.toChecksumAddress(self.sender)
        self.pub = []
        self.pri = []
        self.rpc = RpcClient(self.nodes[0])
        gas = 50000000
        gas_price = 10

        # lock token for genesis account
        self.tx_conf = {
            "from": self.sender,
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }
        self.tx_conf['to'] = staking_contract_addr
        tx_data = decode_hex(
            staking_contract.functions.deposit(
                1000000 * 10**18).buildTransaction(self.tx_conf)["data"])
        tx = self.rpc.new_tx(value=0,
                             receiver=staking_contract_addr,
                             data=tx_data,
                             gas=gas,
                             gas_price=gas_price)
        self.rpc.send_tx(tx, True)

        for i in range(10):
            priv_key = random.randint(0, 2**256).to_bytes(32, "big")
            pub_key = encode_hex_0x(privtoaddr(priv_key))
            self.pub.append(pub_key)
            self.pri.append(priv_key)
            transaction = self.rpc.new_tx(sender=self.sender,
                                          receiver=pub_key,
                                          value=1000000 * 10**18,
                                          priv_key=self.priv_key)
            self.rpc.send_tx(transaction, True)
            # deposit 10000 tokens
            tx_data = decode_hex(
                staking_contract.functions.deposit(
                    10000 * 10**18).buildTransaction(self.tx_conf)["data"])
            tx = self.rpc.new_tx(value=0,
                                 sender=pub_key,
                                 receiver=self.tx_conf["to"],
                                 gas=gas,
                                 data=tx_data,
                                 priv_key=priv_key)
            self.rpc.send_tx(tx)
        self.tx_conf = {
            "from": self.sender,
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }
        self.filter = Filter(from_epoch="earliest", to_epoch="latest_mined")
        self.testEventContract()
        self.tx_conf = {
            "from": self.sender,
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }
        self.testBallotContract()
        self.tx_conf = {
            "from": self.sender,
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }
        self.testPayContract()
        self.tx_conf = {
            "from": self.sender,
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }
        self.testHTLCContract()
        self.tx_conf = {
            "from": self.sender,
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }
        self.testDaiContract()
        self.tx_conf = {
            "from": self.sender,
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }
        self.testMappingContract()
        self.tx_conf = {
            "from": self.sender,
            "gas": int_to_hex(gas),
            "gasPrice": int_to_hex(gas_price),
            "chainId": 0
        }
        self.testDaiJoinContract()
        self.log.info("Pass")
Exemple #18
0
import sys
import grpc
from web3 import Web3, HTTPProvider
from easysolc import Solc
import traceback
import random
import tc_pb2
import tc_pb2_grpc

logging.basicConfig(
    format=
    '%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)-4d] %(message)s',
    datefmt='%d-%m-%Y:%H:%M:%S',
    level=logging.INFO)
logger = logging.getLogger(__name__)
solc = Solc('..')


class TCMonitor:
    ETH_RPC_ADDRESS = 'http://localhost:8000'
    TC_CORE_RPC_URL = "localhost:8123"
    # (DCMMC) TC 合约发出的 RequestInfo 信号的 Keccak-256 hash
    # RequestInfo(uint64,uint8,address,uint256,address,bytes32,uint256,bytes32[])
    # 这个可以直接用 truffle develop 交互式界面输入 tc 的 instance 名称,然后找到这个 event,
    # 下面就有它的 hash
    TC_REQUEST_TOPIC = "0x295780ea261767c398d062898e5648587d7b8ca371ffd203be8b4f9a43454ffa"
    SIM_NET = 'sim'
    NUM_OF_RETRY_ON_NETWORK_ERROR = 10

    def __init__(self, config):
        assert config.TC_CONTRACT_BLOCK_NUM >= 0
Exemple #19
0
    def testDaiContract(self):
        CONTRACT_PATH = "contracts/Dai_bytecode.dat"
        logs = self.rpc.get_logs(self.filter)
        l = len(logs)

        # construct contract object
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        contract = solc.get_contract_instance(
            abi_file=os.path.join(file_dir, "contracts/Dai_abi.json"),
            bytecode_file=os.path.join(file_dir, CONTRACT_PATH),
        )

        # deploy contract
        data = contract.constructor(1).buildTransaction(self.tx_conf)["data"]
        receipt, contractAddr = self.deploy_contract(self.sender,
                                                     self.priv_key, data)
        tx_hash = receipt['transactionHash']
        contractAddr = Web3.toChecksumAddress(contractAddr)
        self.tx_conf["to"] = contractAddr

        # rely [0,5)
        for i in range(5):
            data = contract.functions.rely(Web3.toChecksumAddress(
                self.pub[i])).buildTransaction(self.tx_conf)["data"]
            result = self.call_contract(self.sender, self.priv_key,
                                        contractAddr, data, 0)
            assert_equal(result["outcomeStatus"], 0)

        # deny 1, 3
        for i in range(5):
            if (i % 2 == 1):
                data = contract.functions.deny(
                    Web3.toChecksumAddress(self.pub[i])).buildTransaction(
                        self.tx_conf)["data"]
                result = self.call_contract(self.pub[i - 1], self.pri[i - 1],
                                            contractAddr, data, 0)
                assert_equal(result["outcomeStatus"], 0)

        # check wards
        for i in range(5):
            data = contract.functions.wards(Web3.toChecksumAddress(
                self.pub[i])).buildTransaction(self.tx_conf)["data"]
            result = self.rpc.call(contractAddr, data)
            assert_equal(int(result, 0), int(i % 2 == 0))

        # mint tokens
        data = contract.functions.mint(Web3.toChecksumAddress(
            self.pub[0]), 100000).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data, 0)
        logs = self.rpc.get_logs(self.filter)

        # check balance
        data = contract.functions.balanceOf(Web3.toChecksumAddress(
            self.pub[0])).buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert (int(result, 0) == 100000)

        # approve
        data = contract.functions.approve(
            self.sender_checksum, 50000).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.pub[0], self.pri[0], contractAddr,
                                    data)
        logs = self.rpc.get_logs(self.filter)

        # check allowance
        data = contract.functions.allowance(
            Web3.toChecksumAddress(self.pub[0]),
            self.sender_checksum).buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert (int(result, 0) == 50000)

        # insufficient balance
        data = contract.functions.transfer(self.sender_checksum,
                                           200000).buildTransaction(
                                               self.tx_conf)["data"]
        result = self.call_contract(self.pub[0], self.pri[0], contractAddr,
                                    data)
        assert (result["outcomeStatus"] != 0)

        # insuffcient allowance
        data = contract.functions.transferFrom(
            Web3.toChecksumAddress(self.pub[0]), self.sender_checksum,
            10000).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.pub[1], self.pri[1], contractAddr,
                                    data)
        assert (result["outcomeStatus"] != 0)

        # transfer 50000 use allowance
        data = contract.functions.transferFrom(
            Web3.toChecksumAddress(self.pub[0]),
            Web3.toChecksumAddress(self.pub[1]),
            50000).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data)
        assert (result["outcomeStatus"] == 0)

        # get digest and sign it
        ts = int(time.time()) + 7200
        data = contract.functions.getHash(Web3.toChecksumAddress(self.pub[0]),
                                          Web3.toChecksumAddress(self.pub[1]),
                                          0, ts, True).buildTransaction(
                                              self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        v, r, s = ecsign(bytes.fromhex(result[2:]), self.pri[0])
        r = self.fixto64(hex(r))
        s = self.fixto64(hex(s))
        assert (len(r) == 66)
        assert (len(s) == 66)

        # premit
        data = contract.functions.permit(
            Web3.toChecksumAddress(self.pub[0]),
            Web3.toChecksumAddress(self.pub[1]), 0, ts, True, v, r,
            s).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.pub[5], self.pri[5], contractAddr,
                                    data)
        assert (result["outcomeStatus"] == 0)

        # check allowance
        data = contract.functions.allowance(
            Web3.toChecksumAddress(self.pub[0]),
            self.sender_checksum).buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert (int(result, 0) == 0)
        data = contract.functions.allowance(
            Web3.toChecksumAddress(self.pub[0]),
            Web3.toChecksumAddress(self.pub[1])).buildTransaction(
                self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert (
            result ==
            '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'
        )

        # burn pub[0]
        data = contract.functions.burn(Web3.toChecksumAddress(
            self.pub[0]), 50000).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.pub[1], self.pri[1], contractAddr,
                                    data)
        assert (result["outcomeStatus"] == 0)

        # check balance
        data = contract.functions.balanceOf(Web3.toChecksumAddress(
            self.pub[0])).buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert (int(result, 0) == 0)
        data = contract.functions.balanceOf(Web3.toChecksumAddress(
            self.pub[1])).buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert (int(result, 0) == 50000)
        data = contract.functions.totalSupply().buildTransaction(
            self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert (int(result, 0) == 50000)
Exemple #20
0
    def testEventContract(self):
        CONTRACT_PATH = "contracts/event_bytecode_new.dat"
        logs = self.rpc.get_logs(self.filter)
        l = len(logs)
        # deploy contract
        bytecode_file = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), CONTRACT_PATH)
        assert (os.path.isfile(bytecode_file))
        bytecode = open(bytecode_file).read().strip()
        receipt, contractAddr = self.deploy_contract(self.sender,
                                                     self.priv_key, bytecode)
        contractAddr = Web3.toChecksumAddress(contractAddr)
        logs = self.rpc.get_logs(self.filter)
        assert_equal(len(logs), l + 1)

        # construct contract object
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        contract = solc.get_contract_instance(
            abi_file=os.path.join(file_dir, "contracts/event_abi_new.json"),
            bytecode_file=os.path.join(file_dir, CONTRACT_PATH),
        )
        self.tx_conf["to"] = contractAddr

        # interact with foo()
        data = contract.functions.foo().buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data)
        logs = self.rpc.get_logs(self.filter)
        assert_equal(len(logs), l + 2)
        assert_equal(logs[-1]["topics"][1], self.address_to_topic(self.sender))
        assert_equal(logs[-1]["topics"][2], self.number_to_topic(1))

        # interact with goo(10), will pass modifier, emit new event
        data = contract.functions.goo(10).buildTransaction(
            self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data)
        logs = self.rpc.get_logs(self.filter)
        assert_equal(len(logs), l + 3)
        assert_equal(logs[-1]["topics"][1], self.address_to_topic(self.sender))
        assert_equal(logs[-1]["topics"][2], self.number_to_topic(11))

        # interact with goo(10), will not pass modifier, no event emitted
        data = contract.functions.goo(10).buildTransaction(
            self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data)
        logs = self.rpc.get_logs(self.filter)
        assert_equal(len(logs), l + 3)

        # call const function hoo()
        data = contract.functions.hoo().buildTransaction(self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert_equal(result, self.number_to_topic(11))

        # call const function byte32oo(solution)
        data = contract.functions.byte32oo(self.solution).buildTransaction(
            self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert_equal(result, self.solution)

        # call const function getSha256(solution)
        data = contract.functions.getSha256(self.solution).buildTransaction(
            self.tx_conf)["data"]
        result = self.rpc.call(contractAddr, data)
        assert_equal(result, self.problem)
Exemple #21
0
    def testMappingContract(self):
        CONTRACT_PATH = "contracts/mapping_bytecode.dat"
        logs = self.rpc.get_logs(self.filter)
        l = len(logs)

        # construct contract object
        solc = Solc()
        file_dir = os.path.dirname(os.path.realpath(__file__))
        contract = solc.get_contract_instance(
            abi_file=os.path.join(file_dir, "contracts/mapping_abi.json"),
            bytecode_file=os.path.join(file_dir, CONTRACT_PATH),
        )

        # deploy contract
        data = contract.constructor(1).buildTransaction(self.tx_conf)["data"]
        receipt, contractAddr = self.deploy_contract(self.sender,
                                                     self.priv_key, data)
        tx_hash = receipt['transactionHash']
        contractAddr = Web3.toChecksumAddress(contractAddr)
        self.tx_conf["to"] = contractAddr

        c = "0x81f3521d71990945b99e1c592750d7157f2b545f"

        def check_wards(x, y, z):
            data = contract.functions.wards(Web3.toChecksumAddress(
                self.pub[0])).buildTransaction(self.tx_conf)["data"]
            result = self.rpc.call(contractAddr, data)
            A = int(result, 0)
            assert (A == x)
            data = contract.functions.wards(
                self.sender_checksum).buildTransaction(self.tx_conf)["data"]
            result = self.rpc.call(contractAddr, data)
            B = int(result, 0)
            assert (B == y)
            data = contract.functions.wards(
                Web3.toChecksumAddress(c)).buildTransaction(
                    self.tx_conf)["data"]
            result = self.rpc.call(contractAddr, data)
            C = int(result, 0)
            assert (C == z)

        # deny pub[0]
        check_wards(0, 2, 0)
        data = contract.functions.set1(
            Web3.toChecksumAddress(c)).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data)
        check_wards(0, 2, 1)
        data = contract.functions.set2(Web3.toChecksumAddress(
            self.pub[0])).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data)
        check_wards(2, 2, 1)
        data = contract.functions.set0(
            Web3.toChecksumAddress(c)).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data)
        check_wards(2, 2, 0)
        data = contract.functions.set0(Web3.toChecksumAddress(
            self.pub[0])).buildTransaction(self.tx_conf)["data"]
        result = self.call_contract(self.sender, self.priv_key, contractAddr,
                                    data)
        check_wards(0, 2, 0)