示例#1
0
def test_mediator_task_view():
    """Same as above for mediator tasks."""
    secret1 = factories.make_secret(1)
    locked_amount1 = 11
    payee_transfer = factories.create(
        factories.LockedTransferUnsignedStateProperties(secret=secret1))
    payer_transfer = factories.create(
        factories.LockedTransferSignedStateProperties(
            secret=secret1, payment_identifier=1,
            locked_amount=locked_amount1))
    secrethash1 = payee_transfer.lock.secrethash
    initiator = payee_transfer.initiator
    initiator_channel = factories.create(
        factories.NettingChannelStateProperties(
            partner_state=factories.NettingChannelEndStateProperties(
                address=initiator, balance=100)))
    routes = [factories.make_route_from_channel(initiator_channel)]
    transfer_state1 = MediatorTransferState(secrethash=secrethash1,
                                            routes=routes)
    transfer_state1.transfers_pair.append(
        MediationPairState(
            payer_transfer=payer_transfer,
            payee_transfer=payee_transfer,
            payee_address=payee_transfer.target,
        ))
    task1 = MediatorTask(
        token_network_identifier=factories.UNIT_TOKEN_NETWORK_ADDRESS,
        mediator_state=transfer_state1,
    )

    secret2 = factories.make_secret(2)
    locked_amount2 = 13
    transfer2 = factories.create(
        factories.LockedTransferSignedStateProperties(
            secret=secret2, payment_identifier=2,
            locked_amount=locked_amount2))
    secrethash2 = transfer2.lock.secrethash
    transfer_state2 = MediatorTransferState(secrethash=secrethash2,
                                            routes=routes)
    transfer_state2.waiting_transfer = WaitingTransferState(transfer=transfer2)
    task2 = MediatorTask(
        token_network_identifier=factories.UNIT_TOKEN_NETWORK_ADDRESS,
        mediator_state=transfer_state2,
    )

    payment_mapping = {secrethash1: task1, secrethash2: task2}
    view = transfer_tasks_view(payment_mapping)

    assert len(view) == 2
    if view[0].get("payment_identifier") == "1":
        pending_transfer, waiting_transfer = view
    else:
        waiting_transfer, pending_transfer = view

    assert pending_transfer.get("role") == waiting_transfer.get(
        "role") == "mediator"
    assert pending_transfer.get("payment_identifier") == "1"
    assert waiting_transfer.get("payment_identifier") == "2"
    assert pending_transfer.get("locked_amount") == str(locked_amount1)
    assert waiting_transfer.get("locked_amount") == str(locked_amount2)
示例#2
0
def test_get_secret():
    secret1 = factories.make_secret()
    secret2 = factories.make_secret()
    secrethash3 = factories.make_keccak_hash()
    secrethash4 = factories.make_keccak_hash()

    lock_state = HashTimeLockState(amount=10,
                                   expiration=10,
                                   secrethash=factories.UNIT_SECRETHASH)
    end_state = factories.create(factories.NettingChannelEndStateProperties())
    end_state = factories.replace(
        end_state,
        secrethashes_to_lockedlocks={secrethash3: lock_state},
        secrethashes_to_unlockedlocks={
            sha3(secret1): UnlockPartialProofState(lock=lock_state,
                                                   secret=secret1)
        },
        secrethashes_to_onchain_unlockedlocks={
            sha3(secret2): UnlockPartialProofState(lock=lock_state,
                                                   secret=secret2)
        },
    )

    assert get_secret(
        end_state,
        sha3(secret1)) == secret1  # known secret from offchain unlock
    assert get_secret(
        end_state,
        sha3(secret2)) == secret2  # known secret from offchain unlock
    assert get_secret(end_state,
                      secrethash3) is None  # known lock but not unlocked yet
    assert get_secret(end_state, secrethash4) is None  # unknown secrethash
示例#3
0
文件: test_api.py 项目: sekmet/raiden
def test_mediator_task_view():
    """Same as above for mediator tasks."""
    secret1 = factories.make_secret(1)
    locked_amount1 = TokenAmount(11)
    payee_transfer = factories.create(
        factories.LockedTransferUnsignedStateProperties(secret=secret1))
    payer_transfer = factories.create(
        factories.LockedTransferSignedStateProperties(
            secret=secret1,
            payment_identifier=PaymentID(1),
            locked_amount=locked_amount1))
    secrethash1 = payee_transfer.lock.secrethash
    route_state = RouteState(route=[payee_transfer.target])

    transfer_state1 = MediatorTransferState(secrethash=secrethash1,
                                            routes=[route_state])
    # pylint: disable=E1101
    transfer_state1.transfers_pair.append(
        MediationPairState(
            payer_transfer=payer_transfer,
            payee_transfer=payee_transfer,
            payee_address=payee_transfer.target,
        ))
    task1 = MediatorTask(
        token_network_address=factories.UNIT_TOKEN_NETWORK_ADDRESS,
        mediator_state=transfer_state1)

    secret2 = factories.make_secret(2)
    locked_amount2 = TokenAmount(13)
    transfer2 = factories.create(
        factories.LockedTransferSignedStateProperties(
            secret=secret2,
            payment_identifier=PaymentID(2),
            locked_amount=locked_amount2))
    secrethash2 = transfer2.lock.secrethash
    transfer_state2 = MediatorTransferState(secrethash=secrethash2,
                                            routes=[route_state])
    transfer_state2.waiting_transfer = WaitingTransferState(transfer=transfer2)
    task2 = MediatorTask(
        token_network_address=factories.UNIT_TOKEN_NETWORK_ADDRESS,
        mediator_state=transfer_state2)

    payment_mapping = {
        secrethash1: cast(TransferTask, task1),
        secrethash2: cast(TransferTask, task2),
    }
    view = transfer_tasks_view(payment_mapping)

    assert len(view) == 2
    if view[0].get("payment_identifier") == "1":
        pending_transfer, waiting_transfer = view
    else:
        waiting_transfer, pending_transfer = view

    assert pending_transfer.get("role") == waiting_transfer.get(
        "role") == "mediator"
    assert pending_transfer.get("payment_identifier") == "1"
    assert waiting_transfer.get("payment_identifier") == "2"
    assert pending_transfer.get("locked_amount") == str(locked_amount1)
    assert waiting_transfer.get("locked_amount") == str(locked_amount2)
示例#4
0
def make_signed_transfer_from_counter(counter):
    lock = Lock(
        amount=next(counter),
        expiration=next(counter),
        secrethash=sha3(factories.make_secret(next(counter))),
    )

    signed_transfer = factories.make_signed_transfer(
        amount=next(counter),
        initiator=factories.make_address(),
        target=factories.make_address(),
        expiration=next(counter),
        secret=factories.make_secret(next(counter)),
        payment_identifier=next(counter),
        message_identifier=next(counter),
        nonce=next(counter),
        transferred_amount=next(counter),
        locked_amount=next(counter),
        locksroot=sha3(lock.as_bytes),
        recipient=factories.make_address(),
        channel_identifier=next(counter),
        token_network_address=factories.make_address(),
        token=factories.make_address(),
        pkey=factories.HOP1_KEY,
        sender=factories.HOP1,
    )

    return signed_transfer
示例#5
0
def test_register_secret_happy_path(secret_registry_proxy: SecretRegistry,
                                    contract_manager):
    """Test happy path of SecretRegistry with a single secret.

    Test that `register_secret` changes the smart contract state by registering
    the secret, this can be verified by the block height and the existence of
    the SecretRegistered event.
    """
    secret = make_secret()
    secrethash = keccak(secret)
    secret_unregistered = make_secret()
    secrethash_unregistered = keccak(secret_unregistered)

    secret_registered_filter = secret_registry_proxy.secret_registered_filter()

    assert not secret_registry_proxy.is_secret_registered(
        secrethash=secrethash, block_identifier="latest"
    ), "Test setup is invalid, secret must be unknown"
    assert not secret_registry_proxy.is_secret_registered(
        secrethash=secrethash_unregistered, block_identifier="latest"
    ), "Test setup is invalid, secret must be unknown"

    chain = BlockChainService(jsonrpc_client=secret_registry_proxy.client,
                              contract_manager=contract_manager)
    chain.wait_until_block(STATE_PRUNING_AFTER_BLOCKS + 1)

    with pytest.raises(NoStateForBlockIdentifier):
        secret_registry_proxy.is_secret_registered(
            secrethash=secrethash_unregistered, block_identifier=0)

    secret_registry_proxy.register_secret(secret=secret)

    logs = [
        secret_registry_proxy.proxy.decode_event(encoded_log)
        for encoded_log in secret_registered_filter.get_all_entries()
    ]
    secret_registered = must_have_event(logs, {
        "event": "SecretRevealed",
        "args": {
            "secrethash": secrethash
        }
    })

    msg = "SecretRegistry.register_secret returned but the SecretRevealed event was not emitted."
    assert secret_registered, msg

    registered_block = secret_registry_proxy.get_secret_registration_block_by_secrethash(
        secrethash=secrethash, block_identifier="latest")
    msg = (
        "Block height returned by the SecretRegistry.get_secret_registration_block_by_secrethash "
        "does not match the block from the SecretRevealed event.")
    assert secret_registered["blockNumber"] == registered_block, msg

    block = secret_registry_proxy.get_secret_registration_block_by_secrethash(
        secrethash=secrethash_unregistered, block_identifier="latest")
    assert block is None, "The secret that was not registered must not change block height!"
示例#6
0
def secret_registry_batch_happy_path(secret_registry_proxy, block_identifier):
    secrets = [make_secret() for i in range(4)]
    secrethashes = [keccak(secret) for secret in secrets]

    secret_registered_filter = secret_registry_proxy.secret_registered_filter()
    secret_registry_proxy.register_secret_batch(
        secrets=secrets,
        given_block_identifier=block_identifier,
    )

    logs = [
        secret_registry_proxy.proxy.decode_event(log)
        for log in secret_registered_filter.get_all_entries()
    ]

    for secrethash in secrethashes:
        secret_registered = must_have_event(
            logs,
            {
                'event': 'SecretRevealed',
                'args': {
                    'secrethash': secrethash,
                },
            },
        )
        assert secret_registered, 'All secrets from the batch must be registered'

        block = secret_registry_proxy.get_secret_registration_block_by_secrethash(
            secrethash=secrethash,
            block_identifier='latest',
        )
        msg = 'Block number reported by the proxy and the event must match'
        assert block == secret_registered['blockNumber'], msg
示例#7
0
def test_target_task_view():
    """Same as above for target tasks."""
    secret = factories.make_secret()
    transfer = factories.create(
        factories.LockedTransferSignedStateProperties(secret=secret))
    secrethash = transfer.lock.secrethash
    mediator = factories.make_address()
    mediator_channel = factories.create(
        factories.NettingChannelStateProperties(
            partner_state=factories.NettingChannelEndStateProperties(
                address=mediator, balance=100)))
    transfer_state = TargetTransferState(route=None,
                                         transfer=transfer,
                                         secret=secret)
    task = TargetTask(
        canonical_identifier=mediator_channel.canonical_identifier,
        target_state=transfer_state)
    payment_mapping = {secrethash: task}

    view = transfer_tasks_view(payment_mapping)

    assert len(view) == 1
    pending_transfer = view[0]
    assert pending_transfer.get("role") == "target"
    assert pending_transfer.get("locked_amount") == str(
        transfer.balance_proof.locked_amount)
    assert pending_transfer.get("payment_identifier") == str(
        transfer.payment_identifier)
def secret_registry_batch_happy_path(
        proxy_manager: ProxyManager,
        secret_registry_proxy: SecretRegistry) -> None:
    secrets = [make_secret() for i in range(4)]
    secrethashes = [sha256_secrethash(secret) for secret in secrets]

    secret_registry_proxy.register_secret_batch(secrets=secrets)

    logs = get_secret_registry_events(
        proxy_manager=proxy_manager,
        secret_registry_address=secret_registry_proxy.address,
        contract_manager=secret_registry_proxy.contract_manager,
    )

    for secrethash in secrethashes:
        secret_registered = must_have_event(logs, {
            "event": "SecretRevealed",
            "args": {
                "secrethash": secrethash
            }
        })
        assert secret_registered, "All secrets from the batch must be registered"

        block = secret_registry_proxy.get_secret_registration_block_by_secrethash(
            secrethash=secrethash, block_identifier="latest")
        msg = "Block number reported by the proxy and the event must match"
        assert block == secret_registered["block_number"], msg
示例#9
0
def secret_registry_batch_happy_path(secret_registry_proxy):
    secrets = [make_secret() for i in range(4)]
    secrethashes = [keccak(secret) for secret in secrets]

    secret_registered_filter = secret_registry_proxy.secret_registered_filter()
    secret_registry_proxy.register_secret_batch(secrets=secrets)

    logs = [
        secret_registry_proxy.proxy.decode_event(log)
        for log in secret_registered_filter.get_all_entries()
    ]

    for secrethash in secrethashes:
        secret_registered = must_have_event(logs, {
            "event": "SecretRevealed",
            "args": {
                "secrethash": secrethash
            }
        })
        assert secret_registered, "All secrets from the batch must be registered"

        block = secret_registry_proxy.get_secret_registration_block_by_secrethash(
            secrethash=secrethash, block_identifier="latest")
        msg = "Block number reported by the proxy and the event must match"
        assert block == secret_registered["blockNumber"], msg
示例#10
0
def test_channel_withdraw(
    raiden_network: List[App],
    token_addresses: List[TokenAddress],
    deposit: TokenAmount,
    retry_timeout: float,
) -> None:
    """ Withdraw funds after a mediated transfer."""
    alice_app, bob_app = raiden_network
    token_address = token_addresses[0]
    token_network_address = views.get_token_network_address_by_token_address(
        views.state_from_app(alice_app), alice_app.raiden.default_registry.address, token_address
    )
    assert token_network_address

    token_proxy = bob_app.raiden.proxy_manager.token(token_address, BLOCK_ID_LATEST)
    bob_initial_balance = token_proxy.balance_of(bob_app.raiden.address)

    message_handler = WaitForMessage()
    bob_app.raiden.message_handler = message_handler

    alice_to_bob_amount = PaymentAmount(10)
    identifier = PaymentID(1)
    target = TargetAddress(bob_app.raiden.address)
    secret = factories.make_secret()

    payment_status = alice_app.raiden.start_mediated_transfer_with_secret(
        token_network_address=token_network_address,
        amount=alice_to_bob_amount,
        target=target,
        identifier=identifier,
        secret=secret,
    )
    wait_for_unlock = bob_app.raiden.message_handler.wait_for_message(
        Unlock, {"payment_identifier": identifier}
    )
    with block_offset_timeout(alice_app.raiden):
        wait_for_unlock.get()
        msg = (
            f"transfer from {to_checksum_address(alice_app.raiden.address)} "
            f"to {to_checksum_address(bob_app.raiden.address)} failed."
        )
        assert payment_status.payment_done.get(), msg

    total_withdraw = WithdrawAmount(deposit + alice_to_bob_amount)

    bob_alice_channel_state = get_channelstate(bob_app, alice_app, token_network_address)
    bob_app.raiden.withdraw(
        canonical_identifier=bob_alice_channel_state.canonical_identifier,
        total_withdraw=total_withdraw,
    )

    waiting.wait_for_withdraw_complete(
        raiden=bob_app.raiden,
        canonical_identifier=bob_alice_channel_state.canonical_identifier,
        total_withdraw=total_withdraw,
        retry_timeout=retry_timeout,
    )

    bob_balance_after_withdraw = token_proxy.balance_of(bob_app.raiden.address)
    assert bob_initial_balance + total_withdraw == bob_balance_after_withdraw
示例#11
0
def test_secret_registry(secret_registry_proxy):
    #  register secret
    secret = make_secret()
    event_filter = secret_registry_proxy.secret_registered_filter()
    secret_registry_proxy.register_secret(secret=secret, given_block_identifier='latest')

    # check if event is raised
    logs = event_filter.get_all_entries()
    assert len(logs) == 1
    decoded_event = secret_registry_proxy.proxy.decode_event(logs[0])
    data = keccak(secret)
    assert decoded_event['args']['secrethash'] == data
    # check if registration block matches
    block = secret_registry_proxy.get_register_block_for_secrethash(
        secrethash=data,
        block_identifier='latest',
    )
    assert logs[0]['blockNumber'] == block

    #  test non-existing secret
    block = secret_registry_proxy.get_register_block_for_secrethash(
        secrethash=b'\x11' * 32,
        block_identifier='latest',
    )
    assert 0 == block
示例#12
0
def test_target_task_view():
    """Same as above for target tasks."""
    secret = factories.make_secret()
    transfer = factories.create(
        factories.LockedTransferSignedStateProperties(
            transfer=factories.LockedTransferProperties(secret=secret), ))
    secrethash = transfer.lock.secrethash
    mediator = factories.make_address()
    mediator_channel = factories.create(
        factories.NettingChannelStateProperties(
            partner_state=factories.NettingChannelEndStateProperties(
                address=mediator, balance=100), ))
    transfer_state = TargetTransferState(route=None,
                                         transfer=transfer,
                                         secret=secret)
    task = TargetTask(
        token_network_identifier=factories.UNIT_TOKEN_NETWORK_ADDRESS,
        channel_identifier=mediator_channel.identifier,
        target_state=transfer_state,
    )
    payment_mapping = {secrethash: task}

    view = transfer_tasks_view(payment_mapping)

    assert len(view) == 1
    pending_transfer = view[0]
    assert pending_transfer.get('role') == 'target'
    assert pending_transfer.get('locked_amount') == str(
        transfer.balance_proof.locked_amount)
    assert pending_transfer.get('payment_identifier') == str(
        transfer.payment_identifier)
示例#13
0
def test_target_task_view():
    """Same as above for target tasks."""
    secret = factories.make_secret()
    transfer = factories.create(
        factories.LockedTransferSignedStateProperties(secret=secret))
    secrethash = transfer.lock.secrethash
    mediator = factories.make_address()
    mediator_channel = factories.create(
        factories.NettingChannelStateProperties(
            partner_state=factories.NettingChannelEndStateProperties(
                address=mediator, balance=TokenAmount(100))))
    transfer_state = TargetTransferState(
        from_hop=HopState(
            channel_identifier=mediator_channel.canonical_identifier.
            channel_identifier,
            node_address=mediator,
        ),
        transfer=transfer,
        secret=secret,
    )
    task = TargetTask(
        canonical_identifier=mediator_channel.canonical_identifier,
        target_state=transfer_state)
    payment_mapping = {secrethash: cast(TransferTask, task)}

    view = transfer_tasks_view(payment_mapping)

    assert len(view) == 1
    pending_transfer = view[0]
    assert pending_transfer.get("role") == "target"
    # pylint: disable=no-member
    assert pending_transfer.get("locked_amount") == str(
        transfer.balance_proof.locked_amount)
    assert pending_transfer.get("payment_identifier") == str(
        transfer.payment_identifier)
示例#14
0
def make_from_route_from_counter(counter):
    from_channel = factories.make_channel(
        partner_balance=next(counter),
        partner_address=factories.HOP1,
        token_address=factories.make_address(),
        channel_identifier=next(counter),
    )
    from_route = factories.route_from_channel(from_channel)

    expiration = factories.UNIT_REVEAL_TIMEOUT + 1

    from_transfer = factories.make_signed_transfer_for(
        from_channel,
        factories.LockedTransferSignedStateProperties(
            transfer=factories.LockedTransferProperties(
                balance_proof=factories.BalanceProofProperties(
                    transferred_amount=0,
                    token_network_identifier=from_channel.token_network_identifier,
                ),
                amount=1,
                expiration=expiration,
                secret=sha3(factories.make_secret(next(counter))),
                initiator=factories.make_address(),
                target=factories.make_address(),
                payment_identifier=next(counter),
            ),
            sender=factories.HOP1,
            pkey=factories.HOP1_KEY,
        ),
    )
    return from_route, from_transfer
示例#15
0
def make_transfer_from_counter(counter):
    return factories.make_transfer(
        amount=next(counter),
        initiator=factories.make_address(),
        target=factories.make_address(),
        expiration=next(counter),
        secret=factories.make_secret(next(counter)),
    )
示例#16
0
def _transfer_expired(
    initiator_app: App,
    target_app: App,
    token_address: TokenAddress,
    amount: PaymentAmount,
    identifier: PaymentID,
    fee: FeeAmount = 0,
    timeout: Optional[float] = None,
) -> None:
    assert identifier is not None, "The identifier must be provided"
    assert isinstance(target_app.raiden.message_handler, WaitForMessage)

    # This timeout has to be larger then the lock expiration. The lock
    # expiration unit is block numbers, and its value is defined relative to
    # the node's reveal timeout configuration. For the integration tests the
    # reveal timeout is chosen proportionally to the number of nodes, 90
    # seconds is a rough default that should work with the standard
    # configuration.
    if timeout is None:
        timeout = 90

    secret = make_secret()
    secrethash = sha3(secret)

    wait_for_remove_expired_lock = target_app.raiden.message_handler.wait_for_message(
        LockExpired, {"secrethash": secrethash})

    payment_network_identifier = initiator_app.raiden.default_registry.address
    token_network_identifier = views.get_token_network_identifier_by_token_address(
        chain_state=views.state_from_app(initiator_app),
        payment_network_id=payment_network_identifier,
        token_address=token_address,
    )
    payment_status = initiator_app.raiden.start_mediated_transfer_with_secret(
        token_network_identifier=token_network_identifier,
        amount=amount,
        fee=fee,
        target=target_app.raiden.address,
        identifier=identifier,
        payment_hash_invoice=EMPTY_PAYMENT_HASH_INVOICE,
        secret=secret,
        secrethash=secrethash,
    )

    with Timeout(seconds=timeout):
        wait_for_remove_expired_lock.get()
        msg = (f"transfer from {pex(initiator_app.raiden.address)} "
               f"to {pex(target_app.raiden.address)} did not expire.")
        assert payment_status.payment_done.get() is False, msg
def test_secret_registry_register_batch(secret_registry_proxy):
    secrets = [make_secret() for i in range(4)]
    secrethashes = [keccak(secret) for secret in secrets]

    event_filter = secret_registry_proxy.secret_registered_filter()
    secret_registry_proxy.register_secret_batch(secrets)

    logs = event_filter.get_all_entries()
    assert len(logs) == 4

    block = secret_registry_proxy.get_register_block_for_secrethash(secrethashes[0])
    decoded_events = [secret_registry_proxy.proxy.decode_event(log) for log in logs]
    assert all(event['blockNumber'] == block for event in decoded_events)

    recovered_hashes = [event['args']['secrethash'] for event in decoded_events]
    assert all(secrethash in recovered_hashes for secrethash in secrethashes)
示例#18
0
def test_message_ack_timing_keeper():
    matk = MessageAckTimingKeeper()

    matk.add_message(RevealSecret(MessageID(1), make_signature(), make_secret()))

    gevent.sleep(0.05)
    matk.finalize_message(Processed(MessageID(1), make_signature()))

    assert len(matk._durations) == 1
    assert 0.05 <= matk._durations[0] <= 0.06

    # Set duration to a fixed value
    matk._durations[0] = 0.05

    report = matk.generate_report()
    assert len(report) == 1
    assert report == [0.05]
示例#19
0
def test_concurrent_access(secret_registry_proxy_patched, ):
    """Test if multiple greenlets actually send only one transaction
    when registering a secret.
    This is done by patchin secret_registry_proxy to forbid more than
    one call to `_register_secret_batch`.
    """
    secret = make_secret()
    # Spawn multiple greenlets registrering a single secret
    # Patched secret registry asserts that the on-chain registry call
    # is only called once.
    events = [
        gevent.spawn(
            secret_registry_proxy_patched.register_secret,
            secret,
        ) for _ in range(0, 40)
    ]
    gevent.joinall(events)
示例#20
0
def make_signed_balance_proof_from_counter(counter):
    lock = Lock(
        amount=next(counter),
        expiration=next(counter),
        secrethash=sha3(factories.make_secret(next(counter))),
    )
    lock_expired_balance_proof = factories.make_signed_balance_proof(
        nonce=next(counter),
        transferred_amount=next(counter),
        locked_amount=next(counter),
        token_network_address=factories.make_address(),
        channel_identifier=next(counter),
        locksroot=sha3(lock.as_bytes),
        extra_hash=sha3(b''),
        private_key=factories.HOP1_KEY,
        sender_address=factories.HOP1,
    )

    return lock_expired_balance_proof
示例#21
0
def test_lock_expiry(raiden_network, token_addresses, deposit):
    """Test lock expiry and removal."""
    alice_app, bob_app = raiden_network
    token_address = token_addresses[0]
    token_network_identifier = views.get_token_network_identifier_by_token_address(
        views.state_from_app(alice_app),
        alice_app.raiden.default_registry.address,
        token_address,
    )

    hold_event_handler = HoldOffChainSecretRequest()
    wait_message_handler = WaitForMessage()
    bob_app.raiden.message_handler = wait_message_handler
    bob_app.raiden.raiden_event_handler = hold_event_handler

    token_network = views.get_token_network_by_identifier(
        views.state_from_app(alice_app),
        token_network_identifier,
    )

    channel_state = get_channelstate(alice_app, bob_app, token_network_identifier)
    channel_identifier = channel_state.identifier

    assert channel_identifier in token_network.partneraddresses_to_channelidentifiers[
        bob_app.raiden.address
    ]

    alice_to_bob_amount = 10
    identifier = 1
    target = bob_app.raiden.address
    transfer_1_secret = factories.make_secret(0)
    transfer_1_secrethash = sha3(transfer_1_secret)
    transfer_2_secret = factories.make_secret(1)
    transfer_2_secrethash = sha3(transfer_2_secret)

    hold_event_handler.hold_secretrequest_for(secrethash=transfer_1_secrethash)
    transfer1_received = wait_message_handler.wait_for_message(
        LockedTransfer,
        {'lock': {'secrethash': transfer_1_secrethash}},
    )
    transfer2_received = wait_message_handler.wait_for_message(
        LockedTransfer,
        {'lock': {'secrethash': transfer_2_secrethash}},
    )
    remove_expired_lock_received = wait_message_handler.wait_for_message(
        LockExpired,
        {'secrethash': transfer_1_secrethash},
    )

    alice_app.raiden.start_mediated_transfer_with_secret(
        token_network_identifier,
        alice_to_bob_amount,
        target,
        identifier,
        transfer_1_secret,
    )
    transfer1_received.wait()

    alice_bob_channel_state = get_channelstate(alice_app, bob_app, token_network_identifier)
    lock = channel.get_lock(alice_bob_channel_state.our_state, transfer_1_secrethash)

    # This is the current state of the protocol:
    #
    #    A -> B LockedTransfer
    #    B -> A SecretRequest
    #    - protocol didn't continue
    assert_synced_channel_state(
        token_network_identifier,
        alice_app, deposit, [lock],
        bob_app, deposit, [],
    )

    # Verify lock is registered in both channel states
    alice_channel_state = get_channelstate(alice_app, bob_app, token_network_identifier)
    assert transfer_1_secrethash in alice_channel_state.our_state.secrethashes_to_lockedlocks

    bob_channel_state = get_channelstate(bob_app, alice_app, token_network_identifier)
    assert transfer_1_secrethash in bob_channel_state.partner_state.secrethashes_to_lockedlocks

    alice_chain_state = views.state_from_raiden(alice_app.raiden)
    assert transfer_1_secrethash in alice_chain_state.payment_mapping.secrethashes_to_task

    remove_expired_lock_received.wait()

    alice_channel_state = get_channelstate(alice_app, bob_app, token_network_identifier)
    assert transfer_1_secrethash not in alice_channel_state.our_state.secrethashes_to_lockedlocks

    # Verify Bob received the message and processed the LockExpired message
    bob_channel_state = get_channelstate(bob_app, alice_app, token_network_identifier)
    assert transfer_1_secrethash not in bob_channel_state.partner_state.secrethashes_to_lockedlocks

    alice_chain_state = views.state_from_raiden(alice_app.raiden)
    assert transfer_1_secrethash not in alice_chain_state.payment_mapping.secrethashes_to_task

    # Make another transfer
    alice_to_bob_amount = 10
    identifier = 2

    hold_event_handler.hold_secretrequest_for(secrethash=transfer_2_secrethash)

    alice_app.raiden.start_mediated_transfer_with_secret(
        token_network_identifier,
        alice_to_bob_amount,
        target,
        identifier,
        transfer_2_secret,
    )
    transfer2_received.wait()

    # Make sure the other transfer still exists
    alice_chain_state = views.state_from_raiden(alice_app.raiden)
    assert transfer_2_secrethash in alice_chain_state.payment_mapping.secrethashes_to_task

    bob_channel_state = get_channelstate(bob_app, alice_app, token_network_identifier)
    assert transfer_2_secrethash in bob_channel_state.partner_state.secrethashes_to_lockedlocks
示例#22
0
def test_get_event_with_balance_proof():
    """ All events which contain a balance proof must be found by when
    querying the database.
    """
    serializer = JSONSerializer
    storage = SQLiteStorage(':memory:', serializer)
    counter = itertools.count()

    lock_expired = SendLockExpired(
        recipient=factories.make_address(),
        message_identifier=next(counter),
        balance_proof=make_balance_proof_from_counter(counter),
        secrethash=sha3(factories.make_secret(next(counter))),
    )
    locked_transfer = SendLockedTransfer(
        recipient=factories.make_address(),
        channel_identifier=factories.make_channel_identifier(),
        message_identifier=next(counter),
        transfer=make_transfer_from_counter(counter),
    )
    balance_proof = SendBalanceProof(
        recipient=factories.make_address(),
        channel_identifier=factories.make_channel_identifier(),
        message_identifier=next(counter),
        payment_identifier=next(counter),
        token_address=factories.make_address(),
        secret=factories.make_secret(next(counter)),
        balance_proof=make_balance_proof_from_counter(counter),
    )
    refund_transfer = SendRefundTransfer(
        recipient=factories.make_address(),
        channel_identifier=factories.make_channel_identifier(),
        message_identifier=next(counter),
        transfer=make_transfer_from_counter(counter),
    )

    events_balanceproofs = [
        (lock_expired, lock_expired.balance_proof),
        (locked_transfer, locked_transfer.balance_proof),
        (balance_proof, balance_proof.balance_proof),
        (refund_transfer, refund_transfer.transfer.balance_proof),
    ]

    timestamp = datetime.utcnow().isoformat(timespec='milliseconds')
    state_change = ''
    for event, _ in events_balanceproofs:
        state_change_identifier = storage.write_state_change(
            state_change,
            timestamp,
        )
        storage.write_events(
            state_change_identifier=state_change_identifier,
            events=[event],
            log_time=timestamp,
        )

    for event, balance_proof in events_balanceproofs:
        event_record = get_event_with_balance_proof_by_balance_hash(
            storage=storage,
            chain_id=balance_proof.chain_id,
            token_network_identifier=balance_proof.token_network_identifier,
            channel_identifier=balance_proof.channel_identifier,
            balance_hash=balance_proof.balance_hash,
        )
        assert event_record.data == event
        # Checking that balance proof attribute can be accessed for all events.
        # Issue https://github.com/raiden-network/raiden/issues/3179
        assert event_record.data.balance_proof == event.balance_proof
示例#23
0
def test_get_state_change_with_balance_proof():
    """ All state changes which contain a balance proof must be found by when
    querying the database.
    """
    serializer = JSONSerializer
    storage = SQLiteStorage(':memory:', serializer)
    counter = itertools.count()

    lock_expired = ReceiveLockExpired(
        balance_proof=make_signed_balance_proof_from_counter(counter),
        secrethash=sha3(factories.make_secret(next(counter))),
        message_identifier=next(counter),
    )
    unlock = ReceiveUnlock(
        message_identifier=next(counter),
        secret=sha3(factories.make_secret(next(counter))),
        balance_proof=make_signed_balance_proof_from_counter(counter),
    )
    transfer_refund = ReceiveTransferRefund(
        transfer=make_signed_transfer_from_counter(counter),
        routes=list(),
    )
    transfer_refund_cancel_route = ReceiveTransferRefundCancelRoute(
        routes=list(),
        transfer=make_signed_transfer_from_counter(counter),
        secret=sha3(factories.make_secret(next(counter))),
    )
    mediator_from_route, mediator_signed_transfer = make_from_route_from_counter(counter)
    action_init_mediator = ActionInitMediator(
        routes=list(),
        from_route=mediator_from_route,
        from_transfer=mediator_signed_transfer,
    )
    target_from_route, target_signed_transfer = make_from_route_from_counter(counter)
    action_init_target = ActionInitTarget(
        route=target_from_route,
        transfer=target_signed_transfer,
    )

    statechanges_balanceproofs = [
        (lock_expired, lock_expired.balance_proof),
        (unlock, unlock.balance_proof),
        (transfer_refund, transfer_refund.transfer.balance_proof),
        (transfer_refund_cancel_route, transfer_refund_cancel_route.transfer.balance_proof),
        (action_init_mediator, action_init_mediator.from_transfer.balance_proof),
        (action_init_target, action_init_target.transfer.balance_proof),
    ]

    timestamp = datetime.utcnow().isoformat(timespec='milliseconds')

    for state_change, _ in statechanges_balanceproofs:
        storage.write_state_change(state_change, timestamp)

    # Make sure state changes are returned in the correct order in which they were stored
    stored_statechanges = storage.get_statechanges_by_identifier(1, 'latest')
    assert isinstance(stored_statechanges[0], ReceiveLockExpired)
    assert isinstance(stored_statechanges[1], ReceiveUnlock)
    assert isinstance(stored_statechanges[2], ReceiveTransferRefund)
    assert isinstance(stored_statechanges[3], ReceiveTransferRefundCancelRoute)
    assert isinstance(stored_statechanges[4], ActionInitMediator)
    assert isinstance(stored_statechanges[5], ActionInitTarget)

    # Make sure state changes are returned in the correct order in which they were stored
    stored_statechanges = storage.get_statechanges_by_identifier(1, 2)
    assert isinstance(stored_statechanges[0], ReceiveLockExpired)
    assert isinstance(stored_statechanges[1], ReceiveUnlock)

    for state_change, balance_proof in statechanges_balanceproofs:
        state_change_record = get_state_change_with_balance_proof_by_balance_hash(
            storage=storage,
            chain_id=balance_proof.chain_id,
            token_network_identifier=balance_proof.token_network_identifier,
            channel_identifier=balance_proof.channel_identifier,
            sender=balance_proof.sender,
            balance_hash=balance_proof.balance_hash,
        )
        assert state_change_record.data == state_change