예제 #1
0
def test_setup_proxies_all_addresses_are_given():
    """
    Test that startup for proxies works fine if all addresses are given and routing is local
    """
    chain_id = ChainID(5)
    config = RaidenConfig(chain_id=chain_id,
                          environment_type=Environment.DEVELOPMENT)
    contracts = load_deployed_contracts_data(config, chain_id)
    proxy_manager = MockProxyManager(node_address=make_address())

    deployed_addresses = load_deployment_addresses_from_contracts(contracts)
    with patch.object(pathfinding, "get_pfs_info", return_value=PFS_INFO):
        raiden_bundle = raiden_bundle_from_contracts_deployment(
            proxy_manager=proxy_manager,
            token_network_registry_address=deployed_addresses.
            token_network_registry_address,
            secret_registry_address=deployed_addresses.secret_registry_address,
        )
        services_bundle = services_bundle_from_contracts_deployment(
            config=config,
            proxy_manager=proxy_manager,
            deployed_addresses=deployed_addresses,
            routing_mode=RoutingMode.LOCAL,
            pathfinding_service_address="my-pfs",
            enable_monitoring=True,
        )
    assert raiden_bundle
    assert services_bundle
    assert raiden_bundle.token_network_registry
    assert raiden_bundle.secret_registry
    assert services_bundle.user_deposit
    assert not services_bundle.service_registry
예제 #2
0
def test_setup_proxies_no_service_registry_and_no_pfs_address_but_requesting_pfs(
        environment_type):
    """
    Test that if pfs routing mode is requested and no address or service registry is given
    then the client exits with an error message
    """

    chain_id = ChainID(5)
    config = RaidenConfig(
        chain_id=chain_id,
        environment_type=environment_type,
        services=ServiceConfig(pathfinding_max_fee=100,
                               pathfinding_iou_timeout=500,
                               pathfinding_max_paths=5),
    )
    contracts = load_deployed_contracts_data(config, chain_id)
    proxy_manager = MockProxyManager(node_address=make_address())

    with pytest.raises(RaidenError):
        deployed_addresses = load_deployment_addresses_from_contracts(
            contracts)
        with patch.object(pathfinding, "get_pfs_info", return_value=PFS_INFO):
            services_bundle_from_contracts_deployment(
                config=config,
                proxy_manager=proxy_manager,
                deployed_addresses=deployed_addresses,
                routing_mode=RoutingMode.PFS,
                pathfinding_service_address=None,
                enable_monitoring=False,
            )
예제 #3
0
def test_setup_proxies_raiden_addresses_are_given():
    """
    Test that startup for proxies works fine if only raiden addresses are given
    """
    chain_id = ChainID(5)
    config = RaidenConfig(chain_id=chain_id,
                          environment_type=Environment.DEVELOPMENT)
    contracts = load_deployed_contracts_data(config, chain_id)
    proxy_manager = MockProxyManager(node_address=make_address())

    deployed_addresses = load_deployment_addresses_from_contracts(contracts)
    raiden_bundle = raiden_bundle_from_contracts_deployment(
        proxy_manager=proxy_manager,
        token_network_registry_address=deployed_addresses.
        token_network_registry_address,
        secret_registry_address=deployed_addresses.secret_registry_address,
    )
    services_bundle = services_bundle_from_contracts_deployment(
        config=config,
        proxy_manager=proxy_manager,
        deployed_addresses=deployed_addresses,
        routing_mode=RoutingMode.LOCAL,
        pathfinding_service_address=None,
        enable_monitoring=False,
    )
    assert raiden_bundle
    assert services_bundle
    assert raiden_bundle.token_network_registry
    assert raiden_bundle.secret_registry
    assert services_bundle.user_deposit
    assert not services_bundle.service_registry
예제 #4
0
def test_setup_proxies_no_service_registry_but_pfs() -> None:
    """
    Test that if no service registry is provided but a manual pfs address is given then startup
    still works

    Regression test for https://github.com/raiden-network/raiden/issues/3740
    """
    chain_id = ChainID(5)
    config = RaidenConfig(
        chain_id=chain_id,
        environment_type=Environment.DEVELOPMENT,
        services=ServiceConfig(
            pathfinding_max_fee=TokenAmount(100),
            pathfinding_iou_timeout=BlockTimeout(500),
            pathfinding_max_paths=5,
        ),
    )
    config.transport.available_servers = ["http://matrix.example.com"]
    contracts = load_deployed_contracts_data(config, chain_id)
    proxy_manager = MockProxyManager(node_address=make_address())

    PFS_INFO = PFSInfo(
        url="my-pfs",
        price=TokenAmount(12),
        chain_id=ChainID(5),
        token_network_registry_address=TokenNetworkRegistryAddress(
            to_canonical_address(contracts[CONTRACT_TOKEN_NETWORK_REGISTRY]["address"])
        ),
        user_deposit_address=user_deposit_address_test_default,
        confirmed_block_number=BlockNumber(1),
        payment_address=pfs_payment_address_default,
        message="This is your favorite pathfinding service",
        operator="John Doe",
        version="0.0.3",
        matrix_server="http://matrix.example.com",
        matrix_room_id="!room-id:matrix.example.com",
    )
    deployed_addresses = load_deployment_addresses_from_contracts(contracts)
    with patch.object(pathfinding, "get_pfs_info", return_value=PFS_INFO):
        services_bundle = services_bundle_from_contracts_deployment(
            config=config,
            proxy_manager=proxy_manager,  # type: ignore
            deployed_addresses=deployed_addresses,
            routing_mode=RoutingMode.PFS,
            pathfinding_service_address="my-pfs",
            enable_monitoring=True,
        )
    assert services_bundle
예제 #5
0
    def __init__(self,
                 message_handler=None,
                 state_transition=None,
                 private_key=None):
        if private_key is None:
            self.privkey, self.address = factories.make_privkey_address()
        else:
            self.privkey = private_key
            self.address = privatekey_to_address(private_key)

        self.rpc_client = MockJSONRPCClient(self.address)
        self.proxy_manager = MockProxyManager(node_address=self.address)
        self.signer = LocalSigner(self.privkey)

        self.message_handler = message_handler
        self.routing_mode = RoutingMode.PRIVATE
        self.config = RaidenConfig(chain_id=self.rpc_client.chain_id,
                                   environment_type=Environment.DEVELOPMENT)

        self.default_user_deposit = Mock()
        self.default_registry = Mock()
        self.default_registry.address = factories.make_address()
        self.default_one_to_n_address = factories.make_address()
        self.default_msc_address = factories.make_address()

        self.targets_to_identifiers_to_statuses: Dict[Address,
                                                      dict] = defaultdict(dict)
        self.route_to_feedback_token: dict = {}

        if state_transition is None:
            state_transition = node.state_transition

        serializer = JSONSerializer()
        state_manager = StateManager(state_transition, None)
        storage = SerializedSQLiteStorage(":memory:", serializer)
        self.wal = WriteAheadLog(state_manager, storage)

        state_change = ActionInitChain(
            pseudo_random_generator=random.Random(),
            block_number=BlockNumber(0),
            block_hash=factories.make_block_hash(),
            our_address=self.rpc_client.address,
            chain_id=self.rpc_client.chain_id,
        )
        with self.wal.process_state_change_atomically() as dispatcher:
            dispatcher.dispatch(state_change)

        self.transport = Mock()
예제 #6
0
def test_setup_proxies_all_addresses_are_known():
    """
    Test that startup for proxies works fine if all addresses are given and routing is basic
    """
    chain_id = ChainID(5)
    config = RaidenConfig(chain_id=chain_id,
                          environment_type=Environment.DEVELOPMENT)
    config.transport.available_servers = ["http://matrix.example.com"]
    contracts = load_deployed_contracts_data(config, chain_id)
    proxy_manager = MockProxyManager(node_address=make_address())
    PFS_INFO = PFSInfo(
        url="my-pfs",
        price=TokenAmount(12),
        chain_id=ChainID(5),
        token_network_registry_address=to_canonical_address(
            contracts[CONTRACT_TOKEN_NETWORK_REGISTRY]["address"]),
        user_deposit_address=user_deposit_address_test_default,
        payment_address=pfs_payment_address_default,
        confirmed_block_number=BlockNumber(1),
        message="This is your favorite pathfinding service",
        operator="John Doe",
        version="0.0.3",
        matrix_server="http://matrix.example.com",
        matrix_room_id="!room-id:matrix.example.com",
    )
    deployed_addresses = load_deployment_addresses_from_contracts(contracts)
    with patch.object(pathfinding, "get_pfs_info", return_value=PFS_INFO):
        raiden_bundle = raiden_bundle_from_contracts_deployment(
            proxy_manager=proxy_manager,
            token_network_registry_address=deployed_addresses.
            token_network_registry_address,
            secret_registry_address=deployed_addresses.secret_registry_address,
        )
        services_bundle = services_bundle_from_contracts_deployment(
            config=config,
            proxy_manager=proxy_manager,
            deployed_addresses=deployed_addresses,
            routing_mode=RoutingMode.PFS,
            pathfinding_service_address="my-pfs",
            enable_monitoring=False,
        )
    assert raiden_bundle
    assert services_bundle
    assert raiden_bundle.token_network_registry
    assert raiden_bundle.secret_registry
    assert services_bundle.user_deposit
    assert services_bundle.service_registry
예제 #7
0
def load_deployed_contracts_data(config: RaidenConfig, network_id: ChainID) -> Dict[str, Any]:
    """Sets the contract deployment data depending on the network id and environment type

    If an invalid combination of network id and environment type is provided, exits
    the program with an error
    """
    check_raiden_environment(network_id, config.environment_type)

    deployed_contracts_data: Dict[str, Any] = dict()
    contracts_version = RAIDEN_CONTRACT_VERSION

    config.contracts_path = contracts_precompiled_path(contracts_version)

    if network_id in ID_TO_NETWORKNAME and ID_TO_NETWORKNAME[network_id] != "smoketest":
        deployment_data = get_contracts_deployment_info(
            chain_id=network_id, version=contracts_version
        )
        if not deployment_data:
            return deployed_contracts_data

        deployed_contracts_data = deployment_data["contracts"]

    return deployed_contracts_data
예제 #8
0
def test_setup_contracts():
    # Mainnet production: contracts are not deployed
    config = RaidenConfig(chain_id=1, environment_type=Environment.PRODUCTION)
    contracts = load_deployed_contracts_data(config, 1)
    assert config.contracts_path is not None
    assert raiden_contracts_in_data(contracts)
    assert service_contracts_in_data(contracts)

    # Mainnet development -- NOT allowed
    config = RaidenConfig(chain_id=1, environment_type=Environment.DEVELOPMENT)
    with pytest.raises(RaidenError):
        contracts = load_deployed_contracts_data(config, 1)

    # Ropsten production
    config = RaidenConfig(chain_id=3, environment_type=Environment.PRODUCTION)
    contracts = load_deployed_contracts_data(config, 3)
    assert config.contracts_path is not None
    assert raiden_contracts_in_data(contracts)
    assert service_contracts_in_data(contracts)

    # Ropsten development
    config = RaidenConfig(chain_id=3, environment_type=Environment.DEVELOPMENT)
    contracts = load_deployed_contracts_data(config, 3)
    assert config.contracts_path is not None
    assert raiden_contracts_in_data(contracts)
    assert service_contracts_in_data(contracts)

    # Rinkeby production
    config = RaidenConfig(chain_id=4, environment_type=Environment.PRODUCTION)
    contracts = load_deployed_contracts_data(config, 4)
    assert config.contracts_path is not None
    assert raiden_contracts_in_data(contracts)
    assert service_contracts_in_data(contracts)

    # Rinkeby development
    config = RaidenConfig(chain_id=4, environment_type=Environment.DEVELOPMENT)
    contracts = load_deployed_contracts_data(config, 4)
    assert config.contracts_path is not None
    assert raiden_contracts_in_data(contracts)
    assert service_contracts_in_data(contracts)

    # Goerli production
    config = RaidenConfig(chain_id=5, environment_type=Environment.PRODUCTION)
    contracts = load_deployed_contracts_data(config, 5)
    assert config.contracts_path is not None
    assert raiden_contracts_in_data(contracts)
    assert service_contracts_in_data(contracts)

    # Goerli development
    config = RaidenConfig(chain_id=5, environment_type=Environment.DEVELOPMENT)
    contracts = load_deployed_contracts_data(config, 5)
    assert config.contracts_path is not None
    assert raiden_contracts_in_data(contracts)
    assert service_contracts_in_data(contracts)

    # random private network production
    config = RaidenConfig(chain_id=5257,
                          environment_type=Environment.PRODUCTION)
    contracts = load_deployed_contracts_data(config, 5257)
    assert config.contracts_path is not None
    assert not raiden_contracts_in_data(contracts)
    assert not service_contracts_in_data(contracts)

    # random private network development
    config = RaidenConfig(chain_id=5257,
                          environment_type=Environment.DEVELOPMENT)
    contracts = load_deployed_contracts_data(config, 5257)
    assert config.contracts_path is not None
    assert not raiden_contracts_in_data(contracts)
    assert not service_contracts_in_data(contracts)
def test_monitoring_broadcast_messages(
    local_matrix_servers,
    retry_interval_initial,
    retry_interval_max,
    retries_before_backoff,
    monkeypatch,
    broadcast_rooms,
):
    """
    Test that RaidenService broadcast RequestMonitoring messages to
    MONITORING_BROADCASTING_ROOM room on newly received balance proofs.
    """
    transport = MatrixTransport(
        config=MatrixTransportConfig(
            broadcast_rooms=broadcast_rooms + [MONITORING_BROADCASTING_ROOM],
            retries_before_backoff=retries_before_backoff,
            retry_interval_initial=retry_interval_initial,
            retry_interval_max=retry_interval_max,
            server=local_matrix_servers[0],
            available_servers=[local_matrix_servers[0]],
        ),
        environment=Environment.DEVELOPMENT,
    )
    transport._client.api.retry_timeout = 0
    transport._send_raw = MagicMock()
    raiden_service = MockRaidenService(None)
    raiden_service.config = RaidenConfig(
        chain_id=1234,
        environment_type=Environment.DEVELOPMENT,
        services=ServiceConfig(monitoring_enabled=True),
    )

    transport.start(raiden_service, [], None)

    ms_room_name = make_room_alias(transport.chain_id, MONITORING_BROADCASTING_ROOM)
    ms_room = transport._broadcast_rooms.get(ms_room_name)
    assert isinstance(ms_room, Room)
    ms_room.send_text = MagicMock(spec=ms_room.send_text)

    raiden_service.transport = transport
    transport.log = MagicMock()

    balance_proof = factories.create(HOP1_BALANCE_PROOF)
    channel_state = factories.create(factories.NettingChannelStateProperties())
    channel_state.our_state.balance_proof = balance_proof
    channel_state.partner_state.balance_proof = balance_proof
    monkeypatch.setattr(
        raiden.transfer.views,
        "get_channelstate_by_canonical_identifier",
        lambda *a, **kw: channel_state,
    )
    monkeypatch.setattr(raiden.transfer.channel, "get_balance", lambda *a, **kw: 123)
    raiden_service.user_deposit.effective_balance.return_value = MONITORING_REWARD

    update_monitoring_service_from_balance_proof(
        raiden=raiden_service,
        chain_state=None,
        new_balance_proof=balance_proof,
        non_closing_participant=HOP1,
    )
    gevent.idle()

    with gevent.Timeout(2):
        while ms_room.send_text.call_count < 1:
            gevent.idle()
    assert ms_room.send_text.call_count == 1

    transport.stop()
    transport.greenlet.get()
예제 #10
0
파일: app.py 프로젝트: pinklite/raiden
def run_app(
        address: Address,
        keystore_path: str,
        gas_price: Callable,
        eth_rpc_endpoint: str,
        user_deposit_contract_address: Optional[UserDepositAddress],
        api_address: Endpoint,
        rpc: bool,
        rpccorsdomain: str,
        sync_check: bool,
        console: bool,
        password_file: TextIO,
        web_ui: bool,
        datadir: Optional[str],
        matrix_server: str,
        network_id: ChainID,
        environment_type: Environment,
        unrecoverable_error_should_crash: bool,
        pathfinding_service_address: str,
        pathfinding_max_paths: int,
        enable_monitoring: bool,
        resolver_endpoint: str,
        default_reveal_timeout: BlockTimeout,
        default_settle_timeout: BlockTimeout,
        routing_mode: RoutingMode,
        flat_fee: Tuple[Tuple[TokenAddress, FeeAmount], ...],
        proportional_fee: Tuple[Tuple[TokenAddress, ProportionalFeeAmount],
                                ...],
        proportional_imbalance_fee: Tuple[Tuple[TokenAddress,
                                                ProportionalFeeAmount], ...],
        blockchain_query_interval: float,
        cap_mediation_fees: bool,
        **
    kwargs: Any,  # FIXME: not used here, but still receives stuff in smoketest
) -> App:
    # pylint: disable=too-many-locals,too-many-branches,too-many-statements,unused-argument

    token_network_registry_deployed_at: Optional[BlockNumber]
    smart_contracts_start_at: BlockNumber

    if datadir is None:
        datadir = os.path.join(os.path.expanduser("~"), ".raiden")

    account_manager = AccountManager(keystore_path)
    web3 = Web3(HTTPProvider(rpc_normalized_endpoint(eth_rpc_endpoint)))

    check_sql_version()
    check_ethereum_has_accounts(account_manager)
    check_ethereum_client_is_supported(web3)
    check_ethereum_network_id(network_id, web3)

    address, privatekey = get_account_and_private_key(account_manager, address,
                                                      password_file)

    api_host, api_port = split_endpoint(api_address)

    if not api_port:
        api_port = DEFAULT_HTTP_SERVER_PORT

    domain_list = []
    if rpccorsdomain:
        if "," in rpccorsdomain:
            for domain in rpccorsdomain.split(","):
                domain_list.append(str(domain))
        else:
            domain_list.append(str(rpccorsdomain))

    # Set up config
    fee_config = prepare_mediation_fee_config(
        cli_token_to_flat_fee=flat_fee,
        cli_token_to_proportional_fee=proportional_fee,
        cli_token_to_proportional_imbalance_fee=proportional_imbalance_fee,
        cli_cap_mediation_fees=cap_mediation_fees,
    )
    rest_api_config = RestApiConfig(
        rest_api_enabled=rpc,
        web_ui_enabled=rpc and web_ui,
        cors_domain_list=domain_list,
        eth_rpc_endpoint=eth_rpc_endpoint,
        host=api_host,
        port=api_port,
    )

    config = RaidenConfig(
        chain_id=network_id,
        environment_type=environment_type,
        reveal_timeout=default_reveal_timeout,
        settle_timeout=default_settle_timeout,
        console=console,
        mediation_fees=fee_config,
        unrecoverable_error_should_crash=unrecoverable_error_should_crash,
        resolver_endpoint=resolver_endpoint,
        rest_api=rest_api_config,
    )
    config.blockchain.query_interval = blockchain_query_interval
    config.services.monitoring_enabled = enable_monitoring
    config.services.pathfinding_max_paths = pathfinding_max_paths
    config.transport.server = matrix_server

    contracts = load_deployed_contracts_data(config, network_id)

    rpc_client = JSONRPCClient(
        web3=web3,
        privkey=privatekey,
        gas_price_strategy=gas_price,
        block_num_confirmations=DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS,
    )

    token_network_registry_deployed_at = None
    if "TokenNetworkRegistry" in contracts:
        token_network_registry_deployed_at = BlockNumber(
            contracts[CONTRACT_TOKEN_NETWORK_REGISTRY]["block_number"])

    if token_network_registry_deployed_at is None:
        smart_contracts_start_at = get_smart_contracts_start_at(network_id)
    else:
        smart_contracts_start_at = token_network_registry_deployed_at

    proxy_manager = ProxyManager(
        rpc_client=rpc_client,
        contract_manager=ContractManager(config.contracts_path),
        metadata=ProxyManagerMetadata(
            token_network_registry_deployed_at=
            token_network_registry_deployed_at,
            filters_start_at=smart_contracts_start_at,
        ),
    )

    api_server: Optional[APIServer] = None
    if config.rest_api.rest_api_enabled:
        api_server = start_api_server(rpc_client=rpc_client,
                                      config=config.rest_api,
                                      eth_rpc_endpoint=eth_rpc_endpoint)

    if sync_check:
        check_synced(rpc_client)

    # The user has the option to launch Raiden with a custom
    # user deposit contract address. This can be used to load
    # the addresses for the rest of the deployed contracts.
    # The steps done here make sure that if a UDC address is provided,
    # the address has to be valid and all the connected contracts
    # are configured properly.
    # If a UDC address was not provided, Raiden would fall back
    # to using the ones deployed and provided by the raiden-contracts package.
    if user_deposit_contract_address is not None:
        if not is_address(user_deposit_contract_address):
            raise RaidenError("The user deposit address is invalid")

        deployed_addresses = load_deployment_addresses_from_udc(
            proxy_manager=proxy_manager,
            user_deposit_address=user_deposit_contract_address,
            block_identifier=BLOCK_ID_LATEST,
        )
    else:
        deployed_addresses = load_deployment_addresses_from_contracts(
            contracts=contracts)

    # Load the available matrix servers when no matrix server is given
    # The list is used in a PFS check
    if config.transport.server == MATRIX_AUTO_SELECT_SERVER:
        fetch_available_matrix_servers(config.transport, environment_type)

    raiden_bundle = raiden_bundle_from_contracts_deployment(
        proxy_manager=proxy_manager,
        token_network_registry_address=deployed_addresses.
        token_network_registry_address,
        secret_registry_address=deployed_addresses.secret_registry_address,
    )

    services_bundle = services_bundle_from_contracts_deployment(
        config=config,
        deployed_addresses=deployed_addresses,
        proxy_manager=proxy_manager,
        routing_mode=routing_mode,
        pathfinding_service_address=pathfinding_service_address,
        enable_monitoring=enable_monitoring,
    )

    check_ethereum_confirmed_block_is_not_pruned(
        jsonrpc_client=rpc_client,
        secret_registry=raiden_bundle.secret_registry,
        confirmation_blocks=config.blockchain.confirmation_blocks,
    )

    database_path = Path(
        os.path.join(
            datadir,
            f"node_{pex(address)}",
            f"netid_{network_id}",
            f"network_{pex(raiden_bundle.token_network_registry.address)}",
            f"v{RAIDEN_DB_VERSION}_log.db",
        ))
    config.database_path = database_path

    print(f"Raiden is running in {environment_type.value.lower()} mode")
    print("\nYou are connected to the '{}' network and the DB path is: {}".
          format(ID_TO_CHAINNAME.get(network_id, network_id), database_path))

    matrix_transport = setup_matrix(config.transport, config.services,
                                    environment_type, routing_mode)

    event_handler: EventHandler = RaidenEventHandler()

    # User should be told how to set fees, if using default fee settings
    log.debug("Fee Settings", fee_settings=fee_config)
    has_default_fees = (len(fee_config.token_to_flat_fee) == 0
                        and len(fee_config.token_to_proportional_fee) == 0
                        and len(fee_config.token_to_proportional_imbalance_fee)
                        == 0)
    if has_default_fees:
        click.secho(
            "Default fee settings are used. "
            "If you want use Raiden with mediation fees - flat, proportional and imbalance fees - "
            "see https://raiden-network.readthedocs.io/en/latest/overview_and_guide.html#firing-it-up",  # noqa: E501
            fg="yellow",
        )

    # Only send feedback when PFS is used
    if routing_mode == RoutingMode.PFS:
        event_handler = PFSFeedbackEventHandler(event_handler)

    message_handler = MessageHandler()

    one_to_n_address = (services_bundle.one_to_n.address
                        if services_bundle.one_to_n is not None else None)
    monitoring_service_address = (services_bundle.monitoring_service.address
                                  if services_bundle.monitoring_service
                                  is not None else None)
    raiden_app = App(
        config=config,
        rpc_client=rpc_client,
        proxy_manager=proxy_manager,
        query_start_block=smart_contracts_start_at,
        default_registry=raiden_bundle.token_network_registry,
        default_secret_registry=raiden_bundle.secret_registry,
        default_service_registry=services_bundle.service_registry,
        default_user_deposit=services_bundle.user_deposit,
        default_one_to_n_address=one_to_n_address,
        default_msc_address=monitoring_service_address,
        transport=matrix_transport,
        raiden_event_handler=event_handler,
        message_handler=message_handler,
        routing_mode=routing_mode,
        api_server=api_server,
    )

    raiden_app.start()

    return raiden_app
예제 #11
0
def services_bundle_from_contracts_deployment(
    config: RaidenConfig,
    proxy_manager: ProxyManager,
    routing_mode: RoutingMode,
    deployed_addresses: DeploymentAddresses,
    pathfinding_service_address: str,
    enable_monitoring: bool,
) -> ServicesBundle:
    """
    Initialize and setup the contract proxies.

    Depending on the provided contract addresses via the CLI, the routing mode,
    the environment type and the network id try to initialize the proxies.
    Returns the initialized proxies or exits the application with an error if
    there is a problem.

    Also depending on the given arguments populate config with PFS related settings
    """
    node_network_id = config.chain_id
    environment_type = config.environment_type

    user_deposit_address = deployed_addresses.user_deposit_address
    service_registry_address = deployed_addresses.service_registry_address
    token_network_registry_address = deployed_addresses.token_network_registry_address

    contractname_address: List[Tuple[str, Address, Callable]] = [
        ("user_deposit", Address(user_deposit_address), proxy_manager.user_deposit)
    ]
    if routing_mode == RoutingMode.PFS:
        contractname_address.append(
            ("service_registry", Address(service_registry_address), proxy_manager.service_registry)
        )
    if enable_monitoring or routing_mode == RoutingMode.PFS:
        contractname_address.append(
            (
                "monitoring_service",
                Address(deployed_addresses.monitoring_service_address),
                proxy_manager.monitoring_service,
            )
        )
        contractname_address.append(
            ("one_to_n", Address(deployed_addresses.one_to_n_address), proxy_manager.one_to_n)
        )

    proxies = dict()

    for contractname, address, constructor in contractname_address:
        try:
            proxy = constructor(address)
        except ContractCodeMismatch as e:
            handle_contract_code_mismatch(e)
        except AddressWithoutCode:
            handle_contract_no_code(contractname, address)
        except AddressWrongContract:
            handle_contract_wrong_address(contractname, address)

        proxies[contractname] = proxy

    if routing_mode == RoutingMode.PFS:
        check_pfs_configuration(pathfinding_service_address=pathfinding_service_address)

        pfs_info = configure_pfs_or_exit(
            pfs_url=pathfinding_service_address,
            routing_mode=routing_mode,
            service_registry=proxies["service_registry"],
            node_network_id=node_network_id,
            token_network_registry_address=TokenNetworkRegistryAddress(
                token_network_registry_address
            ),
            pathfinding_max_fee=config.services.pathfinding_max_fee,
        )
        msg = "Eth address of selected pathfinding service is unknown."
        assert pfs_info.payment_address is not None, msg

        # Only check that PFS is registered in production mode
        if environment_type == Environment.PRODUCTION:
            check_pfs_for_production(
                service_registry=proxies["service_registry"], pfs_info=pfs_info
            )

        config.pfs_config = PFSConfig(
            info=pfs_info,
            maximum_fee=config.services.pathfinding_max_fee,
            iou_timeout=config.services.pathfinding_iou_timeout,
            max_paths=config.services.pathfinding_max_paths,
        )
    else:
        config.pfs_config = None

    return ServicesBundle(
        user_deposit=cast(UserDeposit, proxies.get("user_deposit")),
        service_registry=cast(ServiceRegistry, proxies.get("service_registry")),
        monitoring_service=cast(MonitoringService, proxies.get("monitoring_service")),
        one_to_n=cast(OneToN, proxies.get("one_to_n")),
    )
예제 #12
0
def create_apps(
    chain_id: ChainID,
    contracts_path: Path,
    blockchain_services: BlockchainServices,
    token_network_registry_address: TokenNetworkRegistryAddress,
    one_to_n_address: Optional[OneToNAddress],
    secret_registry_address: SecretRegistryAddress,
    service_registry_address: Optional[ServiceRegistryAddress],
    user_deposit_address: Optional[UserDepositAddress],
    monitoring_service_contract_address: MonitoringServiceAddress,
    reveal_timeout: BlockTimeout,
    settle_timeout: BlockTimeout,
    database_basedir: str,
    retry_interval_initial: float,
    retry_interval_max: float,
    retries_before_backoff: int,
    environment_type: Environment,
    unrecoverable_error_should_crash: bool,
    local_matrix_url: Optional[ParsedURL],
    broadcast_rooms: List[str],
    routing_mode: RoutingMode,
    blockchain_query_interval: float,
    resolver_ports: List[Optional[int]],
    enable_rest_api: bool,
    port_generator: Iterator[Port],
    capabilities_config: CapabilitiesConfig,
) -> List[App]:
    """ Create the apps."""
    # pylint: disable=too-many-locals
    services = blockchain_services

    apps = []
    for idx, proxy_manager in enumerate(services):
        database_path = database_from_privatekey(base_dir=database_basedir,
                                                 app_number=idx)
        assert len(resolver_ports) > idx
        resolver_port = resolver_ports[idx]

        config = RaidenConfig(
            chain_id=chain_id,
            environment_type=environment_type,
            unrecoverable_error_should_crash=unrecoverable_error_should_crash,
            reveal_timeout=reveal_timeout,
            settle_timeout=settle_timeout,
            contracts_path=contracts_path,
            database_path=database_path,
            blockchain=BlockchainConfig(
                confirmation_blocks=DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS,
                query_interval=blockchain_query_interval,
            ),
            mediation_fees=MediationFeeConfig(),
            services=ServiceConfig(monitoring_enabled=False),
            rest_api=RestApiConfig(rest_api_enabled=enable_rest_api,
                                   host=Host("localhost"),
                                   port=next(port_generator)),
            console=False,
            transport_type="matrix",
        )
        config.transport.capabilities_config = capabilities_config

        if local_matrix_url is not None:
            config.transport = MatrixTransportConfig(
                broadcast_rooms=broadcast_rooms,
                retries_before_backoff=retries_before_backoff,
                retry_interval_initial=retry_interval_initial,
                retry_interval_max=retry_interval_max,
                server=local_matrix_url,
                available_servers=[],
                capabilities_config=capabilities_config,
            )

        assert config.transport.capabilities_config is not None
        if resolver_port is not None:
            config.resolver_endpoint = f"http://localhost:{resolver_port}"

        registry = proxy_manager.token_network_registry(
            token_network_registry_address, block_identifier=BLOCK_ID_LATEST)
        secret_registry = proxy_manager.secret_registry(
            secret_registry_address, block_identifier=BLOCK_ID_LATEST)

        service_registry = None
        if service_registry_address:
            service_registry = proxy_manager.service_registry(
                service_registry_address, block_identifier=BLOCK_ID_LATEST)

        user_deposit = None
        if user_deposit_address:
            user_deposit = proxy_manager.user_deposit(
                user_deposit_address, block_identifier=BLOCK_ID_LATEST)

        # Use `TestMatrixTransport` that saves sent messages for assertions in tests
        assert config.transport.capabilities_config is not None
        transport = TestMatrixTransport(config=config.transport,
                                        environment=environment_type)

        raiden_event_handler = RaidenEventHandler()
        hold_handler = HoldRaidenEventHandler(raiden_event_handler)
        message_handler = WaitForMessage()

        api_server = None
        if enable_rest_api:
            api_server = start_api_server(rpc_client=proxy_manager.client,
                                          config=config.rest_api,
                                          eth_rpc_endpoint="bla")

        app = App(
            config=config,
            rpc_client=proxy_manager.client,
            proxy_manager=proxy_manager,
            query_start_block=BlockNumber(0),
            default_registry=registry,
            default_secret_registry=secret_registry,
            default_service_registry=service_registry,
            default_user_deposit=user_deposit,
            default_one_to_n_address=one_to_n_address,
            default_msc_address=monitoring_service_contract_address,
            transport=transport,
            raiden_event_handler=hold_handler,
            message_handler=message_handler,
            routing_mode=routing_mode,
            api_server=api_server,
        )
        apps.append(app)

    return apps