示例#1
0
文件: client.py 项目: ahuachen/raiden
    def __init__(self, host_port, privkey, address, registry_address):
        """
        Args:
            host_port (Tuple[(str, int)]): two-tuple with the (address, host)
                of the JSON-RPC server.
        """
        channel_manager_abi = get_abi_from_file(get_contract_path('channelManagerContract.sol'))
        netting_contract_abi = get_abi_from_file(get_contract_path('nettingChannelContract.sol'))
        registry_abi = get_abi_from_file(get_contract_path('registry.sol'))

        jsonrpc_client = JSONRPCClient(
            sender=address,
            privkey=privkey,
        )

        registry_proxy = jsonrpc_client.new_abi_contract(registry_abi, registry_address)

        self.asset_managerproxy = dict()
        self.contract_by_address = dict()

        self.host_port = host_port
        self.privkey = privkey
        self.client = jsonrpc_client

        self.registry_address = registry_address
        self.registry_proxy = registry_proxy

        self.channel_manager_abi = channel_manager_abi
        self.netting_contract_abi = netting_contract_abi
        self.registry_abi = registry_abi

        if not self._code_exists(registry_address):
            raise ValueError('Registry {} does not exists'.format(registry_address))
示例#2
0
    def __init__(self, host_port, privkey, address, registry_address):
        """
        Args:
            host_port (Tuple[(str, int)]): two-tuple with the (address, host)
                of the JSON-RPC server.
        """
        channel_manager_abi = get_abi_from_file(
            get_contract_path('channelManagerContract.sol'))
        netting_contract_abi = get_abi_from_file(
            get_contract_path('nettingChannelContract.sol'))
        registry_abi = get_abi_from_file(get_contract_path('registry.sol'))

        jsonrpc_client = JSONRPCClient(
            sender=address,
            privkey=privkey,
        )

        registry_proxy = jsonrpc_client.new_abi_contract(
            registry_abi, registry_address)

        self.asset_managerproxy = dict()
        self.contract_by_address = dict()

        self.host_port = host_port
        self.privkey = privkey
        self.client = jsonrpc_client

        self.registry_address = registry_address
        self.registry_proxy = registry_proxy

        self.channel_manager_abi = channel_manager_abi
        self.netting_contract_abi = netting_contract_abi
        self.registry_abi = registry_abi

        if not self._code_exists(registry_address):
            raise ValueError(
                'Registry {} does not exists'.format(registry_address))
示例#3
0
class TestDriverThread(Thread):
    def __init__(self,
                 group=None,
                 target=None,
                 name=None,
                 args=(),
                 kwargs=None,
                 verbose=None,
                 gasprice=None,
                 evt=None,
                 port=4000):
        super(TestDriverThread, self).__init__(group, target, name, args,
                                               kwargs, verbose)
        self.gasprice = gasprice
        self.log = slogging.getLogger('test_working_app')
        self.test_successful = False
        self.finished = False
        self.evt = evt
        self.port = port

    def wait_for_blocknumber(self, number, retry=20):
        block = self.client.call('eth_getBlockByNumber', hex(number), False)
        while block is None and retry > 0:
            block = self.client.call('eth_getBlockByNumber', hex(number),
                                     False)
            time.sleep(.5)
            retry -= 1
        assert retry > 0, "could not find block {}".format(number)
        return block

    def connect_client(self):
        while True:
            try:
                self.client = JSONRPCClient(port=self.port,
                                            print_communication=False)
                self.client.call('web3_clientVersion')
                break
            except ConnectionError:
                time.sleep(0.5)

    def run(self):
        self.log.debug('test started')

        try:
            self.connect_client()
            self.log.debug('client connected')

            # Read initial blocks created by HydraChain on startup
            self.wait_for_blocknumber(10)
            self.log.debug("found block number 10")

            # Create a contract
            params = {
                'from': self.client.coinbase.encode('hex'),
                'to': '',
                'data': contract_code,
                'gasPrice': '0x{}'.format(self.gasprice)
            }
            self.client.call('eth_sendTransaction', params)
            self.log.debug('eth_sendTransaction OK')

            # Wait for new block
            recent_block = self.wait_for_blocknumber(11)

            self.log.debug('recent_block_hash {}'.format(recent_block))

            block = self.client.call('eth_getBlockByHash',
                                     recent_block['hash'], True)
            self.log.debug('eth_getBlockByHash OK {}'.format(block))

            assert block['transactions'], 'no transactions in block'
            tx = block['transactions'][0]
            assert tx['to'] == '0x'
            assert tx['gasPrice'] == params['gasPrice']
            assert len(tx['input']) > len('0x')
            assert tx['input'].startswith('0x')

            # Get transaction receipt to have the address of contract
            receipt = self.client.call('eth_getTransactionReceipt', tx['hash'])
            self.log.debug('eth_getTransactionReceipt OK {}'.format(receipt))

            assert receipt['transactionHash'] == tx['hash']
            assert receipt['blockHash'] == tx['blockHash']
            assert receipt['blockHash'] == block['hash']

            # Get contract address from receipt
            contract_address = receipt['contractAddress']
            code = self.client.call('eth_getCode', contract_address)
            self.log.debug('eth_getCode OK {}'.format(code))

            assert code.startswith('0x')
            assert len(code) > len('0x')

            # Perform some action on contract (set value to random number)
            rand_value = random.randint(64, 1024)
            contract = self.client.new_abi_contract(contract_interface,
                                                    contract_address)
            contract.set(rand_value, gasprice=self.gasprice)
            self.log.debug('contract.set({}) OK'.format(rand_value))

            # Wait for new block
            recent_block = self.wait_for_blocknumber(12)
            # recent_block_hash = self.wait_for_new_block()

            block = self.client.call('eth_getBlockByHash',
                                     recent_block['hash'], True)

            # Check that value was correctly set on contract
            res = contract.get()
            self.log.debug('contract.get() OK {}'.format(res))
            assert res == rand_value

            self.test_successful = True
        except Exception as ex:
            print("Exception", ex)
            import traceback
            traceback.print_exc()
            self.log.exception("Exception in test thread")
        finally:
            self.evt.set()
            self.finished = True