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') 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, 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, 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).encode())) 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 _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, 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 compile_to_data(self, name, path): """Compile a solidity file and return the result data.""" compiled = solidity.compile_file( path, combined='bin,abi,userdoc,devdoc,hashes', extra_args='common={} lib={} permission_management={} system={}'. format(self.contracts_common_dir, self.contracts_lib_dir, self.contracts_perm_dir, self.contracts_sys_dir)) data = solidity.solidity_get_contract_data(compiled, path, name) if not data['bin']: sys.exit(1) return data
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_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 compile_to_data(self, name, path): """Compile a solidity file and return the result data.""" import logging compiled = solidity.compile_file( path, combined='bin,abi,userdoc,devdoc,hashes', extra_args='common={} lib={} interaction={}'.format( self.contracts_common_dir, self.contracts_lib_dir, self.contracts_interaction_dir)) data = solidity.solidity_get_contract_data(compiled, path, name) if not data['bin']: logging.critical( 'The bin of contract %r is empty. Please check it!', name) sys.exit(1) return data
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, list(), constructor_parameters, contract_path=contract_path, 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=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.contract_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, list(), constructor_parameters, contract_path=contract_path, gasprice=GAS_PRICE, timeout=self.poll_timeout, ) return proxy.contract_address
def create_contract(path, args=None, sender=t.k0): t.s.mine() contract_name = path.split('/')[1] contract_name += ':' + contract_name.split('.')[0] path, extra_args = get_dirs(path) if args: args = [ x.address if isinstance(x, t.ABIContract) else x for x in args ] compiler = t.languages['solidity'] combined = _solidity.compile_file(path, combined='bin,abi', optimize=True, extra_args=extra_args) abi = combined[contract_name]['abi'] ct = ContractTranslator(abi) code = combined[contract_name]['bin'] + ( ct.encode_constructor_arguments(args) if args else b'') address = t.s.tx(sender=sender, to=b'', value=0, data=code) return t.ABIContract(t.s, abi, 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.contract_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 init_contracts(nodes): result = dict() tester_state = Chain() for address, contract in CONTRACTS.iteritems(): contract_path = path.join(CONTRACTS_DIR, contract['file']) simple_compiled = compile_file(contract_path) simple_data = solidity_get_contract_data( simple_compiled, contract_path, contract['name'], ) ct = ContractTranslator(simple_data['abi']) if (address == '0x00000000000000000000000000000000013241a3'): extra = (ct.encode_constructor_arguments([nodes[address]]) if nodes[address] else b'') else: extra = (ct.encode_constructor_arguments([nodes[address][0], nodes[address][1]]) if nodes[address] else b'') print(binascii.hexlify(simple_data['bin'] + extra)) abi_address = tester_state.contract(simple_data['bin'] + extra) tester_state.mine() account = tester_state.chain.state.account_to_dict(abi_address) result[address] = {'code': account['code'], 'storage': account['storage'], 'nonce': account['nonce']} return result
def test_abicontract_interface(): """ Test for issue #370. """ tester_state = Chain() 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.contract(simple_data['bin']) # ABIContract class must accept json_abi abi_json = json.dumps(simple_data['abi']).encode('utf-8') abi = ABIContract( _chain=tester_state, _abi=abi_json, address=simple_address, ) assert abi.test() == 1 # pylint: disable=no-member
def tester_deploy_contract(tester_chain, private_key, contract_name, contract_path, constructor_parameters=None): 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(os.path.basename(contract_path))) 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 = unhexlify(hex_bytecode) dependency_contract['bin_hex'] = hex_bytecode dependency_contract['bin'] = bytecode log.info('Creating contract {}'.format(deploy_contract)) contract_address = tester_chain.contract(bytecode, language='evm', sender=private_key) tester_chain.mine(number_of_blocks=1) if len(tester_chain.head_state.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 = unhexlify(hex_bytecode) 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_chain.contract(bytecode, language='evm', sender=private_key) tester_chain.mine(number_of_blocks=1) if len(tester_chain.head_state.get_code(contract_address)) == 0: raise Exception('Contract code empty') return contract_address
SOLIDITY_AVAILABLE = get_solidity() is not None from ethereum import slogging #slogging.configure(':INFO,eth.vm:INFO') #slogging.configure(':DEBUG') # Create the simulated blockchain tester.Chain().chain.config['BLOCK_GAS_LIMIT'] = 31415920000 tester.Chain().chain.config['START_GAS_LIMIT'] = 31415920000 s = tester.Chain() s.mine() benchmark_path = './benchmark.sol' benchmark_name = 'Benchmark' benchmark_compiled = compile_file(benchmark_path) benchmark_data = solidity_get_contract_data( benchmark_compiled, benchmark_path, benchmark_name,) benchmark_address = s.contract(benchmark_data['bin'], language='evm') benchmark_abi = tester.ABIContract( s, benchmark_data['abi'], benchmark_address) # Take a snapshot before trying out test cases s.mine()
from ethereum import slogging #slogging.configure(':INFO,eth.vm:INFO') #slogging.configure(':DEBUG') # Create the simulated blockchain tester.Chain().chain.config['BLOCK_GAS_LIMIT'] = 3141592000 tester.Chain().chain.config['START_GAS_LIMIT'] = 3141592000 s = tester.Chain() s.mine() contract_path = './contractNipopow.sol' contract_name = 'Crosschain' contract_compiled = compile_file(contract_path) contract_data = solidity_get_contract_data( contract_compiled, contract_path, contract_name, ) contract_address = s.contract(contract_data['bin'], language='evm') contract_abi = tester.ABIContract(s, contract_data['abi'], contract_address) import cPickle as pickle proof = pickle.load(open('proof.pkl')) proof_f = pickle.load(open('proof-fork50k.pkl')) proof2 = pickle.load(open('proof-2.pkl'))
def tester_deploy_contract( tester_chain, private_key, contract_name, contract_path, constructor_parameters=None): 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(os.path.basename(contract_path))) 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 = unhexlify(hex_bytecode) dependency_contract['bin_hex'] = hex_bytecode dependency_contract['bin'] = bytecode log.info('Creating contract {}'.format(deploy_contract)) contract_address = tester_chain.contract(bytecode, language='evm', sender=private_key) tester_chain.mine(number_of_blocks=1) if len(tester_chain.head_state.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 = unhexlify(hex_bytecode) 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_chain.contract(bytecode, language='evm', sender=private_key) tester_chain.mine(number_of_blocks=1) if len(tester_chain.head_state.get_code(contract_address)) == 0: raise Exception('Contract code empty') return contract_address
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( 'HumanStandardToken', humantoken_contracts, list(), (total_token, 'raiden', 2, 'Rd'), contract_path=humantoken_path, timeout=poll_timeout, ) registry_path = get_contract_path('Registry.sol') registry_contracts = compile_file(registry_path) registry_proxy = jsonrpc_client.deploy_solidity_contract( 'Registry', registry_contracts, list(), tuple(), contract_path=registry_path, timeout=poll_timeout, ) log_list = jsonrpc_client.rpccall_with_retry( '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', address, token_proxy.contract_address, ) jsonrpc_client.poll(unhexlify(transaction_hash), timeout=poll_timeout) assert len(registry_proxy.call('tokenAddresses')) == 1 log_list = jsonrpc_client.rpccall_with_retry( '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 = to_canonical_address( 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 == to_canonical_address( event['channel_manager_address']) assert token_proxy.contract_address == to_canonical_address( 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, ) jsonrpc_client.poll(unhexlify(transaction_hash), timeout=poll_timeout) log_list = jsonrpc_client.rpccall_with_retry( 'eth_getLogs', { 'fromBlock': '0x0', 'toBlock': 'latest', 'topics': [], }, ) assert len(log_list) == 2
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, list(), (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, list(), 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 = normalize_address(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 == normalize_address(event['channel_manager_address']) assert token_proxy.contract_address == normalize_address(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 _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=GAS_PRICE, 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_LIMIT, 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_LIMIT, GAS_PRICE, ) blockchain_services.append(blockchain) return BlockchainServices( deploy_registry, deploy_blockchain, blockchain_services, )