Example #1
0
def main(  # pylint: disable-msg=too-many-arguments
    private_key: str,
    state_db: str,
    web3: Web3,
    contracts: Dict[str, Contract],
    start_block: BlockNumber,
    confirmations: int,
    host: str,
    service_fee: TokenAmount,
    operator: str,
    info_message: str,
    enable_debug: bool,
    matrix_server: List[str],
) -> int:
    """ The Pathfinding service for the Raiden Network. """
    log.info("Starting Raiden Pathfinding Service")
    log.info("Web3 client", node_address=web3.providers[0].endpoint_uri)
    hex_addresses = {
        name: to_checksum_address(contract.address)
        for name, contract in contracts.items()
    }
    log.info("Contract information",
             addresses=hex_addresses,
             start_block=start_block)

    service = None
    api = None
    try:
        service = PathfindingService(
            web3=web3,
            contracts=contracts,
            sync_start_block=start_block,
            required_confirmations=confirmations,
            private_key=private_key,
            poll_interval=DEFAULT_POLL_INTERVALL,
            db_filename=state_db,
            matrix_servers=matrix_server,
        )

        api = ServiceApi(
            pathfinding_service=service,
            service_fee=service_fee,
            debug_mode=enable_debug,
            one_to_n_address=contracts[CONTRACT_ONE_TO_N].address,
            operator=operator,
            info_message=info_message,
        )
        api.run(host=host)

        service.run()
    except (KeyboardInterrupt, SystemExit):
        print("Exiting...")
    finally:
        log.info("Stopping Pathfinding Service...")
        if api:
            api.stop()
        if service:
            service.stop()

    return 0
Example #2
0
def api_sut(
    pathfinding_service_mock, free_port: int, populate_token_network_case_1: None
) -> Iterator[ServiceApi]:
    api = ServiceApi(pathfinding_service_mock)
    api.run(port=free_port)
    yield api
    api.stop()
Example #3
0
def api_sut_with_debug(
        pathfinding_service_mock,
        free_port: int,
        populate_token_network_case_1,  # pylint: disable=unused-argument
) -> Iterator[ServiceApi]:
    api = ServiceApi(pathfinding_service_mock, debug_mode=True)
    api.run(port=free_port)
    yield api
    api.stop()
Example #4
0
def api_sut(
        pathfinding_service_mock,
        address_to_reachability: Dict[Address, AddressReachability],
        free_port: int,
        populate_token_network_case_1,  # pylint: disable=unused-argument
) -> Iterator[ServiceApi]:
    pathfinding_service_mock.address_to_reachability = address_to_reachability
    api = ServiceApi(pathfinding_service_mock,
                     one_to_n_address=Address(bytes([1] * 20)))
    api.run(port=free_port)
    yield api
    api.stop()
Example #5
0
def main(  # pylint: disable-msg=too-many-arguments
    private_key: str,
    state_db: str,
    web3: Web3,
    contracts: Dict[str, Contract],
    start_block: BlockNumber,
    confirmations: int,
    host: str,
    service_fee: TokenAmount,
    enable_debug: bool,
) -> int:
    """ The Pathfinding service for the Raiden Network. """
    log.info("Starting Raiden Pathfinding Service")

    service = None
    api = None
    try:
        service = PathfindingService(
            web3=web3,
            contracts=contracts,
            sync_start_block=start_block,
            required_confirmations=confirmations,
            private_key=private_key,
            poll_interval=DEFAULT_POLL_INTERVALL,
            db_filename=state_db,
        )

        api = ServiceApi(
            pathfinding_service=service,
            service_fee=service_fee,
            debug_mode=enable_debug,
            one_to_n_address=contracts[CONTRACT_ONE_TO_N].address,
        )
        api.run(host=host)

        service.run()
    except (KeyboardInterrupt, SystemExit):
        print("Exiting...")
    finally:
        log.info("Stopping Pathfinding Service...")
        if api:
            api.stop()
        if service:
            service.stop()

    return 0
Example #6
0
def main(
    private_key: str,
    state_db: str,
    web3: Web3,
    contracts: Dict[str, Contract],
    start_block: BlockNumber,
    confirmations: int,
    host: str,
    service_fee: int,
) -> int:
    """ The Pathfinding service for the Raiden Network. """
    log.info("Starting Raiden Pathfinding Service")

    service = None
    api = None
    try:
        service = PathfindingService(
            web3=web3,
            contracts=contracts,
            sync_start_block=start_block,
            required_confirmations=confirmations,
            private_key=private_key,
            poll_interval=DEFAULT_POLL_INTERVALL,
            db_filename=state_db,
            service_fee=service_fee,
        )

        api = ServiceApi(service)
        api.run(host=host)

        service.run()
    except (KeyboardInterrupt, SystemExit):
        print('Exiting...')
    finally:
        log.info('Stopping Pathfinding Service...')
        if api:
            api.stop()
        if service:
            service.stop()

    return 0
Example #7
0
def test_get_paths_validation(
    api_sut: ServiceApi,
    api_url: str,
    addresses: List[Address],
    token_network_model: TokenNetwork,
    make_iou,
):
    initiator_address = to_checksum_address(addresses[0])
    target_address = to_checksum_address(addresses[1])
    url = api_url + "/" + to_checksum_address(token_network_model.address) + "/paths"
    default_params = {"from": initiator_address, "to": target_address, "value": 5, "max_paths": 3}

    def request_path_with(status_code=400, **kwargs):
        params = default_params.copy()
        params.update(kwargs)
        response = requests.post(url, json=params)
        assert response.status_code == status_code, response.json()
        return response

    response = requests.post(url)
    assert response.status_code == 400
    assert response.json()["errors"].startswith("JSON payload expected")

    for address in ["notanaddress", to_normalized_address(initiator_address)]:
        response = request_path_with(**{"from": address})
        assert response.json()["error_code"] == exceptions.InvalidRequest.error_code
        assert "from" in response.json()["error_details"]

        response = request_path_with(to=address)
        assert response.json()["error_code"] == exceptions.InvalidRequest.error_code
        assert "to" in response.json()["error_details"]

    response = request_path_with(value=-10)
    assert response.json()["error_code"] == exceptions.InvalidRequest.error_code
    assert "value" in response.json()["error_details"]

    response = request_path_with(max_paths=-1)
    assert response.json()["error_code"] == exceptions.InvalidRequest.error_code
    assert "max_paths" in response.json()["error_details"]

    # successful request without payment
    request_path_with(status_code=200)

    # Exemplary test for payment errors. Different errors are serialized the
    # same way in the rest API. Checking for specific errors is tested in
    # payment_tests.
    api_sut.service_fee = TokenAmount(1)
    response = request_path_with()
    assert response.json()["error_code"] == exceptions.MissingIOU.error_code

    # prepare iou for payment tests
    iou = make_iou(
        get_random_privkey(),
        api_sut.pathfinding_service.address,
        one_to_n_address=api_sut.one_to_n_address,
    )
    good_iou_dict = iou.Schema().dump(iou)

    # malformed iou
    bad_iou_dict = good_iou_dict.copy()
    del bad_iou_dict["amount"]
    response = request_path_with(iou=bad_iou_dict)
    assert response.json()["error_code"] == exceptions.InvalidRequest.error_code

    # bad signature
    bad_iou_dict = good_iou_dict.copy()
    bad_iou_dict["signature"] = "0x" + "1" * 130
    response = request_path_with(iou=bad_iou_dict)
    assert response.json()["error_code"] == exceptions.InvalidSignature.error_code

    # with successful payment
    request_path_with(iou=good_iou_dict, status_code=200)
Example #8
0
def test_get_paths_validation(
    api_sut: ServiceApi,
    api_url: str,
    addresses: List[Address],
    token_network_model: TokenNetwork,
    make_iou: Callable,
):
    initiator_address = to_checksum_address(addresses[0])
    target_address = to_checksum_address(addresses[1])
    url = api_url + "/" + to_checksum_address(
        token_network_model.address) + "/paths"
    default_params = {
        "from": initiator_address,
        "to": target_address,
        "value": 5,
        "max_paths": 3
    }

    def request_path_with(status_code=400, **kwargs):
        params = default_params.copy()
        params.update(kwargs)
        response = requests.post(url, json=params)
        assert response.status_code == status_code, response.json()
        return response

    response = requests.post(url)
    assert response.status_code == 400
    assert response.json()["errors"].startswith("JSON payload expected")

    for address in ["notanaddress", to_normalized_address(initiator_address)]:
        response = request_path_with(**{"from": address})
        assert response.json(
        )["error_code"] == exceptions.InvalidRequest.error_code
        assert "from" in response.json()["error_details"]

        response = request_path_with(to=address)
        assert response.json(
        )["error_code"] == exceptions.InvalidRequest.error_code
        assert "to" in response.json()["error_details"]

    response = request_path_with(value=-10)
    assert response.json(
    )["error_code"] == exceptions.InvalidRequest.error_code
    assert "value" in response.json()["error_details"]

    response = request_path_with(max_paths=-1)
    assert response.json(
    )["error_code"] == exceptions.InvalidRequest.error_code
    assert "max_paths" in response.json()["error_details"]

    # successful request without payment
    request_path_with(status_code=200)

    # Exemplary test for payment errors. Different errors are serialized the
    # same way in the rest API. Checking for specific errors is tested in
    # payment_tests.
    api_sut.service_fee = TokenAmount(1)
    response = request_path_with()
    assert response.json()["error_code"] == exceptions.MissingIOU.error_code

    # prepare iou for payment tests
    iou = make_iou(
        get_random_privkey(),
        api_sut.pathfinding_service.address,
        one_to_n_address=api_sut.one_to_n_address,
    )
    good_iou_dict = iou.Schema().dump(iou)

    # malformed iou
    bad_iou_dict = good_iou_dict.copy()
    del bad_iou_dict["amount"]
    response = request_path_with(iou=bad_iou_dict)
    assert response.json(
    )["error_code"] == exceptions.InvalidRequest.error_code

    # malformed iou
    bad_iou_dict = {
        "amount": {
            "_hex": "0x64"
        },
        "chain_id": {
            "_hex": "0x05"
        },
        "expiration_block": {
            "_hex": "0x188cba"
        },
        "one_to_n_address":
        "0x0000000000000000000000000000000000000000",
        "receiver":
        "0x94DEe8e391410A9ebbA791B187df2d993212c849",
        "sender":
        "0x2046F7341f15D0211ca1EBeFb19d029c4Bc4c4e7",
        "signature":
        ("0x0c3066e6a954d660028695f96dfe88cabaf0bc8a385e51781ac4d21003d0b6cd7a8b2"
         "a1134115845655d1a509061f48459cd401565b5df7845c913ed329cd2351b"),
    }
    response = request_path_with(iou=bad_iou_dict)
    assert response.json(
    )["error_code"] == exceptions.InvalidRequest.error_code

    # bad signature
    bad_iou_dict = good_iou_dict.copy()
    bad_iou_dict["signature"] = "0x" + "1" * 130
    response = request_path_with(iou=bad_iou_dict)
    assert response.json(
    )["error_code"] == exceptions.InvalidSignature.error_code

    # with successful payment
    request_path_with(iou=good_iou_dict, status_code=200)