def create_and_distribute_token(client, receivers, amount_per_receiver=1000, name=None, gasprice=GAS_PRICE, timeout=120): """Create a new ERC-20 token and distribute it among `receivers`. If `name` is None, the name will be derived from hashing all receivers. """ name = name or hexlify(sha3(''.join(receivers))) contract_path = get_contract_path('HumanStandardToken.sol') token_proxy = client.deploy_solidity_contract( client.sender, 'HumanStandardToken', compile_file(contract_path), dict(), ( len(receivers) * amount_per_receiver, name, 2, # decimals name[:4].upper() # symbol ), contract_path=contract_path, gasprice=gasprice, timeout=timeout) for receiver in receivers: token_proxy.transact('transfer', receiver, amount_per_receiver) return hexlify(token_proxy.contract_address)
def test_abicontract_interface(): """ Test for issue #370. """ tester_state = state() contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol') contract_name = 'Simple' simple_compiled = compile_file(contract_path) simple_data = solidity_get_contract_data( simple_compiled, contract_path, contract_name, ) simple_address = tester_state.evm(simple_data['bin']) # ABIContract class must accept json_abi abi_json = json.dumps(simple_data['abi']).encode('utf-8') abi = ABIContract( _state=tester_state, _abi=abi_json, address=simple_address, listen=False, log_listener=None, default_key=None, ) assert abi.test() == 1 # pylint: disable=no-member
def _jsonrpc_services(private_keys, verbose, poll_timeout): print_communication = True if verbose > 7 else False privatekey = private_keys[0] address = privatekey_to_address(privatekey) jsonrpc_client = JSONRPCClient( host='0.0.0.0', privkey=privatekey, print_communication=print_communication, ) patch_send_transaction(jsonrpc_client) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path, libraries=dict()) log.info('Deploying registry contract') registry_proxy = jsonrpc_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), timeout=poll_timeout, ) registry_address = registry_proxy.address blockchain_services = list() for privkey in private_keys: blockchain = BlockChainService( privkey, registry_address, ) blockchain_services.append(blockchain) return blockchain_services
def discovery_blockchain(request, private_keys, geth_cluster, poll_timeout): gevent.sleep(2) privatekey = private_keys[0] address = privtoaddr(privatekey) jsonrpc_client = JSONRPCClient( host='0.0.0.0', privkey=privatekey, print_communication=False, ) patch_send_transaction(jsonrpc_client) # deploy discovery contract discovery_contract_path = get_contract_path('EndpointRegistry.sol') discovery_contracts = compile_file(discovery_contract_path, libraries=dict()) discovery_contract_proxy = jsonrpc_client.deploy_solidity_contract( address, 'EndpointRegistry', discovery_contracts, dict(), tuple(), timeout=poll_timeout, ) discovery_contract_address = discovery_contract_proxy.address # initialize and return ContractDiscovery object from raiden.network.discovery import ContractDiscovery return ContractDiscovery(jsonrpc_client, discovery_contract_address), address
def create_and_distribute_token(client, receivers, amount_per_receiver=1000, name=None, gasprice=denoms.shannon * 20, timeout=120): """Create a new ERC-20 token and distribute it among `receivers`. If `name` is None, the name will be derived from hashing all receivers. """ name = name or sha3(''.join(receivers)).encode('hex') token_proxy = client.deploy_solidity_contract( client.sender, 'HumanStandardToken', compile_file(get_contract_path('HumanStandardToken.sol')), dict()( len(receivers) * amount_per_receiver, name, 2, # decimals name[:4].upper() # symbol ), gasprice=gasprice, timeout=timeout) for receiver in receivers: token_proxy.transfer(receiver, amount_per_receiver) return token_proxy.address.encode('hex')
def create_and_distribute_token(client, receivers, amount_per_receiver=1000, name=None, gasprice=denoms.shannon * 20, timeout=120): """Create a new ERC-20 token and distribute it among `receivers`. If `name` is None, the name will be derived from hashing all receivers. """ name = name or sha3(''.join(receivers)).encode('hex') token_proxy = client.deploy_solidity_contract( client.sender, 'HumanStandardToken', compile_file(get_contract_path('HumanStandardToken.sol')), dict() ( len(receivers) * amount_per_receiver, name, 2, # decimals name[:4].upper() # symbol ), gasprice=gasprice, timeout=timeout ) for receiver in receivers: token_proxy.transfer(receiver, amount_per_receiver) return token_proxy.address.encode('hex')
def _jsonrpc_services( deploy_key, deploy_client, private_keys, verbose, poll_timeout, registry_address=None): # we cannot instantiate BlockChainService without a registry, so first # deploy it directly with a JSONRPCClient if registry_address is None: address = privatekey_to_address(deploy_key) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path, libraries=dict()) log.info('Deploying registry contract') registry_proxy = deploy_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), contract_path=registry_path, gasprice=default_gasprice, timeout=poll_timeout, ) registry_address = registry_proxy.address # at this point the blockchain must be running, this will overwrite the # method so even if the client is patched twice, it should work fine patch_send_transaction(deploy_client) deploy_blockchain = BlockChainService( deploy_key, registry_address, deploy_client, ) host = '0.0.0.0' blockchain_services = list() for privkey in private_keys: rpc_client = JSONRPCClient( privkey=privkey, host=host, port=deploy_client.port, print_communication=False, ) patch_send_transaction(rpc_client) patch_send_message(rpc_client) blockchain = BlockChainService( privkey, registry_address, rpc_client, ) blockchain_services.append(blockchain) return BlockchainServices(deploy_blockchain, blockchain_services)
def _jsonrpc_services( deploy_key, private_keys, verbose, poll_timeout, rpc_port, registry_address=None): host = '0.0.0.0' print_communication = verbose > 6 deploy_client = JSONRPCClient( host=host, port=rpc_port, privkey=deploy_key, print_communication=print_communication, ) # we cannot instantiate BlockChainService without a registry, so first # deploy it directly with a JSONRPCClient if registry_address is None: address = privatekey_to_address(deploy_key) patch_send_transaction(deploy_client) patch_send_message(deploy_client) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path, libraries=dict()) log.info('Deploying registry contract') registry_proxy = deploy_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), contract_path=registry_path, gasprice=default_gasprice, timeout=poll_timeout, ) registry_address = registry_proxy.address deploy_blockchain = BlockChainService( deploy_key, registry_address, host, deploy_client.port, ) blockchain_services = list() for privkey in private_keys: blockchain = BlockChainService( privkey, registry_address, host, deploy_client.port, ) blockchain_services.append(blockchain) return BlockchainServices(deploy_blockchain, blockchain_services)
def _jsonrpc_services( deploy_key, private_keys, verbose, poll_timeout, rpc_port, registry_address=None): host = '0.0.0.0' deploy_client = JSONRPCClient( host=host, port=rpc_port, privkey=deploy_key, ) # we cannot instantiate BlockChainService without a registry, so first # deploy it directly with a JSONRPCClient if registry_address is None: address = privatekey_to_address(deploy_key) patch_send_transaction(deploy_client) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path, libraries=dict()) log.info('Deploying registry contract') registry_proxy = deploy_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), timeout=poll_timeout, ) registry_address = registry_proxy.address deploy_blockchain = BlockChainService( deploy_key, registry_address, host, deploy_client.port, ) blockchain_services = list() for privkey in private_keys: blockchain = BlockChainService( privkey, registry_address, host, deploy_client.port, ) blockchain_services.append(blockchain) return BlockchainServices(deploy_blockchain, blockchain_services)
def test_endpointregistry(blockchain_services, poll_timeout): chain = blockchain_services[0] my_address = chain.node_address # deploy discovery contract discovery_contract_path = get_contract_path('EndpointRegistry.sol') discovery_contracts = _solidity.compile_file(discovery_contract_path, libraries=dict()) endpoinregistry_proxy = chain.client.deploy_solidity_contract( my_address, 'EndpointRegistry', discovery_contracts, dict(), tuple(), timeout=poll_timeout, ) endpointregistry_address = endpoinregistry_proxy.address contract_discovery = ContractDiscovery( chain, endpointregistry_address, ) unregistered_address = make_address() # get should raise for unregistered addresses with pytest.raises(KeyError): contract_discovery.get(my_address) with pytest.raises(KeyError): contract_discovery.get(unregistered_address) assert contract_discovery.nodeid_by_host_port(('127.0.0.1', 44444)) is None contract_discovery.register(my_address, '127.0.0.1', 44444) assert contract_discovery.nodeid_by_host_port( ('127.0.0.1', 44444)) == my_address assert contract_discovery.get(my_address) == ('127.0.0.1', 44444) contract_discovery.register(my_address, '127.0.0.1', 88888) assert contract_discovery.nodeid_by_host_port( ('127.0.0.1', 88888)) == my_address assert contract_discovery.get(my_address) == ('127.0.0.1', 88888) with pytest.raises(KeyError): contract_discovery.get(unregistered_address)
def deploy_rpc_test_contract(deploy_client): here = os.path.dirname(os.path.relpath(__file__)) contract_path = os.path.join(here, 'RpcTest.sol') contracts = _solidity.compile_file(contract_path, libraries=dict()) contract_proxy = deploy_client.deploy_solidity_contract( deploy_client.sender, 'RpcTest', contracts, libraries=dict(), constructor_parameters=None, contract_path=contract_path, ) return contract_proxy
def deploy_contract(self, contract_name, contract_file, constructor_parameters=None): contract_path = get_contract_path(contract_file) contracts = _solidity.compile_file(contract_path, libraries=dict()) log.info( 'Deploying "%s" contract', contract_file, ) proxy = self.client.deploy_solidity_contract( self.node_address, contract_name, contracts, dict(), constructor_parameters, timeout=self.poll_timeout, ) return proxy.address
def deploy_contract(self, contract_name, contract_file, constructor_parameters=None): contract_path = get_contract_path(contract_file) contracts = _solidity.compile_file(contract_path, libraries=dict()) log.info('Deploying "{}" contract'.format(contract_file)) proxy = self.client.deploy_solidity_contract( self.node_address, contract_name, contracts, dict(), constructor_parameters, timeout=self.poll_timeout, ) return proxy.address
def create_token( self, initial_alloc=10 ** 6, name='raidentester', symbol='RDT', decimals=2, timeout=60, gasprice=GAS_PRICE, auto_register=True): """ Create a proxy for a new HumanStandardToken (ERC20), that is initialized with Args(below). Per default it will be registered with 'raiden'. Args: initial_alloc (int): amount of initial tokens. name (str): human readable token name. symbol (str): token shorthand symbol. decimals (int): decimal places. timeout (int): timeout in seconds for creation. gasprice (int): gasprice for the creation transaction. auto_register (boolean): if True(default), automatically register the token with raiden. Returns: token_address_hex: the hex encoded address of the new token/token. """ contract_path = get_contract_path('HumanStandardToken.sol') # Deploy a new ERC20 token token_proxy = self._chain.client.deploy_solidity_contract( self._raiden.address, 'HumanStandardToken', compile_file(contract_path), dict(), (initial_alloc, name, decimals, symbol), contract_path=contract_path, gasprice=gasprice, timeout=timeout) token_address_hex = hexlify(token_proxy.address) if auto_register: self.register_token(token_address_hex) print("Successfully created {}the token '{}'.".format( 'and registered ' if auto_register else ' ', name )) return token_address_hex
def deploy_contract(self, contract_name, contract_path, constructor_parameters=None): contracts = _solidity.compile_file(contract_path, libraries=dict()) log.info( 'Deploying "%s" contract', os.path.basename(contract_path), ) proxy = self.client.deploy_solidity_contract( self.node_address, contract_name, contracts, dict(), constructor_parameters, contract_path=contract_path, gasprice=GAS_PRICE, timeout=self.poll_timeout, ) return proxy.contract_address
def create_token( self, initial_alloc=10 ** 6, name='raidentester', symbol='RDT', decimals=2, timeout=60, gasprice=denoms.shannon * 20, auto_register=True): """Create a proxy for a new HumanStandardToken (ERC20), that is initialized with Args(below). Per default it will be registered with 'raiden'. Args: initial_alloc (int): amount of initial tokens. name (str): human readable token name. symbol (str): token shorthand symbol. decimals (int): decimal places. timeout (int): timeout in seconds for creation. gasprice (int): gasprice for the creation transaction. auto_register (boolean): if True(default), automatically register the asset with raiden. Returns: token_address: the hex encoded address of the new token/asset. """ # Deploy a new ERC20 token token_proxy = self._chain.client.deploy_solidity_contract( self._raiden.address, 'HumanStandardToken', compile_file(get_contract_path('HumanStandardToken.sol')), dict(), (initial_alloc, name, decimals, symbol), gasprice=gasprice, timeout=timeout) token_address = token_proxy.address.encode('hex') if auto_register: self.register_asset(token_address) print("Successfully created {}the token '{}'.".format( 'and registered ' if auto_register else ' ', name )) return token_address
def test_abicontract_interface(): """ Test for issue #370. """ tester_state = state() contract_path = path.join(CONTRACTS_DIR, 'simple_contract.sol') simple_compiled = compile_file(contract_path) simple_address = tester_state.evm(simple_compiled['Simple']['bin']) # ABIContract class must accept json_abi abi_json = json.dumps(simple_compiled['Simple']['abi']).encode('utf-8') abi = ABIContract( _state=tester_state, _abi=abi_json, address=simple_address, listen=False, log_listener=None, default_key=None, ) assert abi.test() == 1 # pylint: disable=no-member
def token_abi(): human_token_path = get_contract_path('HumanStandardToken.sol') human_compiled = compile_file(human_token_path, combined='abi') return human_compiled['HumanStandardToken']['abi']
def test_blockchain( blockchain_type, blockchain_backend, # required to start the geth backend blockchain_rpc_ports, private_keys, poll_timeout): # pylint: disable=too-many-locals # this test is for interaction with a blockchain using json-rpc, so it # doesnt make sense to execute it against mock or tester if blockchain_type not in ('geth',): return addresses = [ privatekey_to_address(priv) for priv in private_keys ] privatekey = private_keys[0] address = privatekey_to_address(privatekey) total_token = 100 jsonrpc_client = JSONRPCClient( port=blockchain_rpc_ports[0], privkey=privatekey, print_communication=False, ) patch_send_transaction(jsonrpc_client) patch_send_message(jsonrpc_client) humantoken_path = get_contract_path('HumanStandardToken.sol') humantoken_contracts = compile_file(humantoken_path, libraries=dict()) token_proxy = jsonrpc_client.deploy_solidity_contract( address, 'HumanStandardToken', humantoken_contracts, dict(), (total_token, 'raiden', 2, 'Rd'), contract_path=humantoken_path, gasprice=default_gasprice, timeout=poll_timeout, ) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path) registry_proxy = jsonrpc_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), contract_path=registry_path, gasprice=default_gasprice, timeout=poll_timeout, ) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 0 # pylint: disable=no-member assert token_proxy.balanceOf(address) == total_token transaction_hash = registry_proxy.addToken.transact( token_proxy.address, gasprice=denoms.wei, ) jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=poll_timeout) assert len(registry_proxy.tokenAddresses.call()) == 1 log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 1 channel_manager_address_encoded = registry_proxy.channelManagerByToken.call( token_proxy.address, ) channel_manager_address = channel_manager_address_encoded.decode('hex') log = log_list[0] log_topics = [ decode_topic(topic) for topic in log['topics'] # pylint: disable=invalid-sequence-index ] log_data = log['data'] event = registry_proxy.translator.decode_event( log_topics, log_data[2:].decode('hex'), ) assert channel_manager_address == event['channel_manager_address'].decode('hex') assert token_proxy.address == event['token_address'].decode('hex') channel_manager_proxy = jsonrpc_client.new_contract_proxy( CHANNEL_MANAGER_ABI, channel_manager_address, ) transaction_hash = channel_manager_proxy.newChannel.transact( addresses[1], 10, gasprice=denoms.wei, ) jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=poll_timeout) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 2
def test_blockchain(request): # pylint: disable=too-many-locals from hydrachain import app app.slogging.configure(':ERROR') quantity = 3 base_port = 29870 timeout = 3 # seconds tmp_datadir = tempfile.mktemp() private_keys = [ mk_privkey('raidentest:{}'.format(position)) for position in range(quantity) ] addresses = [privtoaddr(priv) for priv in private_keys] hydrachain_apps = hydrachain_network(private_keys, base_port, tmp_datadir) privatekey = private_keys[0] address = privtoaddr(privatekey) jsonrpc_client = JSONRPCClient(privkey=private_keys[0], print_communication=False) humantoken_path = get_contract_path('HumanStandardToken.sol') humantoken_contracts = compile_file(humantoken_path, libraries=dict()) token_abi = jsonrpc_client.deploy_solidity_contract( address, 'HumanStandardToken', humantoken_contracts, dict(), (9999, 'raiden', 2, 'Rd'), timeout=timeout, ) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path, libraries=dict()) registry_abi = jsonrpc_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), timeout=timeout, ) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 0 # pylint: disable=no-member assert token_abi.balanceOf(address) == 9999 transaction_hash = registry_abi.addAsset(token_abi.address) jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=timeout) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 1 channel_manager_address_encoded = registry_abi.channelManagerByAsset.call( token_abi.address) channel_manager_address = channel_manager_address_encoded.decode('hex') log_channel_manager_address_encoded = log_list[0]['data'] log_channel_manager_address = log_channel_manager_address_encoded[ 2:].lstrip('0').rjust(40, '0').decode('hex') assert channel_manager_address == log_channel_manager_address channel_manager_abi = jsonrpc_client.new_contract_proxy( registry_contracts['ChannelManagerContract']['abi'], channel_manager_address, ) transaction_hash = channel_manager_abi.newChannel(addresses[1], 10) jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=timeout) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 2 channel_manager_abi.get.call( address.encode('hex'), addresses[1].encode('hex'), )
def tester_deploy_contract(tester_state, private_key, contract_name, contract_file, constructor_parameters=None): contract_path = get_contract_path(contract_file) all_contracts = _solidity.compile_file(contract_path, libraries=dict()) contract = all_contracts[contract_name] contract_interface = contract['abi'] log.info('Deploying "{}" contract'.format(contract_file)) dependencies = deploy_dependencies_symbols(all_contracts) deployment_order = dependencies_order_of_build(contract_name, dependencies) log.info('Deploing dependencies: {}'.format(str(deployment_order))) deployment_order.pop() # remove `contract_name` from the list libraries = dict() for deploy_contract in deployment_order: dependency_contract = all_contracts[deploy_contract] hex_bytecode = _solidity.solidity_resolve_symbols( dependency_contract['bin_hex'], libraries, ) bytecode = decode_hex(hex_bytecode) dependency_contract['bin_hex'] = hex_bytecode dependency_contract['bin'] = bytecode log.info('Creating contract {}'.format(deploy_contract)) contract_address = tester_state.evm( bytecode, private_key, endowment=0, ) tester_state.mine(number_of_blocks=1) if len(tester_state.block.get_code(contract_address)) == 0: raise Exception('Contract code empty') libraries[deploy_contract] = encode_hex(contract_address) hex_bytecode = _solidity.solidity_resolve_symbols(contract['bin_hex'], libraries) bytecode = hex_bytecode.decode('hex') contract['bin_hex'] = hex_bytecode contract['bin'] = bytecode if constructor_parameters: translator = ContractTranslator(contract_interface) parameters = translator.encode_constructor_arguments(constructor_parameters) bytecode = contract['bin'] + parameters else: bytecode = contract['bin'] log.info('Creating contract {}'.format(contract_name)) contract_address = tester_state.evm( bytecode, private_key, endowment=0, ) tester_state.mine(number_of_blocks=1) if len(tester_state.block.get_code(contract_address)) == 0: raise Exception('Contract code empty') return contract_address
def netting_channel_abi(): netting_library_path = get_contract_path('ChannelManagerLibrary.sol') netting_channel_compiled = compile_file( netting_library_path)['NettingChannelContract'] netting_channel_abi = netting_channel_compiled['abi'] return netting_channel_abi
def deployed_network(request, private_keys, channels_per_node, deposit, number_of_assets, settle_timeout, poll_timeout, transport_class, geth_cluster): gevent.sleep(2) assert channels_per_node in (0, 1, 2, CHAIN), ( 'deployed_network uses create_sequential_network that can only work ' 'with 0, 1 or 2 channels' ) privatekey = private_keys[0] address = privtoaddr(privatekey) blockchain_service_class = BlockChainService jsonrpc_client = JSONRPCClient( host='0.0.0.0', privkey=privatekey, print_communication=False, ) patch_send_transaction(jsonrpc_client) humantoken_path = get_contract_path('HumanStandardToken.sol') registry_path = get_contract_path('Registry.sol') humantoken_contracts = compile_file(humantoken_path, libraries=dict()) registry_contracts = compile_file(registry_path, libraries=dict()) registry_proxy = jsonrpc_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), timeout=poll_timeout, ) registry_address = registry_proxy.address # Using 3 * deposit because we assume that is the maximum number of # channels that will be created. # `total_per_node = channels_per_node * deposit` total_per_node = 3 * deposit total_asset = total_per_node * len(private_keys) asset_addresses = [] for _ in range(number_of_assets): token_proxy = jsonrpc_client.deploy_solidity_contract( address, 'HumanStandardToken', humantoken_contracts, dict(), (total_asset, 'raiden', 2, 'Rd'), timeout=poll_timeout, ) asset_address = token_proxy.address assert len(asset_address) asset_addresses.append(asset_address) transaction_hash = registry_proxy.addAsset(asset_address) # pylint: disable=no-member jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=poll_timeout) # only the creator of the token starts with a balance, transfer from # the creator to the other nodes for transfer_to in private_keys: if transfer_to != jsonrpc_client.privkey: transaction_hash = token_proxy.transfer( # pylint: disable=no-member privtoaddr(transfer_to), total_per_node, startgas=GAS_LIMIT, ) jsonrpc_client.poll(transaction_hash.decode('hex')) for key in private_keys: assert token_proxy.balanceOf(privtoaddr(key)) == total_per_node # pylint: disable=no-member raiden_apps = create_sequential_network( private_keys, asset_addresses[0], registry_address, channels_per_node, deposit, settle_timeout, poll_timeout, transport_class, blockchain_service_class, ) _raiden_cleanup(request, raiden_apps) return raiden_apps
def test_blockchain( blockchain_type, blockchain_backend, # required to start the geth backend blockchain_rpc_ports, private_keys, poll_timeout): # pylint: disable=too-many-locals # this test is for interaction with a blockchain using json-rpc, so it # doesnt make sense to execute it against mock or tester if blockchain_type not in ('geth',): return addresses = [ privatekey_to_address(priv) for priv in private_keys ] privatekey = private_keys[0] address = privatekey_to_address(privatekey) total_asset = 100 jsonrpc_client = JSONRPCClient( port=blockchain_rpc_ports[0], privkey=privatekey, print_communication=False, ) patch_send_transaction(jsonrpc_client) humantoken_path = get_contract_path('HumanStandardToken.sol') humantoken_contracts = compile_file(humantoken_path, libraries=dict()) token_proxy = jsonrpc_client.deploy_solidity_contract( address, 'HumanStandardToken', humantoken_contracts, dict(), (total_asset, 'raiden', 2, 'Rd'), timeout=poll_timeout, ) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path) registry_proxy = jsonrpc_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), timeout=poll_timeout, ) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 0 # pylint: disable=no-member assert token_proxy.balanceOf(address) == total_asset transaction_hash = registry_proxy.addAsset.transact( token_proxy.address, gasprice=denoms.wei, ) jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=poll_timeout) assert len(registry_proxy.assetAddresses.call()) == 1 log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 1 channel_manager_address_encoded = registry_proxy.channelManagerByAsset.call( token_proxy.address, ) channel_manager_address = channel_manager_address_encoded.decode('hex') log = log_list[0] log_topics = [ decode_topic(topic) for topic in log['topics'] # pylint: disable=invalid-sequence-index ] log_data = log['data'] event = registry_proxy.translator.decode_event( log_topics, log_data[2:].decode('hex'), ) assert channel_manager_address == event['channel_manager_address'].decode('hex') assert token_proxy.address == event['asset_address'].decode('hex') channel_manager_proxy = jsonrpc_client.new_contract_proxy( registry_contracts['ChannelManagerContract']['abi'], channel_manager_address, ) transaction_hash = channel_manager_proxy.newChannel.transact( addresses[1], 10, gasprice=denoms.wei, ) jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=poll_timeout) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 2
def test_blockchain(request): # pylint: disable=too-many-locals from hydrachain import app app.slogging.configure(':ERROR') quantity = 3 base_port = 29870 timeout = 3 # seconds tmp_datadir = tempfile.mktemp() private_keys = [ mk_privkey('raidentest:{}'.format(position)) for position in range(quantity) ] addresses = [ privtoaddr(priv) for priv in private_keys ] hydrachain_apps = hydrachain_network(private_keys, base_port, tmp_datadir) privatekey = private_keys[0] address = privtoaddr(privatekey) jsonrpc_client = JSONRPCClient(privkey=private_keys[0], print_communication=False) humantoken_path = get_contract_path('HumanStandardToken.sol') humantoken_contracts = compile_file(humantoken_path, libraries=dict()) token_abi = jsonrpc_client.deploy_solidity_contract( address, 'HumanStandardToken', humantoken_contracts, dict(), (9999, 'raiden', 2, 'Rd'), timeout=timeout, ) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path, libraries=dict()) registry_abi = jsonrpc_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), timeout=timeout, ) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 0 # pylint: disable=no-member assert token_abi.balanceOf(address) == 9999 transaction_hash = registry_abi.addAsset(token_abi.address) jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=timeout) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 1 channel_manager_address_encoded = registry_abi.channelManagerByAsset.call(token_abi.address) channel_manager_address = channel_manager_address_encoded.decode('hex') log_channel_manager_address_encoded = log_list[0]['data'] log_channel_manager_address = log_channel_manager_address_encoded[2:].lstrip('0').rjust(40, '0').decode('hex') assert channel_manager_address == log_channel_manager_address channel_manager_abi = jsonrpc_client.new_contract_proxy( registry_contracts['ChannelManagerContract']['abi'], channel_manager_address, ) transaction_hash = channel_manager_abi.newChannel(addresses[1], 10) jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=timeout) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 2 channel_manager_abi.get.call( address.encode('hex'), addresses[1].encode('hex'), )
def test_blockchain( blockchain_backend, # required to start the geth backend pylint: disable=unused-argument blockchain_rpc_ports, private_keys, poll_timeout): # pylint: disable=too-many-locals addresses = [privatekey_to_address(priv) for priv in private_keys] privatekey = private_keys[0] address = privatekey_to_address(privatekey) total_token = 100 host = '127.0.0.1' jsonrpc_client = JSONRPCClient( host, blockchain_rpc_ports[0], privatekey, ) humantoken_path = get_contract_path('HumanStandardToken.sol') humantoken_contracts = compile_file(humantoken_path, libraries=dict()) token_proxy = jsonrpc_client.deploy_solidity_contract( address, 'HumanStandardToken', humantoken_contracts, dict(), (total_token, 'raiden', 2, 'Rd'), contract_path=humantoken_path, gasprice=GAS_PRICE, timeout=poll_timeout, ) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path) registry_proxy = jsonrpc_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), contract_path=registry_path, gasprice=GAS_PRICE, timeout=poll_timeout, ) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert not log_list assert token_proxy.call('balanceOf', address) == total_token transaction_hash = registry_proxy.transact( 'addToken', token_proxy.contract_address, gasprice=denoms.wei, ) jsonrpc_client.poll(unhexlify(transaction_hash), timeout=poll_timeout) assert len(registry_proxy.call('tokenAddresses')) == 1 log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 1 channel_manager_address_encoded = registry_proxy.call( 'channelManagerByToken', token_proxy.contract_address, ) channel_manager_address = unhexlify(channel_manager_address_encoded) log = log_list[0] log_topics = [ topic_decoder(topic) for topic in log['topics'] # pylint: disable=invalid-sequence-index ] log_data = log['data'] # pylint: disable=invalid-sequence-index event = registry_proxy.translator.decode_event( log_topics, unhexlify(log_data[2:]), ) assert channel_manager_address == unhexlify( event['channel_manager_address']) assert token_proxy.contract_address == unhexlify(event['token_address']) channel_manager_proxy = jsonrpc_client.new_contract_proxy( CONTRACT_MANAGER.get_abi(CONTRACT_CHANNEL_MANAGER), channel_manager_address, ) transaction_hash = channel_manager_proxy.transact( 'newChannel', addresses[1], 10, gasprice=denoms.wei, ) jsonrpc_client.poll(unhexlify(transaction_hash), timeout=poll_timeout) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 2
def compile_contract(contract_path): contract_compiled = compile_file(contract_path) return contract_compiled
def test_blockchain(blockchain_backend, private_keys, number_of_nodes, poll_timeout): # pylint: disable=too-many-locals addresses = [privatekey_to_address(priv) for priv in private_keys] privatekey = private_keys[0] address = privatekey_to_address(privatekey) total_asset = 100 jsonrpc_client = JSONRPCClient( privkey=privatekey, print_communication=False, ) patch_send_transaction(jsonrpc_client) humantoken_path = get_contract_path('HumanStandardToken.sol') humantoken_contracts = compile_file(humantoken_path, libraries=dict()) token_proxy = jsonrpc_client.deploy_solidity_contract( address, 'HumanStandardToken', humantoken_contracts, dict(), (total_asset, 'raiden', 2, 'Rd'), timeout=poll_timeout, ) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path) registry_proxy = jsonrpc_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), timeout=poll_timeout, ) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 0 # pylint: disable=no-member assert token_proxy.balanceOf(address) == total_asset transaction_hash = registry_proxy.addAsset.transact( token_proxy.address, gasprice=denoms.wei, ) jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=poll_timeout) assert len(registry_proxy.assetAddresses.call()) == 1 log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 1 channel_manager_address_encoded = registry_proxy.channelManagerByAsset.call( token_proxy.address) channel_manager_address = channel_manager_address_encoded.decode('hex') log = log_list[0] log_topics = [ decode_topic(topic) for topic in log['topics'] # pylint: disable=invalid-sequence-index ] log_data = log['data'] event = registry_proxy.translator.decode_event( log_topics, log_data[2:].decode('hex'), ) assert channel_manager_address == event['channelManagerAddress'].decode( 'hex') assert token_proxy.address == event['assetAddress'].decode('hex') channel_manager_proxy = jsonrpc_client.new_contract_proxy( registry_contracts['ChannelManagerContract']['abi'], channel_manager_address, ) transaction_hash = channel_manager_proxy.newChannel.transact( addresses[1], 10, gasprice=denoms.wei, ) jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=poll_timeout) log_list = jsonrpc_client.call( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 2
def netting_channel_abi(): netting_library_path = get_contract_path('ChannelManagerLibrary.sol') netting_channel_compiled = compile_file(netting_library_path)['NettingChannelContract'] netting_channel_abi = netting_channel_compiled['abi'] return netting_channel_abi
def tester_deploy_contract( tester_state, private_key, contract_name, contract_file, constructor_parameters=None): contract_path = get_contract_path(contract_file) all_contracts = _solidity.compile_file(contract_path, libraries=dict()) contract_key = solidity_get_contract_key(all_contracts, contract_path, contract_name) contract = all_contracts[contract_key] contract_interface = contract['abi'] log.info('Deploying "{}" contract'.format(contract_file)) dependencies = deploy_dependencies_symbols(all_contracts) deployment_order = dependencies_order_of_build(contract_key, dependencies) log.info('Deploying dependencies: {}'.format(str(deployment_order))) deployment_order.pop() # remove `contract_name` from the list libraries = dict() for deploy_contract in deployment_order: dependency_contract = all_contracts[deploy_contract] hex_bytecode = _solidity.solidity_resolve_symbols( dependency_contract['bin_hex'], libraries, ) bytecode = decode_hex(hex_bytecode) dependency_contract['bin_hex'] = hex_bytecode dependency_contract['bin'] = bytecode log.info('Creating contract {}'.format(deploy_contract)) contract_address = tester_state.evm( bytecode, private_key, endowment=0, ) tester_state.mine(number_of_blocks=1) if len(tester_state.block.get_code(contract_address)) == 0: raise Exception('Contract code empty') libraries[deploy_contract] = encode_hex(contract_address) hex_bytecode = _solidity.solidity_resolve_symbols(contract['bin_hex'], libraries) bytecode = hex_bytecode.decode('hex') contract['bin_hex'] = hex_bytecode contract['bin'] = bytecode if constructor_parameters: translator = ContractTranslator(contract_interface) parameters = translator.encode_constructor_arguments(constructor_parameters) bytecode = contract['bin'] + parameters else: bytecode = contract['bin'] log.info('Creating contract {}'.format(contract_name)) contract_address = tester_state.evm( bytecode, private_key, endowment=0, ) tester_state.mine(number_of_blocks=1) if len(tester_state.block.get_code(contract_address)) == 0: raise Exception('Contract code empty') return contract_address
def deployed_network(request, private_keys, channels_per_node, deposit, number_of_assets, settle_timeout, poll_timeout, transport_class, geth_cluster): gevent.sleep(2) assert channels_per_node in (0, 1, 2, CHAIN), ( 'deployed_network uses create_sequential_network that can only work ' 'with 0, 1 or 2 channels') privatekey = private_keys[0] address = privtoaddr(privatekey) blockchain_service_class = BlockChainService jsonrpc_client = JSONRPCClient( host='0.0.0.0', privkey=privatekey, print_communication=False, ) patch_send_transaction(jsonrpc_client) humantoken_path = get_contract_path('HumanStandardToken.sol') registry_path = get_contract_path('Registry.sol') humantoken_contracts = compile_file(humantoken_path, libraries=dict()) registry_contracts = compile_file(registry_path, libraries=dict()) registry_proxy = jsonrpc_client.deploy_solidity_contract( address, 'Registry', registry_contracts, dict(), tuple(), timeout=poll_timeout, ) registry_address = registry_proxy.address # Using 3 * deposit because we assume that is the maximum number of # channels that will be created. # `total_per_node = channels_per_node * deposit` total_per_node = 3 * deposit total_asset = total_per_node * len(private_keys) asset_addresses = [] for _ in range(number_of_assets): token_proxy = jsonrpc_client.deploy_solidity_contract( address, 'HumanStandardToken', humantoken_contracts, dict(), (total_asset, 'raiden', 2, 'Rd'), timeout=poll_timeout, ) asset_address = token_proxy.address assert len(asset_address) asset_addresses.append(asset_address) transaction_hash = registry_proxy.addAsset(asset_address) # pylint: disable=no-member jsonrpc_client.poll(transaction_hash.decode('hex'), timeout=poll_timeout) # only the creator of the token starts with a balance, transfer from # the creator to the other nodes for transfer_to in private_keys: if transfer_to != jsonrpc_client.privkey: transaction_hash = token_proxy.transfer( # pylint: disable=no-member privtoaddr(transfer_to), total_per_node, startgas=GAS_LIMIT, ) jsonrpc_client.poll(transaction_hash.decode('hex')) for key in private_keys: assert token_proxy.balanceOf(privtoaddr(key)) == total_per_node # pylint: disable=no-member raiden_apps = create_sequential_network( private_keys, asset_addresses[0], registry_address, channels_per_node, deposit, settle_timeout, poll_timeout, transport_class, blockchain_service_class, ) _raiden_cleanup(request, raiden_apps) return raiden_apps