def test_token(): standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') state = tester.state() state.block.number = 1158001 address0 = tester.a0 address1 = tester.a1 standard_token = state.abi_contract( None, path=standard_token_path, language='solidity', ) contract_libraries = { 'StandardToken': hexlify(standard_token.address), } human_token = state.abi_contract( None, path=human_token_path, language='solidity', libraries=contract_libraries, constructor_parameters=[10000, 'raiden', 0, 'rd'], ) # pylint: disable=no-member assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.transfer(address1, 5000) is True assert human_token.balanceOf(address0) == 5000 assert human_token.balanceOf(address1) == 5000
def deploy_standard_token(deploy_key, tester_chain, token_amount): standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') standard_token_compiled = _solidity.compile_contract( standard_token_path, "StandardToken" ) standard_token_address = tester_chain.contract( standard_token_compiled['bin'], language='evm' ) tester_chain.mine(number_of_blocks=1) contract_libraries = { 'StandardToken': hexlify(standard_token_address), } human_token_compiled = _solidity.compile_contract( human_token_path, 'HumanStandardToken', contract_libraries ) ct = tester.ContractTranslator(human_token_compiled['abi']) human_token_args = ct.encode_constructor_arguments([token_amount, 'raiden', 0, 'rd']) human_token_address = tester_chain.contract( human_token_compiled['bin'] + human_token_args, language='evm', sender=deploy_key ) tester_chain.mine(number_of_blocks=1) return human_token_address
def find_dependencies(contract_file): """Resolve solidity dependencies depth first. """ dependencies = [] with open(contract_file) as handler: for line in handler.readlines(): if line.startswith("import"): dependency = line.split()[1].split('"')[1] dependency = dependency.rsplit('/', 1)[-1] if dependency not in dependencies: dependencies.extend( find_dependencies(get_contract_path(dependency))) dependencies.append(dependency) cleaned = [] for dependency in dependencies: if dependency not in cleaned: cleaned.append(dependency) dependencies = cleaned cleaned = [] for dependency in dependencies: with open(get_contract_path(dependency)) as handler: if any( line.startswith('interface') for line in handler.readlines()): continue cleaned.append(dependency) return cleaned
def test_token(): standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') state = tester.state() state.block.number = 1158001 address0 = tester.a0 address1 = tester.a1 standard_token = state.abi_contract( None, path=standard_token_path, language='solidity', ) contract_libraries = { 'StandardToken': standard_token.address.encode('hex'), } human_token = state.abi_contract( None, path=human_token_path, language='solidity', libraries=contract_libraries, constructor_parameters=[10000, 'raiden', 0, 'rd'], ) # pylint: disable=no-member assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.transfer(address1, 5000) is True assert human_token.balanceOf(address0) == 5000 assert human_token.balanceOf(address1) == 5000
def load_or_create_smoketest_config(): # get the contract and compiler (if available) versions versions = dict() for file in os.listdir(get_contract_path('')): if file.endswith('.sol'): versions[file] = contract_checksum(get_contract_path(file)) # if solc is available, record its version, too if get_solidity() is not None: solc_version_out, _ = subprocess.Popen( [get_solidity().compiler_available(), '--version'], stdout=subprocess.PIPE).communicate() versions['solc'] = solc_version_out.split()[-1] smoketest_config_path = os.path.join(get_project_root(), 'smoketest_config.json') # try to load an existing smoketest genesis config smoketest_config = dict() if os.path.exists(smoketest_config_path): with open(smoketest_config_path) as handler: smoketest_config = json.load(handler) # if the file versions still fit, return the genesis config (ignore solc if not available) if all(versions[key] == smoketest_config['versions'][key] for key in versions.keys()): return smoketest_config # something did not fit -- we will create the genesis smoketest_config['versions'] = versions raiden_config, smoketest_genesis = complete_genesis() smoketest_config['genesis'] = smoketest_genesis smoketest_config.update(raiden_config) with open(os.path.join(get_project_root(), 'smoketest_config.json'), 'w') as handler: json.dump(smoketest_config, handler) return smoketest_config
def deploy_standard_token(deploy_key, tester_state, token_amount): standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') standard_token_address = tester_state.contract( None, path=standard_token_path, language='solidity', ) tester_state.mine(number_of_blocks=1) human_token_libraries = { 'StandardToken': standard_token_address.encode('hex'), } # using abi_contract because of the constructor_parameters human_token_proxy = tester_state.abi_contract( None, path=human_token_path, language='solidity', libraries=human_token_libraries, constructor_parameters=[token_amount, 'raiden', 0, 'rd'], sender=deploy_key, ) tester_state.mine(number_of_blocks=1) human_token_address = human_token_proxy.address return human_token_address
def tester_token_address(private_keys, asset_amount, tester_state): standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') standard_token_address = tester_state.contract( None, path=standard_token_path, language='solidity', ) tester_state.mine(number_of_blocks=1) human_token_libraries = { 'StandardToken': standard_token_address.encode('hex'), } # using abi_contract because of the constructor_parameters human_token_proxy = tester_state.abi_contract( None, path=human_token_path, language='solidity', libraries=human_token_libraries, constructor_parameters=[asset_amount, 'raiden', 0, 'rd'], sender=private_keys[0], ) tester_state.mine(number_of_blocks=1) human_token_address = human_token_proxy.address return human_token_address
def test_token_approve(): test_path = os.path.join(os.path.dirname(__file__), 'SimpleApproveTransfer.sol') standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') state = tester.state() state.block.number = 1158001 address0 = tester.a0 address1 = tester.a1 standard_token = state.abi_contract( None, path=standard_token_path, language='solidity', ) contract_libraries = { 'StandardToken': hexlify(standard_token.address), } human_token = state.abi_contract( None, path=human_token_path, language='solidity', libraries=contract_libraries, constructor_parameters=[10000, 'raiden', 0, 'rd'], ) test = state.abi_contract( None, path=test_path, language='solidity', constructor_parameters=[human_token.address], ) # pylint: disable=no-member assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.balanceOf(test.address) == 0 assert human_token.allowance(address0, address0) == 0 assert human_token.allowance(address0, address1) == 0 assert human_token.allowance(address0, test.address) == 0 assert human_token.approve(test.address, 5000) is True assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.balanceOf(test.address) == 0 assert human_token.allowance(address0, address0) == 0 assert human_token.allowance(address0, address1) == 0 assert human_token.allowance(address0, test.address) == 5000 assert test.transfer(address1, 2000) is True assert human_token.balanceOf(address0) == 10000 - 2000 assert human_token.balanceOf(address1) == 0 + 2000 assert human_token.balanceOf(test.address) == 0 assert human_token.allowance(address0, address0) == 0 assert human_token.allowance(address0, address1) == 0 assert human_token.allowance(address0, test.address) == 5000 - 2000
def test_token_approve(): test_path = os.path.join(os.path.dirname(__file__), 'SimpleApproveTransfer.sol') standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') state = tester.state() state.block.number = 1158001 address0 = tester.a0 address1 = tester.a1 standard_token = state.abi_contract( None, path=standard_token_path, language='solidity', ) contract_libraries = { 'StandardToken': standard_token.address.encode('hex'), } human_token = state.abi_contract( None, path=human_token_path, language='solidity', libraries=contract_libraries, constructor_parameters=[10000, 'raiden', 0, 'rd'], ) test = state.abi_contract( None, path=test_path, language='solidity', constructor_parameters=[human_token.address], ) # pylint: disable=no-member assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.balanceOf(test.address) == 0 assert human_token.allowance(address0, address0) == 0 assert human_token.allowance(address0, address1) == 0 assert human_token.allowance(address0, test.address) == 0 assert human_token.approve(test.address, 5000) is True assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.balanceOf(test.address) == 0 assert human_token.allowance(address0, address0) == 0 assert human_token.allowance(address0, address1) == 0 assert human_token.allowance(address0, test.address) == 5000 assert test.transfer(address1, 2000) is True assert human_token.balanceOf(address0) == 10000 - 2000 assert human_token.balanceOf(address1) == 0 + 2000 assert human_token.balanceOf(test.address) == 0 assert human_token.allowance(address0, address0) == 0 assert human_token.allowance(address0, address1) == 0 assert human_token.allowance(address0, test.address) == 5000 - 2000
def deploy_with_dependencies(contract_name, state, libraries=None): if not libraries: libraries = dict() dependencies = find_dependencies(get_contract_path(contract_name)) dependency_names = [d.split('.')[0] for d in dependencies] for key in list(libraries.keys()): if key not in dependency_names: libraries.pop(key) log.DEV( # pylint: disable=no-member 'in deploy_with_dependencies', contract=contract_name, dependencies=dependencies, ) for dependency in dependencies: # 'Contract's are included in 'Registry' and should not be deployed alone if 'Contract' in dependency: continue log.DEV('deploying dependency', name=dependency) # pylint: disable=no-member log.DEV('known libraries', libraries=libraries) # pylint: disable=no-member deployed = state.abi_contract( None, path=get_contract_path(dependency), listen=False, language='solidity', libraries=libraries, sender=DEFAULT_KEY, ) libraries[dependency.split('.')[0]] = hexlify(deployed.address) state.mine() log.DEV('deploying target', name=contract_name) # pylint: disable=no-member log.DEV('known libraries', libraries=libraries) # pylint: disable=no-member contract = state.abi_contract( None, path=get_contract_path(contract_name), language='solidity', libraries=libraries, sender=DEFAULT_KEY, ) libraries[contract_name.split('.')[0]] = hexlify(contract.address) state.mine() return libraries
def deploy_with_dependencies(contract_name, state, libraries=None): if not libraries: libraries = dict() dependencies = find_dependencies(get_contract_path(contract_name)) dependency_names = [d.split('.')[0] for d in dependencies] for key in list(libraries.keys()): if key not in dependency_names: libraries.pop(key) log.DEV( # pylint: disable=no-member 'in deploy_with_dependencies', contract=contract_name, dependencies=dependencies, ) for dependency in dependencies: # 'Contract's are included in 'Registry' and should not be deployed alone if 'Contract' in dependency: continue log.DEV('deploying dependency', name=dependency) # pylint: disable=no-member log.DEV('known libraries', libraries=libraries) # pylint: disable=no-member deployed = state.abi_contract( None, path=get_contract_path(dependency), listen=False, language='solidity', libraries=libraries, sender=DEFAULT_KEY, ) libraries[dependency.split('.')[0]] = deployed.address.encode('hex') state.mine() log.DEV('deploying target', name=contract_name) # pylint: disable=no-member log.DEV('known libraries', libraries=libraries) # pylint: disable=no-member contract = state.abi_contract( None, path=get_contract_path(contract_name), language='solidity', libraries=libraries, sender=DEFAULT_KEY, ) libraries[contract_name.split('.')[0]] = contract.address.encode('hex') state.mine() return libraries
def test_endpointregistry(tester_chain, tester_events): account0 = tester.a0 sender = address_encoder(account0) endpointregistry_path = get_contract_path('EndpointRegistry.sol') endpointregistry_compiled = _solidity.compile_contract( endpointregistry_path, "EndpointRegistry" ) tester_chain.head_state.log_listeners.append(tester_events.append) endpointregistry_address = tester_chain.contract( endpointregistry_compiled['bin'], language='evm' ) endpoint_registry = tester.ABIContract( tester_chain, endpointregistry_compiled['abi'], endpointregistry_address ) endpoint_registry.registerEndpoint('127.0.0.1:4001') assert endpoint_registry.findAddressByEndpoint('127.0.0.1:4001') == sender assert endpoint_registry.findEndpointByAddress(sender) == b'127.0.0.1:4001' endpoint_registry.registerEndpoint('192.168.0.1:4002') assert endpoint_registry.findAddressByEndpoint('192.168.0.1:4002') == sender assert endpoint_registry.findEndpointByAddress(sender) == b'192.168.0.1:4002' assert len(tester_events) == 2 event0 = event_decoder(tester_events[0], endpoint_registry.translator) event1 = event_decoder(tester_events[1], endpoint_registry.translator) assert event0['_event_type'] == b'AddressRegistered' assert event1['_event_type'] == b'AddressRegistered'
def create_and_distribute_token(client, receivers, amount_per_receiver=1000, name=None, 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 encode_hex(sha3(''.join(receivers).encode())) contract_path = get_contract_path('HumanStandardToken.sol') with gevent.Timeout(timeout): token_proxy = client.deploy_solidity_contract( 'HumanStandardToken', compile_files_cwd([contract_path]), dict(), ( len(receivers) * amount_per_receiver, name, 2, # decimals name[:4].upper(), # symbol ), contract_path=contract_path, ) for receiver in receivers: token_proxy.transact('transfer', receiver, amount_per_receiver) return to_checksum_address(token_proxy.contract_address)
def test_deploy_contract(raiden_network, deploy_client, tmpdir): """Test deploying contract with different version than the one we have set in Registry.sol. This test makes sense only for geth backend, tester uses mocked Registry class. """ contract_path = get_contract_path('Registry.sol') # Create temporary directory to put all files required to compile the changed contract to. # Why? Solidity uses first 40 characters of the file path as a library symbol. # It would be nice to just do a copy of 'Registry.sol', replace version and include statements # and then by path substitution argument of solc set the path to something like # raiden-contracts=/path/to/your/raiden/source/contracts. But then if the path is too long, # Python solidity compiler will fail because of duplicate library symbol. temp_dir = TempSolidityDir(os.path.dirname(contract_path), tmpdir) replaced_registry_path = os.path.join(temp_dir.name, 'Registry.sol') CONTRACT_MANAGER.get_contract_abi(CONTRACT_CHANNEL_MANAGER) replace_contract_version(replaced_registry_path, '0.0.31415') contracts = compile_files_cwd([replaced_registry_path]) contract_proxy = deploy_client.deploy_solidity_contract( 'Registry', contracts, dict(), None, contract_path=replaced_registry_path, ) contract_address = contract_proxy.contract_address app0 = raiden_network[0] with pytest.raises(ContractVersionMismatch): app0.raiden.chain.registry(contract_address)
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 create_and_distribute_token( client, receivers, amount_per_receiver=1000, name=None, 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).encode())) contract_path = get_contract_path('HumanStandardToken.sol') with gevent.Timeout(timeout): token_proxy = client.deploy_solidity_contract( 'HumanStandardToken', compile_files_cwd([contract_path]), dict(), ( len(receivers) * amount_per_receiver, name, 2, # decimals name[:4].upper(), # symbol ), contract_path=contract_path, ) for receiver in receivers: token_proxy.transact('transfer', receiver, amount_per_receiver) return hexlify(token_proxy.contract_address)
def test_token_registration(blockchain_type, raiden_network, tester_state): if blockchain_type == 'tester': pytest.skip( 'current version of the pyethereum dependency does not support the REVERT opcode' ) node1 = raiden_network[0] token_amount = 1000 token_address = node1.raiden.chain.deploy_contract( contract_name='HumanStandardToken', contract_path=get_contract_path('HumanStandardToken.sol'), constructor_parameters=(token_amount, 'raiden', 2, 'Rd'), ) api1 = RaidenAPI(node1.raiden) assert not api1.get_tokens_list() assert api1.manager_address_if_token_registered(token_address) is None node1.raiden.poll_blockchain_events() assert not api1.get_tokens_list() api1.register_token(token_address) assert api1.manager_address_if_token_registered(token_address) is not None assert api1.get_tokens_list() == [token_address]
def test_endpointregistry(tester_state, tester_events): account0 = tester.DEFAULT_ACCOUNT sender = hexlify(account0) endpointregistry_path = get_contract_path('EndpointRegistry.sol') registry_contract = tester_state.abi_contract( None, path=endpointregistry_path, language='solidity', log_listener=tester_events.append, ) registry_contract.registerEndpoint('127.0.0.1:4001') assert registry_contract.findAddressByEndpoint('127.0.0.1:4001') == sender assert registry_contract.findEndpointByAddress(sender) == '127.0.0.1:4001' registry_contract.registerEndpoint('192.168.0.1:4002') assert registry_contract.findAddressByEndpoint( '192.168.0.1:4002') == sender assert registry_contract.findEndpointByAddress( sender) == '192.168.0.1:4002' assert len(tester_events) == 2 assert tester_events[0]['_event_type'] == 'AddressRegistered' assert tester_events[1]['_event_type'] == 'AddressRegistered'
def test_endpointregistry(tester_chain, tester_events): account0 = tester.a0 sender = address_encoder(account0) endpointregistry_path = get_contract_path('EndpointRegistry.sol') endpointregistry_compiled = _solidity.compile_contract( endpointregistry_path, "EndpointRegistry") tester_chain.head_state.log_listeners.append(tester_events.append) endpointregistry_address = tester_chain.contract( endpointregistry_compiled['bin'], language='evm') endpoint_registry = tester.ABIContract(tester_chain, endpointregistry_compiled['abi'], endpointregistry_address) endpoint_registry.registerEndpoint('127.0.0.1:4001') assert endpoint_registry.findAddressByEndpoint('127.0.0.1:4001') == sender assert endpoint_registry.findEndpointByAddress(sender) == b'127.0.0.1:4001' endpoint_registry.registerEndpoint('192.168.0.1:4002') assert endpoint_registry.findAddressByEndpoint( '192.168.0.1:4002') == sender assert endpoint_registry.findEndpointByAddress( sender) == b'192.168.0.1:4002' assert len(tester_events) == 2 event0 = event_decoder(tester_events[0], endpoint_registry.translator) event1 = event_decoder(tester_events[1], endpoint_registry.translator) assert event0['_event_type'] == b'AddressRegistered' assert event1['_event_type'] == b'AddressRegistered'
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 parse_contract_version(contract_file, version_re): contract_file = get_contract_path(contract_file) with open(contract_file, 'r') as original: for line in original.readlines(): match = version_re.match(line) if match: return match.group(1)
def deploy_all(client): contracts_expanded = [get_contract_path(x) for x in RAIDEN_CONTRACT_FILES] compiled_contracts = compile_files_cwd(contracts_expanded) deployed = {} for contract in CONTRACTS_TO_DEPLOY: deployed.update(deploy_file(contract, compiled_contracts, client)) return deployed
def test_endpointregistry(private_keys, blockchain_services): chain = blockchain_services.blockchain_services[0] my_address = privatekey_to_address(private_keys[0]) endpointregistry_address = chain.deploy_contract( 'EndpointRegistry', get_contract_path('EndpointRegistry.sol'), ) discovery_proxy = chain.discovery(endpointregistry_address) contract_discovery = ContractDiscovery(my_address, discovery_proxy) 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 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 test_register_token(api_backend, token_amount, token_addresses, raiden_network): app0 = raiden_network[0] new_token_address = app0.raiden.chain.deploy_contract( contract_name='HumanStandardToken', contract_path=get_contract_path('HumanStandardToken.sol'), constructor_parameters=(token_amount, 'raiden', 2, 'Rd'), ) register_request = grequests.put( api_url_for( api_backend, 'registertokenresource', token_address=to_checksum_address(new_token_address), )) register_response = register_request.send().response assert_proper_response(register_response, status_code=HTTPStatus.CREATED) assert 'channel_manager_address' in register_response.json() # now try to reregister it and get the error conflict_request = grequests.put( api_url_for( api_backend, 'registertokenresource', token_address=to_checksum_address(new_token_address), )) conflict_response = conflict_request.send().response assert_response_with_error(conflict_response, HTTPStatus.CONFLICT)
def validate_solc(): if get_solc_version() is None: raise RuntimeError( "Couldn't find the solc in the current $PATH.\n" "Make sure the solidity compiler is installed and available on your $PATH.", ) try: compile_files( [get_contract_path('HumanStandardToken.sol')], 'HumanStandardToken', optimize=False, ) except subprocess.CalledProcessError as e: msg = ( 'The solidity compiler failed to execute. Please make sure that you\n' 'are using the binary version of the compiler (solc-js is not compatible)\n' 'and that the version is >= {}'.format(MIN_REQUIRED_SOLC)) if e.output: msg += ('\n' 'Output: ' + e.output) raise RuntimeError(msg) except OSError as e: msg = ( 'The solidity compiler failed to execute. Please make sure the\n' 'binary is compatible with your architecture and you can execute it.' ) child_traceback = getattr(e, 'child_traceback', None) if child_traceback: msg += ('\n' 'Traceback: ' + child_traceback) raise RuntimeError(msg)
def test_token_registered_race(raiden_chain, token_amount): """Test recreating the scenario described on issue: https://github.com/raiden-network/raiden/issues/784""" app0, app1 = raiden_chain api0 = RaidenAPI(app0.raiden) api1 = RaidenAPI(app1.raiden) # Recreate the race condition by making sure the non-registering app won't # register at all by watching for the TokenAdded blockchain event. app1.raiden.alarm.remove_callback(app1.raiden.poll_blockchain_events) token_address = app1.raiden.chain.deploy_contract( contract_name='HumanStandardToken', contract_path=get_contract_path('HumanStandardToken.sol'), constructor_parameters=(token_amount, 'raiden', 2, 'Rd'), ) gevent.sleep(1) assert token_address not in api0.get_tokens_list() assert token_address not in api1.get_tokens_list() api0.token_network_register(token_address) gevent.sleep(1) assert token_address in api0.get_tokens_list() assert token_address not in api1.get_tokens_list() # The next time when the event is polled, the token is registered app1.raiden.poll_blockchain_events() assert token_address in api1.get_tokens_list()
def test_endpointregistry(private_keys, blockchain_services): chain = blockchain_services.blockchain_services[0] my_address = privatekey_to_address(private_keys[0]) endpointregistry_address = chain.deploy_contract( 'EndpointRegistry', get_contract_path('EndpointRegistry.sol'), ) discovery_proxy = chain.discovery(endpointregistry_address) contract_discovery = ContractDiscovery(my_address, discovery_proxy) unregistered_address = make_address() # get should raise for unregistered addresses with pytest.raises(UnknownAddress): contract_discovery.get(my_address) with pytest.raises(UnknownAddress): 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(UnknownAddress): contract_discovery.get(unregistered_address)
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 allcontracts(contract_files): return { "{}:{}".format(c, name_from_file(c)): compile_contract(get_contract_path(c), name_from_file(c), optimize=False) for c in contract_files }
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 _token_addresses( token_amount, number_of_tokens, deploy_service, registry, participants, register ): """ Deploy `number_of_tokens` ERC20 token instances with `token_amount` minted and distributed among `blockchain_services`. Optionally the instances will be registered with the raiden registry. Args: token_amount (int): number of units that will be created per token number_of_tokens (int): number of token instances that will be created deploy_service (BlockchainService): the blockchain connection that will deploy participants (list(address)): participant addresses that will receive tokens register (bool): switch to control registration with the raiden Registry contract """ result = list() for _ in range(number_of_tokens): if register: token_address = deploy_service.deploy_and_register_token( registry, contract_name='HumanStandardToken', contract_path=get_contract_path('HumanStandardToken.sol'), constructor_parameters=(token_amount, 'raiden', 2, 'Rd'), ) result.append(token_address) else: token_address = deploy_service.deploy_contract( contract_name='HumanStandardToken', contract_path=get_contract_path('HumanStandardToken.sol'), constructor_parameters=(token_amount, 'raiden', 2, 'Rd'), ) result.append(token_address) # only the creator of the token starts with a balance (deploy_service), # transfer from the creator to the other nodes for transfer_to in participants: deploy_service.token(token_address).transfer( transfer_to, token_amount // len(participants), ) return result
def _token_addresses( token_amount, number_of_tokens, deploy_service, registry, participants, register): """ Deploy `number_of_tokens` ERC20 token instances with `token_amount` minted and distributed among `blockchain_services`. Optionally the instances will be registered with the raiden registry. Args: token_amount (int): number of units that will be created per token number_of_tokens (int): number of token instances that will be created deploy_service (BlockchainService): the blockchain connection that will deploy participants (list(address)): participant addresses that will receive tokens register (bool): switch to control registration with the raiden Registry contract """ result = list() for _ in range(number_of_tokens): if register: token_address = deploy_service.deploy_and_register_token( registry, contract_name='HumanStandardToken', contract_path=get_contract_path('HumanStandardToken.sol'), constructor_parameters=(token_amount, 'raiden', 2, 'Rd'), ) result.append(token_address) else: token_address = deploy_service.deploy_contract( contract_name='HumanStandardToken', contract_path=get_contract_path('HumanStandardToken.sol'), constructor_parameters=(token_amount, 'raiden', 2, 'Rd'), ) result.append(token_address) # only the creator of the token starts with a balance (deploy_service), # transfer from the creator to the other nodes for transfer_to in participants: deploy_service.token(token_address).transfer( transfer_to, token_amount // len(participants), ) return result
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: 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( 'Registry', registry_contracts, dict(), tuple(), contract_path=registry_path, timeout=poll_timeout, ) registry_address = registry_proxy.contract_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 deploy_blockchain = BlockChainService( deploy_key, deploy_client, GAS_PRICE, ) deploy_registry = deploy_blockchain.registry(registry_address) host = '0.0.0.0' blockchain_services = list() for privkey in private_keys: rpc_client = JSONRPCClient( host, deploy_client.port, privkey, ) blockchain = BlockChainService( privkey, rpc_client, GAS_PRICE, ) blockchain_services.append(blockchain) return BlockchainServices( deploy_registry, deploy_blockchain, blockchain_services, )
def deploy_nettingchannel_library(deploy_key, tester_chain): netting_library_path = get_contract_path('NettingChannelLibrary.sol') netting_library_compiled = _solidity.compile_contract( netting_library_path, "NettingChannelLibrary") netting_channel_library_address = tester_chain.contract( netting_library_compiled['bin'], language='evm', sender=deploy_key) tester_chain.mine(number_of_blocks=1) return netting_channel_library_address
def endpoint_discovery_services(blockchain_services): discovery_address = blockchain_services.deploy_service.deploy_contract( 'EndpointRegistry', get_contract_path('EndpointRegistry.sol'), ) return [ ContractDiscovery(chain.node_address, chain.discovery(discovery_address)) for chain in blockchain_services.blockchain_services ]
def tester_nettingchannel_library_address(tester_state): netting_library_path = get_contract_path('NettingChannelLibrary.sol') library_address = tester_state.contract( None, path=netting_library_path, language='solidity', contract_name='NettingChannelLibrary', ) tester_state.mine(number_of_blocks=1) return library_address
def f(initial_amount, decimals, token_name, token_symbol): args = [initial_amount, token_name, decimals, token_symbol] contract_path = get_contract_path('HumanStandardToken.sol') compiled = compile_files_cwd([contract_path]) return deploy_client.deploy_solidity_contract( CONTRACT_HUMAN_STANDARD_TOKEN, compiled, constructor_parameters=args, contract_path=contract_path, )
def test_token(): standard_token_path = get_contract_path('StandardToken.sol') human_token_path = get_contract_path('HumanStandardToken.sol') test_chain = tester.Chain() address0 = tester.a0 address1 = tester.a1 standard_token_compiled = _solidity.compile_contract( standard_token_path, "StandardToken" ) standard_token_address = test_chain.contract( standard_token_compiled['bin'], language='evm', sender=tester.k0 ) contract_libraries = { 'StandardToken': hexlify(standard_token_address), } human_token_compiled = _solidity.compile_contract( human_token_path, 'HumanStandardToken', contract_libraries ) ct = ethereum.abi.ContractTranslator(human_token_compiled['abi']) human_token_args = ct.encode_constructor_arguments([10000, 'raiden', 0, 'rd']) human_token_address = test_chain.contract( human_token_compiled['bin'] + human_token_args, language='evm', sender=tester.k0 ) human_token = tester.ABIContract(test_chain, human_token_compiled['abi'], human_token_address) test_chain.mine() # pylint: disable=no-member assert human_token.balanceOf(address0) == 10000 assert human_token.balanceOf(address1) == 0 assert human_token.transfer(address1, 5000) is True assert human_token.balanceOf(address0) == 5000 assert human_token.balanceOf(address1) == 5000
def deploy_nettingchannel_library(deploy_key, tester_state): netting_library_path = get_contract_path('NettingChannelLibrary.sol') netting_channel_library_address = tester_state.contract( None, path=netting_library_path, language='solidity', contract_name='NettingChannelLibrary', sender=deploy_key, ) tester_state.mine(number_of_blocks=1) return netting_channel_library_address
def instantiate(self): with self.lock: if self.is_instantiated: return self.human_standard_token_compiled = get_static_or_compile( get_contract_path('HumanStandardToken.sol'), 'HumanStandardToken', combined='abi', optimize=False, ) self.channel_manager_compiled = get_static_or_compile( get_contract_path('ChannelManagerContract.sol'), 'ChannelManagerContract', combined='abi', optimize=False, ) self.endpoint_registry_compiled = get_static_or_compile( get_contract_path('EndpointRegistry.sol'), 'EndpointRegistry', combined='abi', optimize=False, ) self.netting_channel_compiled = get_static_or_compile( get_contract_path('NettingChannelContract.sol'), 'NettingChannelContract', combined='abi', optimize=False, ) self.registry_compiled = get_static_or_compile( get_contract_path('Registry.sol'), 'Registry', combined='abi', optimize=False, ) self.is_instantiated = True
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 tester_registry_address(tester_state, tester_channelmanager_library_address): registry_path = get_contract_path('Registry.sol') registry_address = tester_state.contract( None, path=registry_path, language='solidity', contract_name='Registry', libraries={ 'ChannelManagerLibrary': tester_channelmanager_library_address.encode('hex') } ) tester_state.mine(number_of_blocks=1) return registry_address
def tester_channelmanager_library_address(tester_state, tester_nettingchannel_library_address): channelmanager_library_path = get_contract_path('ChannelManagerLibrary.sol') manager_address = tester_state.contract( None, path=channelmanager_library_path, language='solidity', contract_name='ChannelManagerLibrary', libraries={ 'NettingChannelLibrary': tester_nettingchannel_library_address.encode('hex'), } ) tester_state.mine(number_of_blocks=1) return manager_address
def load_or_create_smoketest_config(): # get the contract and compiler (if available) versions versions = dict() for file in os.listdir(get_contract_path('')): if file.endswith('.sol'): versions[file] = contract_checksum(get_contract_path(file)) # if solc is available, record its version, too if get_solidity() is not None: solc_version_out, _ = subprocess.Popen( [get_solidity().compiler_available(), '--version'], stdout=subprocess.PIPE ).communicate() versions['solc'] = solc_version_out.split()[-1].decode() smoketest_config_path = os.path.join( get_project_root(), 'smoketest_config.json' ) # try to load an existing smoketest genesis config smoketest_config = dict() if os.path.exists(smoketest_config_path): with open(smoketest_config_path) as handler: smoketest_config = json.load(handler) # if the file versions still fit, return the genesis config (ignore solc if not available) config_matches = [ versions[key] == smoketest_config['versions'][key] for key in versions.keys() ] if all(config_matches): return smoketest_config # something did not fit -- we will create the genesis smoketest_config['versions'] = versions raiden_config, smoketest_genesis = complete_genesis() smoketest_config['genesis'] = smoketest_genesis smoketest_config.update(raiden_config) with open(os.path.join(get_project_root(), 'smoketest_config.json'), 'w') as handler: json.dump(smoketest_config, handler) return smoketest_config
def deploy_nettingchannel_library(deploy_key, tester_chain): netting_library_path = get_contract_path('NettingChannelLibrary.sol') netting_library_compiled = _solidity.compile_contract( netting_library_path, "NettingChannelLibrary" ) netting_channel_library_address = tester_chain.contract( netting_library_compiled['bin'], language='evm', sender=deploy_key ) tester_chain.mine(number_of_blocks=1) return netting_channel_library_address
def test_endpointregistry_gas(private_keys, blockchain_services): chain = blockchain_services.blockchain_services[0] endpointregistry_address = chain.deploy_contract( 'EndpointRegistry', get_contract_path('EndpointRegistry.sol'), ) for i in range(len(private_keys)): chain = blockchain_services.blockchain_services[i] discovery_proxy = chain.discovery(endpointregistry_address) my_address = privatekey_to_address(private_keys[i]) contract_discovery = ContractDiscovery(my_address, discovery_proxy) contract_discovery.register(my_address, '127.0.0.{}'.format(i + 1), 44444) chain.next_block()
def find_dependencies(contract_file): """Resolve solidity dependencies depth first. """ dependencies = [] with open(contract_file) as handler: for line in handler.readlines(): if line.startswith("import"): dependency = line.split()[1].split('"')[1] dependency = dependency.rsplit('/', 1)[-1] if dependency not in dependencies: dependencies.extend(find_dependencies(get_contract_path(dependency))) dependencies.append(dependency) cleaned = [] for dependency in dependencies: if dependency not in cleaned: cleaned.append(dependency) return cleaned
def create_token( self, registry_address, initial_alloc=10 ** 6, name='raidentester', symbol='RDT', decimals=2, timeout=60, 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. 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 with gevent.Timeout(timeout): token_proxy = self._chain.client.deploy_solidity_contract( 'HumanStandardToken', compile_files_cwd([contract_path]), dict(), (initial_alloc, name, decimals, symbol), contract_path=contract_path, ) token_address_hex = encode_hex(token_proxy.contract_address) if auto_register: self.register_token(registry_address, 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_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 endpoint_discovery_services(blockchain_services, cached_genesis): discovery_address = None if cached_genesis and 'defaultDiscoveryAddress' in cached_genesis['config']: discovery_address = address_decoder( cached_genesis['config']['defaultDiscoveryAddress'] ) if discovery_address is None: discovery_address = blockchain_services.deploy_service.deploy_contract( 'EndpointRegistry', get_contract_path('EndpointRegistry.sol'), ) return [ ContractDiscovery(chain.node_address, chain.discovery(discovery_address)) for chain in blockchain_services.blockchain_services ]
def deploy_channelmanager_library(deploy_key, tester_chain, tester_nettingchannel_library_address): channelmanager_library_path = get_contract_path('ChannelManagerLibrary.sol') contract_libraries = { 'NettingChannelLibrary': hexlify(tester_nettingchannel_library_address), } channelmanager_library_compiled = _solidity.compile_contract( channelmanager_library_path, 'ChannelManagerLibrary', contract_libraries ) channelmanager_library_address = tester_chain.contract( channelmanager_library_compiled['bin'], language='evm' ) tester_chain.mine(number_of_blocks=1) return channelmanager_library_address
def deploy_registry(deploy_key, tester_chain, channel_manager_library_address): registry_path = get_contract_path('Registry.sol') contract_libraries = { 'ChannelManagerLibrary': hexlify(channel_manager_library_address), } registry_compiled = _solidity.compile_contract( registry_path, 'Registry', contract_libraries ) registry_address = tester_chain.contract( registry_compiled['bin'], language='evm', sender=deploy_key ) tester_chain.mine(number_of_blocks=1) return registry_address
def validate_solc(): if _solidity.get_solidity() is None: raise RuntimeError( "Couldn't find the solc in the current $PATH.\n" "Make sure the solidity compiler is installed and available on your $PATH." ) try: _solidity.compile_contract( get_contract_path('HumanStandardToken.sol'), 'HumanStandardToken', combined='abi', optimize=False, ) except subprocess.CalledProcessError as e: msg = ( 'The solidity compiler failed to execute. Please make sure that you\n' 'are using the binary version of the compiler (solc-js is not compatible)\n' ) if e.output: msg += ( '\n' 'Output: ' + e.output ) raise RuntimeError(msg) except OSError as e: msg = ( 'The solidity compiler failed to execute. Please make sure the\n' 'binary is compatible with your architecture and you can execute it.' ) child_traceback = getattr(e, 'child_traceback', None) if child_traceback: msg += ( '\n' 'Traceback: ' + child_traceback ) raise RuntimeError(msg)
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 create_and_distribute_token(state, receivers, name=None, amount_per_receiver=1000000): proxy = state.abi_contract( None, path=get_contract_path(TARGETS['token']), language='solidity', listen=False, sender=DEFAULT_KEY, constructor_parameters=( len(receivers) * amount_per_receiver, name, 2, name[:4].upper() ) ) for receiver in receivers: proxy.transfer(receiver, amount_per_receiver) state.mine(number_of_blocks=1) return (name, proxy.address.encode('hex'))
def test_endpointregistry(tester_state, tester_events): account0 = tester.DEFAULT_ACCOUNT sender = account0.encode('hex') endpointregistry_path = get_contract_path('EndpointRegistry.sol') registry_contract = tester_state.abi_contract( None, path=endpointregistry_path, language='solidity', log_listener=tester_events.append, ) registry_contract.registerEndpoint('127.0.0.1:4001') assert registry_contract.findAddressByEndpoint('127.0.0.1:4001') == sender assert registry_contract.findEndpointByAddress(sender) == '127.0.0.1:4001' registry_contract.registerEndpoint('192.168.0.1:4002') assert registry_contract.findAddressByEndpoint('192.168.0.1:4002') == sender assert registry_contract.findEndpointByAddress(sender) == '192.168.0.1:4002' assert len(tester_events) == 2 assert tester_events[0]['_event_type'] == 'AddressRegistered' assert tester_events[1]['_event_type'] == 'AddressRegistered'
def _tester_services(deploy_key, private_keys, tester_blockgas_limit): # calling the fixture directly because we don't want to force all # blockchain_services to instantiate a state tester = tester_chain( deploy_key, private_keys, tester_blockgas_limit, ) tester_registry_address = tester_deploy_contract( tester, deploy_key, contract_name='Registry', contract_path=get_contract_path('Registry.sol'), ) deploy_blockchain = BlockChainServiceTesterMock( deploy_key, tester, ) deploy_registry = deploy_blockchain.registry(tester_registry_address) blockchain_services = list() for privkey in private_keys: blockchain = BlockChainServiceTesterMock( privkey, tester, ) blockchain_services.append(blockchain) return BlockchainServices( deploy_registry, deploy_blockchain, blockchain_services, )