Пример #1
0
def deploy_all(client):
    patch_send_transaction(client)
    patch_send_message(client)
    deployed = dict()
    deployed.update(deploy_files(RAIDEN_CONTRACT_FILES, client))
    deployed.update(deploy_files(DISCOVERY_CONTRACT_FILES, client))
    return deployed
Пример #2
0
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
Пример #3
0
def main(private_key, eth_amount, targets_file, port, host):
    client = JSONRPCClient(
        host=host,
        port=port,
        privkey=private_key,
        print_communication=False,
    )
    patch_send_transaction(client)
    patch_send_message(client)

    targets = [t.strip() for t in targets_file]
    balance = client.balance(client.sender)

    balance_needed = len(targets) * eth_amount
    if balance_needed * WEI_TO_ETH > balance:
        print(
            "Not enough balance to fund {} accounts with {} eth each. Need {}, have {}"
            .format(len(targets), eth_amount, balance_needed,
                    balance / WEI_TO_ETH))

    print("Sending {} eth to:".format(eth_amount))
    for target in targets:
        print("  - {}".format(target))
        client.send_transaction(sender=client.sender,
                                to=target,
                                value=eth_amount * WEI_TO_ETH)
Пример #4
0
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
Пример #5
0
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
Пример #6
0
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)
Пример #7
0
def connect(host="127.0.0.1",
            port=8545,
            use_ssl=False):
    """Create a jsonrpcclient instance, using the 'zero-privatekey'.
    """
    client = JSONRPCClient(host, port, privkey="1" * 64)
    patch_send_transaction(client)
    return client
Пример #8
0
def connect(host="127.0.0.1",
            port=8545,
            use_ssl=False):
    """Create a jsonrpcclient instance, using the 'zero-privatekey'.
    """
    client = JSONRPCClient(host, port, privkey="1" * 64)
    patch_send_transaction(client)
    return client
Пример #9
0
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)
Пример #10
0
def connect(host='127.0.0.1', port=8545):
    """Create a jsonrpcclient instance, using the 'zero-privatekey'. """
    client = JSONRPCClient(
        host,
        port,
        privkey='1' * 64,
    )
    patch_send_transaction(client)
    patch_send_message(client)
    return client
Пример #11
0
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)
Пример #12
0
def main(privatekey_hex, pretty, gas_price, port):
    slogging.configure(':debug')

    privatekey = decode_hex(privatekey_hex)

    patch_deploy_solidity_contract()
    host = '127.0.0.1'
    client = JSONRPCClient(
        host,
        port,
        privatekey,
    )
    patch_send_transaction(client)
    patch_send_message(client)

    deployed = deploy_all(client, gas_price)
    print(json.dumps(deployed, indent=2 if pretty else None))
Пример #13
0
def main(privatekey_hex, pretty, gas_price, port):
    slogging.configure(":debug")
    # Fix pyethapp.rpc_client not using slogging library
    rpc_logger = logging.getLogger('pyethapp.rpc_client')
    rpc_logger.setLevel(logging.DEBUG)
    rpc_logger.parent = slogging.getLogger()

    privatekey = decode_hex(privatekey_hex)

    patch_deploy_solidity_contract()
    client = JSONRPCClient(
        port=port,
        privkey=privatekey,
        print_communication=False,
    )
    patch_send_transaction(client)
    patch_send_message(client)

    deployed = deploy_all(client, gas_price)
    print(json.dumps(deployed, indent=2 if pretty else None))
Пример #14
0
        name = name_from_file(c)
        proxy = client.deploy_solidity_contract(client.sender,
                                                name,
                                                compiled_contracts,
                                                libraries,
                                                '',
                                                gasprice=denoms.shannon * 20)
        libraries[name] = proxy.address
    return {name: addr.encode('hex') for name, addr in libraries.items()}


def deploy_all(client):
    patch_send_transaction(client)
    deployed = dict()
    deployed.update(deploy_files(RAIDEN_CONTRACT_FILES, client))
    deployed.update(deploy_files(DISCOVERY_CONTRACT_FILES, client))
    return deployed


if __name__ == "__main__":
    # FIXME: client params should be read from cmdline-args!
    pretty = False
    client = JSONRPCClient(
        port=8545,
        privkey='1' * 64,
        print_communication=False,
    )
    patch_send_transaction(client)
    deployed = deploy_all(client)
    print json.dumps(deployed, indent=2 if pretty else None)
Пример #15
0
def geth_create_blockchain(deploy_key,
                           deploy_client,
                           private_keys,
                           blockchain_private_keys,
                           rpc_ports,
                           p2p_ports,
                           base_datadir,
                           verbosity,
                           random_marker,
                           genesis_path=None,
                           logdirectory=None):
    # pylint: disable=too-many-locals,too-many-statements,too-many-arguments,too-many-branches

    nodes_configuration = []
    key_p2p_rpc = zip(blockchain_private_keys, p2p_ports, rpc_ports)

    for pos, (key, p2p_port, rpc_port) in enumerate(key_p2p_rpc):
        config = dict()

        address = privatekey_to_address(key)
        # make the first node miner
        if pos == 0:
            config['unlock'] = 0

        config['nodekey'] = key
        config['nodekeyhex'] = encode_hex(key)
        config['pub'] = encode_hex(privtopub(key))
        config['address'] = address
        config['port'] = p2p_port
        config['rpcport'] = rpc_port
        config['enode'] = 'enode://{pub}@127.0.0.1:{port}'.format(
            pub=config['pub'],
            port=config['port'],
        )
        nodes_configuration.append(config)

    for config in nodes_configuration:
        config['bootnodes'] = ','.join(node['enode']
                                       for node in nodes_configuration)

    all_keys = set(private_keys)
    all_keys.add(deploy_key)
    all_keys = sorted(all_keys)

    cmds = []
    for i, config in enumerate(nodes_configuration):
        # HACK: Use only the first 8 characters to avoid golang's issue
        # https://github.com/golang/go/issues/6895 (IPC bind fails with path
        # longer than 108 characters).
        nodekey_part = config['nodekeyhex'][:8]
        nodedir = os.path.join(base_datadir, nodekey_part)
        node_genesis_path = os.path.join(nodedir, 'custom_genesis.json')

        assert len(nodedir + '/geth.ipc') < 108, 'geth data path is too large'

        os.makedirs(nodedir)

        if genesis_path is None:
            geth_bare_genesis(node_genesis_path, all_keys, random_marker)
        else:
            shutil.copy(genesis_path, node_genesis_path)

        geth_init_datadir(nodedir, node_genesis_path)

        if 'unlock' in config:
            geth_create_account(nodedir, all_keys[i])

        commandline = geth_to_cmd(config, nodedir, verbosity)
        cmds.append(commandline)

    # save current term settings before running geth
    if isinstance(sys.stdin,
                  file):  # check that the test is running on non-capture mode
        term_settings = termios.tcgetattr(sys.stdin)

    stdout = None
    stderr = None
    processes_list = []
    for pos, cmd in enumerate(cmds):
        if logdirectory:
            log_path = os.path.join(logdirectory, str(pos))
            logfile = open(log_path, 'w')

            stdout = logfile
            stderr = logfile

        if '--unlock' in cmd:
            cmd.append('--mine')
            process = subprocess.Popen(
                cmd,
                universal_newlines=True,
                stdin=subprocess.PIPE,
                stdout=stdout,
                stderr=stderr,
            )

            # --password wont work, write password to unlock
            process.stdin.write(DEFAULT_PASSPHRASE + os.linesep)  # Passphrase:
            process.stdin.write(DEFAULT_PASSPHRASE +
                                os.linesep)  # Repeat passphrase:
        else:
            process = subprocess.Popen(
                cmd,
                universal_newlines=True,
                stdout=stdout,
                stderr=stderr,
            )

        processes_list.append(process)

    geth_wait_and_check(deploy_client, private_keys, random_marker)
    patch_send_transaction(deploy_client)

    # reenter echo mode (disabled by geth pasphrase prompt)
    if isinstance(sys.stdin, file):
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, term_settings)

    for process in processes_list:
        process.poll()

        if process.returncode is not None:
            raise ValueError('geth failed to start')

    return processes_list
Пример #16
0
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
Пример #17
0
def app(address,
        keystore_path,
        eth_rpc_endpoint,
        registry_contract_address,
        discovery_contract_address,
        listen_address,
        rpccorsdomain,  # pylint: disable=unused-argument
        mapped_socket,
        logging,
        logfile,
        log_json,
        max_unresponsive_time,
        send_ping_time,
        api_address,
        rpc,
        console,
        password_file,
        web_ui,
        datadir,
        eth_client_communication):

    from raiden.app import App
    from raiden.network.rpc.client import BlockChainService

    # config_file = args.config_file
    (listen_host, listen_port) = split_endpoint(listen_address)
    (api_host, api_port) = split_endpoint(api_address)

    config = App.DEFAULT_CONFIG.copy()
    config['host'] = listen_host
    config['port'] = listen_port
    config['console'] = console
    config['rpc'] = rpc
    config['web_ui'] = rpc and web_ui
    config['api_host'] = api_host
    config['api_port'] = api_port

    if mapped_socket:
        config['socket'] = mapped_socket.socket
        config['external_ip'] = mapped_socket.external_ip
        config['external_port'] = mapped_socket.external_port
    else:
        config['socket'] = None
        config['external_ip'] = listen_host
        config['external_port'] = listen_port

    retries = max_unresponsive_time / DEFAULT_NAT_KEEPALIVE_RETRIES
    config['protocol']['nat_keepalive_retries'] = retries
    config['protocol']['nat_keepalive_timeout'] = send_ping_time

    address_hex = address_encoder(address) if address else None
    address_hex, privatekey_bin = prompt_account(address_hex, keystore_path, password_file)

    privatekey_hex = privatekey_bin.encode('hex')
    config['privatekey_hex'] = privatekey_hex

    endpoint = eth_rpc_endpoint

    # Fallback default port if only an IP address is given
    rpc_port = 8545
    if eth_rpc_endpoint.startswith("http://"):
        endpoint = eth_rpc_endpoint[len("http://"):]
        rpc_port = 80
    elif eth_rpc_endpoint.startswith("https://"):
        endpoint = eth_rpc_endpoint[len("https://"):]
        rpc_port = 443

    if ':' not in endpoint:  # no port was given in url
        rpc_host = endpoint
    else:
        rpc_host, rpc_port = split_endpoint(endpoint)

    rpc_client = JSONRPCClient(
        privkey=privatekey_bin,
        host=rpc_host,
        port=rpc_port,
        print_communication=eth_client_communication,
    )

    # this assumes the eth node is already online
    patch_send_transaction(rpc_client)
    patch_send_message(rpc_client)

    try:
        blockchain_service = BlockChainService(
            privatekey_bin,
            registry_contract_address,
            rpc_client,
        )
    except ValueError as e:
        # ValueError exception raised if:
        # - The registry contract address doesn't have code, this might happen
        # if the connected geth process is not synced or if the wrong address
        # is provided (e.g. using the address from a smart contract deployed on
        # ropsten with a geth node connected to morden)
        print(e.message)
        sys.exit(1)

    discovery_tx_cost = GAS_PRICE * DISCOVERY_REGISTRATION_GAS
    while True:
        balance = blockchain_service.client.balance(address_hex)
        if discovery_tx_cost <= balance:
            break
        print(
            'Account has insufficient funds for discovery registration.\n'
            'Needed: {} ETH\n'
            'Available: {} ETH.\n'
            'Please deposit additional funds on this account.'
            .format(discovery_tx_cost / float(denoms.ether), balance / float(denoms.ether))
        )
        if not click.confirm('Try again?'):
            sys.exit(1)

    discovery = ContractDiscovery(
        blockchain_service.node_address,
        blockchain_service.discovery(discovery_contract_address)
    )

    if datadir is None:
        # default database directory
        raiden_directory = os.path.join(os.path.expanduser('~'), '.raiden')
    else:
        raiden_directory = datadir

    if not os.path.exists(raiden_directory):
        os.makedirs(raiden_directory)
    user_db_dir = os.path.join(raiden_directory, address_hex[:8])
    if not os.path.exists(user_db_dir):
        os.makedirs(user_db_dir)
    database_path = os.path.join(user_db_dir, 'log.db')
    config['database_path'] = database_path

    return App(config, blockchain_service, discovery)
Пример #18
0
def deploy_all(client):
    patch_send_transaction(client)
    deployed = dict()
    deployed.update(deploy_files(RAIDEN_CONTRACT_FILES, client))
    deployed.update(deploy_files(DISCOVERY_CONTRACT_FILES, client))
    return deployed
Пример #19
0
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
Пример #20
0
def app(address, keystore_path, eth_rpc_endpoint, registry_contract_address,
        discovery_contract_address, listen_address, rpccorsdomain,
        mapped_socket, logging, logfile, log_json, max_unresponsive_time,
        send_ping_time, api_address, rpc, sync_check, console, password_file,
        web_ui, datadir, eth_client_communication, nat):

    # pylint: disable=too-many-locals,too-many-branches,too-many-statements,unused-argument

    from raiden.app import App
    from raiden.network.rpc.client import BlockChainService

    (listen_host, listen_port) = split_endpoint(listen_address)
    (api_host, api_port) = split_endpoint(api_address)

    config = App.DEFAULT_CONFIG.copy()
    config['host'] = listen_host
    config['port'] = listen_port
    config['console'] = console
    config['rpc'] = rpc
    config['web_ui'] = rpc and web_ui
    config['api_host'] = api_host
    config['api_port'] = api_port

    if mapped_socket:
        config['socket'] = mapped_socket.socket
        config['external_ip'] = mapped_socket.external_ip
        config['external_port'] = mapped_socket.external_port
    else:
        config['socket'] = None
        config['external_ip'] = listen_host
        config['external_port'] = listen_port

    config['protocol']['nat_keepalive_retries'] = DEFAULT_NAT_KEEPALIVE_RETRIES
    timeout = max_unresponsive_time / DEFAULT_NAT_KEEPALIVE_RETRIES
    config['protocol']['nat_keepalive_timeout'] = timeout

    address_hex = address_encoder(address) if address else None
    address_hex, privatekey_bin = prompt_account(address_hex, keystore_path,
                                                 password_file)

    privatekey_hex = privatekey_bin.encode('hex')
    config['privatekey_hex'] = privatekey_hex

    endpoint = eth_rpc_endpoint

    # Fallback default port if only an IP address is given
    rpc_port = 8545
    if eth_rpc_endpoint.startswith("http://"):
        endpoint = eth_rpc_endpoint[len("http://"):]
        rpc_port = 80
    elif eth_rpc_endpoint.startswith("https://"):
        endpoint = eth_rpc_endpoint[len("https://"):]
        rpc_port = 443

    if ':' not in endpoint:  # no port was given in url
        rpc_host = endpoint
    else:
        rpc_host, rpc_port = split_endpoint(endpoint)

    rpc_client = JSONRPCClient(
        privkey=privatekey_bin,
        host=rpc_host,
        port=rpc_port,
        print_communication=eth_client_communication,
    )

    # this assumes the eth node is already online
    patch_send_transaction(rpc_client)
    patch_send_message(rpc_client)

    try:
        blockchain_service = BlockChainService(
            privatekey_bin,
            rpc_client,
        )
    except ValueError as e:
        # ValueError exception raised if:
        # - The registry contract address doesn't have code, this might happen
        # if the connected geth process is not synced or if the wrong address
        # is provided (e.g. using the address from a smart contract deployed on
        # ropsten with a geth node connected to morden)
        print(e.message)
        sys.exit(1)

    if sync_check:
        try:
            net_id = int(blockchain_service.client.call('net_version'))
            network = ID_TO_NETWORKNAME[net_id]
        except:  # pylint: disable=bare-except
            print(
                "Couldn't determine the network the ethereum node is connected to.\n"
                "Because of this there is not way to determine the latest\n"
                "block with an oracle, and the events from the ethereum\n"
                "node cannot be trusted. Giving up.\n")
            sys.exit(1)

        url = ETHERSCAN_API.format(
            network=network,
            action='eth_blockNumber',
        )
        wait_for_sync(
            blockchain_service,
            url=url,
            tolerance=ORACLE_BLOCKNUMBER_DRIFT_TOLERANCE,
            sleep=3,
        )

    discovery_tx_cost = GAS_PRICE * DISCOVERY_REGISTRATION_GAS
    while True:
        balance = blockchain_service.client.balance(address_hex)
        if discovery_tx_cost <= balance:
            break
        print('Account has insufficient funds for discovery registration.\n'
              'Needed: {} ETH\n'
              'Available: {} ETH.\n'
              'Please deposit additional funds on this account.'.format(
                  discovery_tx_cost / float(denoms.ether),
                  balance / float(denoms.ether)))
        if not click.confirm('Try again?'):
            sys.exit(1)

    registry = blockchain_service.registry(registry_contract_address, )

    discovery = ContractDiscovery(
        blockchain_service.node_address,
        blockchain_service.discovery(discovery_contract_address))

    if datadir is None:
        # default database directory
        raiden_directory = os.path.join(os.path.expanduser('~'), '.raiden')
    else:
        raiden_directory = datadir

    if not os.path.exists(raiden_directory):
        os.makedirs(raiden_directory)
    user_db_dir = os.path.join(raiden_directory, address_hex[:8])
    if not os.path.exists(user_db_dir):
        os.makedirs(user_db_dir)
    database_path = os.path.join(user_db_dir, 'log.db')
    config['database_path'] = database_path

    return App(
        config,
        blockchain_service,
        registry,
        discovery,
    )
Пример #21
0
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
Пример #22
0
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
Пример #24
0
def app(address,
        keystore_path,
        eth_rpc_endpoint,
        registry_contract_address,
        discovery_contract_address,
        listen_address,
        rpccorsdomain,
        mapped_socket,
        logging,
        logfile,
        log_json,
        max_unresponsive_time,
        send_ping_time,
        api_address,
        rpc,
        sync_check,
        console,
        password_file,
        web_ui,
        datadir,
        eth_client_communication,
        nat):

    # pylint: disable=too-many-locals,too-many-branches,too-many-statements,unused-argument

    from raiden.app import App
    from raiden.network.rpc.client import BlockChainService

    (listen_host, listen_port) = split_endpoint(listen_address)
    (api_host, api_port) = split_endpoint(api_address)

    config = App.DEFAULT_CONFIG.copy()
    config['host'] = listen_host
    config['port'] = listen_port
    config['console'] = console
    config['rpc'] = rpc
    config['web_ui'] = rpc and web_ui
    config['api_host'] = api_host
    config['api_port'] = api_port

    if mapped_socket:
        config['socket'] = mapped_socket.socket
        config['external_ip'] = mapped_socket.external_ip
        config['external_port'] = mapped_socket.external_port
    else:
        config['socket'] = None
        config['external_ip'] = listen_host
        config['external_port'] = listen_port

    config['protocol']['nat_keepalive_retries'] = DEFAULT_NAT_KEEPALIVE_RETRIES
    timeout = max_unresponsive_time / DEFAULT_NAT_KEEPALIVE_RETRIES
    config['protocol']['nat_keepalive_timeout'] = timeout

    address_hex = address_encoder(address) if address else None
    address_hex, privatekey_bin = prompt_account(address_hex, keystore_path, password_file)
    address = address_decoder(address_hex)

    privatekey_hex = privatekey_bin.encode('hex')
    config['privatekey_hex'] = privatekey_hex

    endpoint = eth_rpc_endpoint

    # Fallback default port if only an IP address is given
    rpc_port = 8545
    if eth_rpc_endpoint.startswith("http://"):
        endpoint = eth_rpc_endpoint[len("http://"):]
        rpc_port = 80
    elif eth_rpc_endpoint.startswith("https://"):
        endpoint = eth_rpc_endpoint[len("https://"):]
        rpc_port = 443

    if ':' not in endpoint:  # no port was given in url
        rpc_host = endpoint
    else:
        rpc_host, rpc_port = split_endpoint(endpoint)

    rpc_client = JSONRPCClient(
        rpc_host,
        rpc_port,
        privatekey_bin,
    )

    # this assumes the eth node is already online
    patch_send_transaction(rpc_client)
    patch_send_message(rpc_client)
    if not check_json_rpc(rpc_client):
        sys.exit(1)

    blockchain_service = BlockChainService(
        privatekey_bin,
        rpc_client,
    )

    if sync_check:
        check_synced(blockchain_service)

    discovery_tx_cost = GAS_PRICE * DISCOVERY_REGISTRATION_GAS
    while True:
        balance = blockchain_service.client.balance(address)
        if discovery_tx_cost <= balance:
            break
        print(
            'Account has insufficient funds for discovery registration.\n'
            'Needed: {} ETH\n'
            'Available: {} ETH.\n'
            'Please deposit additional funds on this account.'
            .format(discovery_tx_cost / float(denoms.ether), balance / float(denoms.ether))
        )
        if not click.confirm('Try again?'):
            sys.exit(1)

    registry = blockchain_service.registry(
        registry_contract_address,
    )

    discovery = ContractDiscovery(
        blockchain_service.node_address,
        blockchain_service.discovery(discovery_contract_address)
    )

    if datadir is None:
        # default database directory
        raiden_directory = os.path.join(os.path.expanduser('~'), '.raiden')
    else:
        raiden_directory = datadir

    if not os.path.exists(raiden_directory):
        os.makedirs(raiden_directory)
    user_db_dir = os.path.join(raiden_directory, address_hex[:8])
    if not os.path.exists(user_db_dir):
        os.makedirs(user_db_dir)
    database_path = os.path.join(user_db_dir, 'log.db')
    config['database_path'] = database_path

    return App(
        config,
        blockchain_service,
        registry,
        discovery,
    )
Пример #25
0
    return deployed


if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('port', type=int)
    parser.add_argument('privatekey')
    parser.add_argument('--pretty', default=False, action='store_true')
    args = parser.parse_args()

    port = args.port
    privatekey_hex = args.privatekey
    privatekey = decode_hex(privatekey_hex)

    pretty = False
    client = JSONRPCClient(
        port=port,
        privkey=privatekey,
        print_communication=False,
    )
    patch_send_transaction(client)
    deployed = deploy_all(client)

    if args.pretty:
        indent = 2
    else:
        indent = None

    print(json.dumps(deployed, indent=indent))