def test_get_and_update_iou():

    request_args = dict(
        url='url',
        token_network_address=factories.UNIT_TOKEN_NETWORK_ADDRESS,
        sender=factories.make_checksum_address(),
        receiver=factories.make_checksum_address(),
    )
    # RequestExceptions should be reraised as ServiceRequestFailed
    with pytest.raises(ServiceRequestFailed):
        with patch.object(requests,
                          'get',
                          side_effect=requests.RequestException):
            get_last_iou(**request_args)

    # invalid JSON should raise a ServiceRequestFailed
    response = Mock()
    response.configure_mock(status_code=200)
    response.json = Mock(side_effect=ValueError)
    with pytest.raises(ServiceRequestFailed):
        with patch.object(requests, 'get', return_value=response):
            get_last_iou(**request_args)

    response = Mock()
    response.configure_mock(status_code=200)
    response.json = Mock(return_value={'other_key': 'other_value'})
    with patch.object(requests, 'get', return_value=response):
        iou = get_last_iou(**request_args)
    assert iou is None, 'get_pfs_iou should return None if pfs returns no iou.'

    response = Mock()
    response.configure_mock(status_code=200)
    last_iou = make_iou(
        config=dict(
            pathfinding_eth_address=to_checksum_address(
                factories.UNIT_TRANSFER_TARGET),
            pathfinding_iou_timeout=500,
            pathfinding_max_fee=100,
        ),
        our_address=factories.UNIT_TRANSFER_INITIATOR,
        privkey=PRIVKEY,
        block_number=10,
    )
    response.json = Mock(return_value=dict(last_iou=last_iou))
    with patch.object(requests, 'get', return_value=response):
        iou = get_last_iou(**request_args)
    assert iou == last_iou

    new_iou_1 = update_iou(iou.copy(), PRIVKEY, added_amount=10)
    assert new_iou_1['amount'] == last_iou['amount'] + 10
    assert all(new_iou_1[k] == iou[k]
               for k in ('expiration_block', 'sender', 'receiver'))
    assert 'signature' in new_iou_1

    new_iou_2 = update_iou(iou, PRIVKEY, expiration_block=45)
    assert new_iou_2['expiration_block'] == 45
    assert all(new_iou_2[k] == iou[k]
               for k in ('amount', 'sender', 'receiver'))
    assert 'signature' in new_iou_2
Beispiel #2
0
def test_api_testnet_token_mint(api_server_test_instance: APIServer,
                                token_addresses):
    user_address = factories.make_checksum_address()
    token_address = token_addresses[0]
    url = api_url_for(api_server_test_instance,
                      "tokensmintresource",
                      token_address=token_address)
    request = grequests.post(url, json=dict(to=user_address, value=1))
    response = request.send().response
    assert_response_with_code(response, HTTPStatus.OK)

    # mint method defaults to mintFor
    request = grequests.post(url, json=dict(to=user_address, value=10))
    response = request.send().response
    assert_response_with_code(response, HTTPStatus.OK)

    # invalid due to negative value
    request = grequests.post(url, json=dict(to=user_address, value=-1))
    response = request.send().response
    assert_response_with_error(response, HTTPStatus.BAD_REQUEST)

    # invalid due to invalid address
    request = grequests.post(url, json=dict(to=user_address[:-2], value=10))
    response = request.send().response
    assert_response_with_error(response, HTTPStatus.BAD_REQUEST)

    # trying to mint with no ETH
    burn_eth(api_server_test_instance.rest_api.raiden_api.raiden.rpc_client)
    request = grequests.post(url, json=dict(to=user_address, value=1))
    response = request.send().response
    assert_response_with_code(response, HTTPStatus.PAYMENT_REQUIRED)
Beispiel #3
0
def test_setup_proxies_no_service_registry_but_pfs():
    """
    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
    """

    network_id = 42
    config = {
        "environment_type": Environment.DEVELOPMENT,
        "chain_id": network_id,
        "services": {}
    }
    contracts = {}
    blockchain_service = MockChain(network_id=network_id,
                                   node_address=make_address())

    with patched_get_for_succesful_pfs_info():
        proxies = setup_proxies_or_exit(
            config=config,
            tokennetwork_registry_contract_address=make_address(),
            secret_registry_contract_address=make_address(),
            endpoint_registry_contract_address=make_address(),
            user_deposit_contract_address=make_address(),
            service_registry_contract_address=None,
            blockchain_service=blockchain_service,
            contracts=contracts,
            routing_mode=RoutingMode.PFS,
            pathfinding_service_address="my-pfs",
            pathfinding_eth_address=make_checksum_address(),
        )
    assert proxies
Beispiel #4
0
def test_setup_proxies_all_addresses_are_known(routing_mode):
    """
    Test that startup for proxies works fine if all addresses are given and routing is basic
    """

    network_id = 42
    config = {
        "environment_type": Environment.DEVELOPMENT,
        "chain_id": network_id,
        "services": {}
    }
    contracts = setup_contracts_or_exit(config, network_id)
    blockchain_service = MockChain(network_id=network_id,
                                   node_address=make_address())

    with patched_get_for_succesful_pfs_info():
        proxies = setup_proxies_or_exit(
            config=config,
            tokennetwork_registry_contract_address=None,
            secret_registry_contract_address=None,
            endpoint_registry_contract_address=None,
            user_deposit_contract_address=None,
            service_registry_contract_address=None,
            blockchain_service=blockchain_service,
            contracts=contracts,
            routing_mode=routing_mode,
            pathfinding_service_address="my-pfs",
            pathfinding_eth_address=make_checksum_address(),
        )
    assert proxies
    assert proxies.token_network_registry
    assert proxies.secret_registry
    assert proxies.user_deposit
    assert proxies.service_registry
def test_get_pfs_iou():
    token_network_address = TokenNetworkAddress(bytes([1] * 20))
    privkey = bytes([2] * 32)
    sender = to_checksum_address(privatekey_to_address(privkey))
    receiver = factories.make_checksum_address()
    with patch('raiden.network.pathfinding.requests.get') as get_mock:
        # No previous IOU
        get_mock.return_value.json.return_value = {'last_iou': None}
        assert get_last_iou('http://example.com', token_network_address,
                            sender, receiver) is None

        # Previous IOU
        iou = dict(sender=sender,
                   receiver=receiver,
                   amount=10,
                   expiration_block=1000)
        iou['signature'] = sign_one_to_n_iou(
            privatekey=encode_hex(privkey),
            sender=sender,
            receiver=receiver,
            amount=iou['amount'],
            expiration=iou['expiration_block'],
        )
        get_mock.return_value.json.return_value = {'last_iou': iou}
        assert get_last_iou('http://example.com', token_network_address,
                            sender, receiver) == iou
Beispiel #6
0
def run_test_mediated_transfer_calls_pfs(raiden_network, token_addresses):
    app0, = raiden_network
    token_address = token_addresses[0]
    chain_state = views.state_from_app(app0)
    payment_network_id = app0.raiden.default_registry.address
    token_network_id = views.get_token_network_identifier_by_token_address(
        chain_state, payment_network_id, token_address)

    with patch("raiden.routing.query_paths",
               return_value=([], None)) as patched:

        app0.raiden.start_mediated_transfer_with_secret(
            token_network_identifier=token_network_id,
            amount=10,
            fee=0,
            target=factories.HOP1,
            identifier=1,
            payment_hash_invoice=EMPTY_PAYMENT_HASH_INVOICE,
            secret=b"1" * 32,
        )
        assert not patched.called

        config_patch = dict(
            pathfinding_service_address="mock-address",
            pathfinding_eth_address=factories.make_checksum_address(),
        )

        with patch.dict(app0.raiden.config["services"], config_patch):
            app0.raiden.start_mediated_transfer_with_secret(
                token_network_identifier=token_network_id,
                amount=11,
                fee=0,
                target=factories.HOP2,
                identifier=2,
                payment_hash_invoice=EMPTY_PAYMENT_HASH_INVOICE,
                secret=b"2" * 32,
            )
            assert patched.call_count == 1

            locked_transfer = factories.create(
                factories.LockedTransferProperties(
                    amount=TokenAmount(5),
                    initiator=factories.HOP1,
                    target=factories.HOP2,
                    sender=factories.HOP1,
                    pkey=factories.HOP1_KEY,
                    token=token_address,
                    canonical_identifier=factories.make_canonical_identifier(
                        token_network_address=token_network_id),
                ))
            app0.raiden.mediate_mediated_transfer(locked_transfer)
            assert patched.call_count == 2
Beispiel #7
0
def run_test_mediated_transfer_calls_pfs(raiden_network, token_addresses):
    app0, = raiden_network
    token_address = token_addresses[0]
    chain_state = views.state_from_app(app0)
    payment_network_id = app0.raiden.default_registry.address
    token_network_id = views.get_token_network_identifier_by_token_address(
        chain_state,
        payment_network_id,
        token_address,
    )

    with patch('raiden.routing.query_paths', return_value=[]) as patched:

        app0.raiden.start_mediated_transfer_with_secret(
            token_network_identifier=token_network_id,
            amount=10,
            fee=0,
            target=factories.HOP1,
            identifier=1,
            secret=b'1' * 32,
        )
        assert not patched.called

        config_patch = dict(
            pathfinding_service_address='mock-address',
            pathfinding_eth_address=factories.make_checksum_address(),
        )

        with patch.dict(app0.raiden.config['services'], config_patch):
            app0.raiden.start_mediated_transfer_with_secret(
                token_network_identifier=token_network_id,
                amount=11,
                fee=0,
                target=factories.HOP2,
                identifier=2,
                secret=b'2' * 32,
            )
            assert patched.call_count == 1

            locked_transfer = factories.make_signed_transfer(
                amount=5,
                initiator=factories.HOP1,
                target=factories.HOP2,
                sender=factories.HOP1,
                pkey=factories.HOP1_KEY,
                token_network_address=token_network_id,
                token=token_address,
            )
            app0.raiden.mediate_mediated_transfer(locked_transfer)
            assert patched.call_count == 2
def test_invalid_instantiation_mediation_pair_state():
    valid = MediationPairState(
        payer_transfer=factories.create(factories.LockedTransferSignedStateProperties()),
        payee_address=factories.make_address(),
        payee_transfer=factories.create(factories.LockedTransferUnsignedStateProperties()),
    )

    unsigned_transfer = factories.create(factories.LockedTransferUnsignedStateProperties())
    with pytest.raises(ValueError):
        replace(valid, payer_transfer=unsigned_transfer)

    signed_transfer = factories.create(factories.LockedTransferSignedStateProperties())
    with pytest.raises(ValueError):
        replace(valid, payee_transfer=signed_transfer)

    hex_instead_of_binary = factories.make_checksum_address()
    with pytest.raises(ValueError):
        replace(valid, payee_address=hex_instead_of_binary)
Beispiel #9
0
    ]

    new_state, channels = factories.create_network(
        token_network_state=token_network_state,
        our_address=our_address,
        routes=routes,
        block_number=10,
    )

    return (new_state, [address1, address2, address3, address4], channels)


CONFIG = {
    "services": {
        "pathfinding_service_address": "my-pfs",
        "pathfinding_eth_address": factories.make_checksum_address(),
        "pathfinding_max_paths": 3,
        "pathfinding_iou_timeout": 10,
        "pathfinding_max_fee": 50,
    }
}

PRIVKEY = b"privkeyprivkeyprivkeyprivkeypriv"


def get_best_routes_with_iou_request_mocked(chain_state,
                                            token_network_state,
                                            from_address,
                                            to_address,
                                            amount,
                                            iou_json_data=None):