Beispiel #1
0
def test_get_batch_unlock_gain():
    channel_state = factories.create(factories.NettingChannelStateProperties())
    channel_state.our_state = replace(
        channel_state.our_state,
        secrethashes_to_lockedlocks={
            factories.make_secret_hash(): make_hash_time_lock_state(1),
            factories.make_secret_hash(): make_hash_time_lock_state(2),
        },
        secrethashes_to_unlockedlocks={
            factories.make_secret_hash(): make_unlock_partial_proof_state(4)
        },
        secrethashes_to_onchain_unlockedlocks={
            factories.make_secret_hash(): make_unlock_partial_proof_state(8)
        },
    )
    channel_state.partner_state = replace(
        channel_state.partner_state,
        secrethashes_to_lockedlocks={factories.make_secret_hash(): make_hash_time_lock_state(16)},
        secrethashes_to_unlockedlocks={
            factories.make_secret_hash(): make_unlock_partial_proof_state(32)
        },
        secrethashes_to_onchain_unlockedlocks={
            factories.make_secret_hash(): make_unlock_partial_proof_state(64),
            factories.make_secret_hash(): make_unlock_partial_proof_state(128),
        },
    )
    unlock_gain = get_batch_unlock_gain(channel_state)
    assert unlock_gain.from_partner_locks == 192
    assert unlock_gain.from_our_locks == 7
Beispiel #2
0
def make_signed_transfer_from_counter(counter):
    lock = Lock(
        amount=next(counter),
        expiration=next(counter),
        secrethash=factories.make_secret_hash(next(counter)),
    )

    signed_transfer = factories.create(
        factories.LockedTransferSignedStateProperties(
            amount=next(counter),
            initiator=factories.make_initiator_address(),
            target=factories.make_target_address(),
            expiration=next(counter),
            secret=factories.make_secret(next(counter)),
            payment_identifier=next(counter),
            token=factories.make_token_address(),
            nonce=next(counter),
            transferred_amount=next(counter),
            locked_amount=next(counter),
            locksroot=sha3(lock.as_bytes),
            canonical_identifier=factories.make_canonical_identifier(
                token_network_address=factories.make_address(),
                channel_identifier=next(counter)),
            recipient=factories.make_address(),
            sender=factories.HOP1,
            pkey=factories.HOP1_KEY,
        ))

    return signed_transfer
def test_pfs_handler_handle_routefailed_with_feedback_token():
    raiden, pfs_handler, _, token_network_address, route, feedback_uuid = setup_pfs_handler_test(
        set_feedback_token=True)

    route_failed_event = EventRouteFailed(
        secrethash=make_secret_hash(),
        route=route,
        token_network_address=token_network_address)

    with patch("raiden.raiden_event_handler.post_pfs_feedback"
               ) as pfs_feedback_handler:
        pfs_handler.on_raiden_events(
            raiden=raiden,
            chain_state=cast(
                ChainState,
                raiden.wal.state_manager.current_state),  # type: ignore
            events=[route_failed_event],
        )
    assert pfs_feedback_handler.called
    assert pfs_feedback_handler.call_args == call(
        pfs_config=raiden.config.pfs_config,
        route=route,
        routing_mode=RoutingMode.PRIVATE,
        successful=False,
        token=feedback_uuid,
        token_network_address=token_network_address,
    )
Beispiel #4
0
def test_get_secret():
    secret1 = factories.make_secret()
    secret2 = factories.make_secret()
    secrethash3 = factories.make_secret_hash()
    secrethash4 = factories.make_secret_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={
            keccak(secret1): UnlockPartialProofState(lock=lock_state, secret=secret1)
        },
        secrethashes_to_onchain_unlockedlocks={
            keccak(secret2): UnlockPartialProofState(lock=lock_state, secret=secret2)
        },
    )

    assert get_secret(end_state, keccak(secret1)) == secret1  # known secret from offchain unlock
    assert get_secret(end_state, keccak(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
def test_pfs_handler_handle_routefailed_without_feedback_token():
    raiden, pfs_handler, _, token_network_address, route, _ = setup_pfs_handler_test(
        set_feedback_token=False)

    route_failed_event = EventRouteFailed(
        secrethash=make_secret_hash(),
        route=route,
        token_network_address=token_network_address)

    with patch("raiden.raiden_event_handler.post_pfs_feedback"
               ) as pfs_feedback_handler:
        pfs_handler.on_raiden_events(
            raiden=raiden,
            chain_state=cast(ChainState,
                             raiden.wal.get_current_state()),  # type: ignore
            events=[route_failed_event],
        )
    assert not pfs_feedback_handler.called
Beispiel #6
0
def make_signed_balance_proof_from_counter(counter):
    lock = Lock(
        amount=next(counter),
        expiration=next(counter),
        secrethash=factories.make_secret_hash(next(counter)),
    )
    lock_expired_balance_proof = factories.create(
        factories.BalanceProofSignedStateProperties(
            nonce=next(counter),
            transferred_amount=next(counter),
            locked_amount=next(counter),
            canonical_identifier=factories.make_canonical_identifier(
                token_network_address=factories.make_address(),
                channel_identifier=next(counter)),
            locksroot=Locksroot(sha3(lock.as_bytes)),
            message_hash=AdditionalHash(sha3(b"")),
            sender=factories.HOP1,
            pkey=factories.HOP1_KEY,
        ))

    return lock_expired_balance_proof
def test_api_payments_with_hash_no_secret(api_server_test_instance,
                                          raiden_network, token_addresses):
    _, app1 = raiden_network
    token_address = token_addresses[0]
    target_address = app1.raiden.address
    secret_hash = factories.make_secret_hash()

    request = grequests.post(
        api_url_for(
            api_server_test_instance,
            "token_target_paymentresource",
            token_address=to_checksum_address(token_address),
            target_address=to_checksum_address(target_address),
        ),
        json={
            "amount": DEFAULT_AMOUNT,
            "identifier": DEFAULT_ID,
            "secret_hash": to_hex(secret_hash),
        },
    )
    response = request.send().response
    assert_proper_response(response, status_code=HTTPStatus.CONFLICT)
Beispiel #8
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 = SerializedSQLiteStorage(":memory:", serializer)
    counter = itertools.count(1)
    partner_address = factories.make_address()

    balance_proof = make_balance_proof_from_counter(counter)
    lock_expired = SendLockExpired(
        recipient=partner_address,
        message_identifier=MessageID(next(counter)),
        balance_proof=balance_proof,
        secrethash=factories.make_secret_hash(next(counter)),
        canonical_identifier=balance_proof.canonical_identifier,
    )
    locked_transfer = SendLockedTransfer(
        recipient=partner_address,
        message_identifier=MessageID(next(counter)),
        transfer=make_transfer_from_counter(counter),
        canonical_identifier=factories.make_canonical_identifier(),
    )
    send_balance_proof = SendBalanceProof(
        recipient=partner_address,
        message_identifier=MessageID(next(counter)),
        payment_identifier=factories.make_payment_id(),
        token_address=factories.make_token_address(),
        secret=factories.make_secret(next(counter)),
        balance_proof=make_balance_proof_from_counter(counter),
        canonical_identifier=factories.make_canonical_identifier(),
    )

    refund_transfer = SendRefundTransfer(
        recipient=partner_address,
        message_identifier=MessageID(next(counter)),
        transfer=make_transfer_from_counter(counter),
        canonical_identifier=factories.make_canonical_identifier(),
    )

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

    state_change = Block(BlockNumber(1), BlockGasLimit(1),
                         factories.make_block_hash())
    for event, _ in events_balanceproofs:
        state_change_identifiers = storage.write_state_changes([state_change])
        storage.write_events(events=[(state_change_identifiers[0], event)])

    for event, balance_proof in events_balanceproofs:
        event_record = get_event_with_balance_proof_by_balance_hash(
            storage=storage,
            canonical_identifier=balance_proof.canonical_identifier,
            balance_hash=balance_proof.balance_hash,
            recipient=partner_address,
        )
        assert event_record
        assert event_record.data == event

        event_record = get_event_with_balance_proof_by_locksroot(
            storage=storage,
            canonical_identifier=balance_proof.canonical_identifier,
            recipient=event.recipient,
            locksroot=balance_proof.locksroot,
        )
        assert event_record
        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

    storage.close()
Beispiel #9
0
def test_get_state_change_with_balance_proof():
    """ All state changes which contain a balance proof must be found when
    querying the database.
    """
    serializer = JSONSerializer()
    storage = SerializedSQLiteStorage(":memory:", serializer)
    counter = itertools.count()

    balance_proof = make_signed_balance_proof_from_counter(counter)

    lock_expired = ReceiveLockExpired(
        sender=balance_proof.sender,
        balance_proof=balance_proof,
        secrethash=factories.make_secret_hash(next(counter)),
        message_identifier=MessageID(next(counter)),
    )

    received_balance_proof = make_signed_balance_proof_from_counter(counter)
    unlock = ReceiveUnlock(
        sender=received_balance_proof.sender,
        message_identifier=MessageID(next(counter)),
        secret=factories.make_secret(next(counter)),
        balance_proof=received_balance_proof,
    )
    transfer = make_signed_transfer_from_counter(counter)
    transfer_refund = ReceiveTransferRefund(
        transfer=transfer,
        balance_proof=transfer.balance_proof,
        sender=transfer.balance_proof.sender,  # pylint: disable=no-member
    )
    transfer = make_signed_transfer_from_counter(counter)
    transfer_reroute = ActionTransferReroute(
        transfer=transfer,
        balance_proof=transfer.balance_proof,
        sender=transfer.balance_proof.sender,  # pylint: disable=no-member
        secret=sha3(factories.make_secret(next(counter))),
    )
    mediator_from_route, mediator_signed_transfer = make_from_route_from_counter(
        counter)

    action_init_mediator = ActionInitMediator(
        route_states=[
            RouteState(
                route=[factories.make_address(),
                       factories.make_address()],
                forward_channel_id=factories.make_channel_identifier(),
            )
        ],
        from_hop=mediator_from_route,
        from_transfer=mediator_signed_transfer,
        balance_proof=mediator_signed_transfer.balance_proof,
        sender=mediator_signed_transfer.balance_proof.sender,  # pylint: disable=no-member
    )
    target_from_route, target_signed_transfer = make_from_route_from_counter(
        counter)
    action_init_target = ActionInitTarget(
        from_hop=target_from_route,
        transfer=target_signed_transfer,
        balance_proof=target_signed_transfer.balance_proof,
        sender=target_signed_transfer.balance_proof.sender,  # pylint: disable=no-member
    )

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

    assert storage.count_state_changes() == 0

    state_change_ids = storage.write_state_changes(
        [state_change for state_change, _ in statechanges_balanceproofs])
    assert storage.count_state_changes() == len(statechanges_balanceproofs)

    msg_in_order = "Querying must return state changes in order"
    stored_statechanges_records = storage.get_statechanges_records_by_range(
        RANGE_ALL_STATE_CHANGES)
    assert len(stored_statechanges_records) == 6, msg_in_order

    pair_elements = zip(statechanges_balanceproofs, state_change_ids,
                        stored_statechanges_records)
    for statechange_balanceproof, statechange_id, record in pair_elements:
        assert record.data == statechange_balanceproof[0], msg_in_order
        assert record.state_change_identifier == statechange_id, msg_in_order

    # Make sure state changes are returned in the correct order in which they were stored
    stored_statechanges = storage.get_statechanges_by_range(
        Range(
            stored_statechanges_records[1].state_change_identifier,
            stored_statechanges_records[2].state_change_identifier,
        ))

    assert len(stored_statechanges) == 2
    assert isinstance(stored_statechanges[0], ReceiveUnlock)
    assert isinstance(stored_statechanges[1], ReceiveTransferRefund)

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

        state_change_record = get_state_change_with_balance_proof_by_locksroot(
            storage=storage,
            canonical_identifier=balance_proof.canonical_identifier,
            sender=balance_proof.sender,
            locksroot=balance_proof.locksroot,
        )
        assert state_change_record
        assert state_change_record.data == state_change

    storage.close()
Beispiel #10
0
def test_api_payments_with_resolver(
        api_server_test_instance: APIServer,
        raiden_network,
        token_addresses,
        resolvers,  # pylint: disable=unused-argument
):

    _, app1 = raiden_network
    amount = 100
    identifier = 42
    token_address = token_addresses[0]
    target_address = app1.raiden.address
    secret_hash = factories.make_secret_hash()

    # payment with secret_hash when both resolver and initiator don't have the secret
    request = grequests.post(
        api_url_for(
            api_server_test_instance,
            "token_target_paymentresource",
            token_address=to_checksum_address(token_address),
            target_address=to_checksum_address(target_address),
        ),
        json={
            "amount": str(amount),
            "identifier": str(identifier),
            "secret_hash": to_hex(secret_hash),
        },
    )
    response = request.send().response
    assert_proper_response(response, status_code=HTTPStatus.CONFLICT)

    # payment with secret where the resolver doesn't have the secret. Should work.
    request = grequests.post(
        api_url_for(
            api_server_test_instance,
            "token_target_paymentresource",
            token_address=to_checksum_address(token_address),
            target_address=to_checksum_address(target_address),
        ),
        json={
            "amount": str(amount),
            "identifier": str(identifier),
            "secret": to_hex(secret_hash)
        },
    )
    response = request.send().response
    assert_proper_response(response, status_code=HTTPStatus.OK)

    # payment with secret_hash where the resolver has the secret. Should work.
    secret = Secret(
        decode_hex(
            "0x2ff886d47b156de00d4cad5d8c332706692b5b572adfe35e6d2f65e92906806e"
        ))
    secret_hash = sha256_secrethash(secret)

    request = grequests.post(
        api_url_for(
            api_server_test_instance,
            "token_target_paymentresource",
            token_address=to_checksum_address(token_address),
            target_address=to_checksum_address(target_address),
        ),
        json={
            "amount": str(amount),
            "identifier": str(identifier),
            "secret_hash": to_hex(secret_hash),
        },
    )
    with watch_for_unlock_failures(*raiden_network):
        response = request.send().response
    assert_proper_response(response, status_code=HTTPStatus.OK)
Beispiel #11
0
def test_encoding_and_decoding():
    message_factories = (
        factories.LockedTransferProperties(),
        factories.RefundTransferProperties(),
        factories.LockExpiredProperties(),
        factories.UnlockProperties(),
    )
    messages = [factories.create(factory) for factory in message_factories]

    # TODO Handle these with factories once #5091 is implemented
    messages.append(
        Delivered(
            delivered_message_identifier=factories.make_message_identifier(),
            signature=factories.make_signature(),
        ))
    messages.append(
        Processed(
            message_identifier=factories.make_message_identifier(),
            signature=factories.make_signature(),
        ))
    messages.append(
        RevealSecret(
            message_identifier=factories.make_message_identifier(),
            secret=factories.make_secret(),
            signature=factories.make_signature(),
        ))
    messages.append(
        SecretRequest(
            message_identifier=factories.make_message_identifier(),
            payment_identifier=factories.make_payment_id(),
            secrethash=factories.make_secret_hash(),
            amount=factories.make_token_amount(),
            expiration=factories.make_block_number(),
            signature=factories.make_signature(),
        ))
    messages.append(
        WithdrawRequest(
            message_identifier=factories.make_message_identifier(),
            chain_id=factories.make_chain_id(),
            token_network_address=factories.make_token_network_address(),
            channel_identifier=factories.make_channel_identifier(),
            participant=factories.make_address(),
            total_withdraw=factories.make_token_amount(),
            nonce=factories.make_nonce(),
            expiration=factories.make_block_number(),
            signature=factories.make_signature(),
        ))
    messages.append(
        WithdrawConfirmation(
            message_identifier=factories.make_message_identifier(),
            chain_id=factories.make_chain_id(),
            token_network_address=factories.make_token_network_address(),
            channel_identifier=factories.make_channel_identifier(),
            participant=factories.make_address(),
            total_withdraw=factories.make_token_amount(),
            nonce=factories.make_nonce(),
            expiration=factories.make_block_number(),
            signature=factories.make_signature(),
        ))
    messages.append(
        WithdrawExpired(
            message_identifier=factories.make_message_identifier(),
            chain_id=factories.make_chain_id(),
            token_network_address=factories.make_token_network_address(),
            channel_identifier=factories.make_channel_identifier(),
            participant=factories.make_address(),
            total_withdraw=factories.make_token_amount(),
            nonce=factories.make_nonce(),
            expiration=factories.make_block_number(),
            signature=factories.make_signature(),
        ))
    messages.append(
        PFSCapacityUpdate(
            canonical_identifier=factories.make_canonical_identifier(),
            updating_participant=factories.make_address(),
            other_participant=factories.make_address(),
            updating_nonce=factories.make_nonce(),
            other_nonce=factories.make_nonce(),
            updating_capacity=factories.make_token_amount(),
            other_capacity=factories.make_token_amount(),
            reveal_timeout=factories.make_uint64(),
            signature=factories.make_signature(),
        ))
    messages.append(
        PFSFeeUpdate(
            canonical_identifier=factories.make_canonical_identifier(),
            updating_participant=factories.make_address(),
            fee_schedule=factories.create(
                factories.FeeScheduleStateProperties()),
            timestamp=datetime.now(),
            signature=factories.make_signature(),
        ))
    messages.append(
        RequestMonitoring(
            reward_amount=factories.make_token_amount(),
            balance_proof=SignedBlindedBalanceProof.
            from_balance_proof_signed_state(
                factories.create(
                    factories.BalanceProofSignedStateProperties())),
            monitoring_service_contract_address=factories.make_address(),
            non_closing_participant=factories.make_address(),
            non_closing_signature=factories.make_signature(),
            signature=factories.make_signature(),
        ))

    for message in messages:
        serialized = MessageSerializer.serialize(message)
        deserialized = MessageSerializer.deserialize(serialized)
        assert deserialized == message
Beispiel #12
0
        message_identifier=factories.make_message_identifier(),
        signature=factories.make_signature(),
    )
)
messages.append(
    RevealSecret(
        message_identifier=factories.make_message_identifier(),
        secret=factories.make_secret(),
        signature=factories.make_signature(),
    )
)
messages.append(
    SecretRequest(
        message_identifier=factories.make_message_identifier(),
        payment_identifier=factories.make_payment_id(),
        secrethash=factories.make_secret_hash(),
        amount=factories.make_payment_amount(),
        expiration=factories.make_block_expiration_number(),
        signature=factories.make_signature(),
    )
)
messages.append(
    WithdrawRequest(
        message_identifier=factories.make_message_identifier(),
        chain_id=factories.make_chain_id(),
        token_network_address=factories.make_token_network_address(),
        channel_identifier=factories.make_channel_identifier(),
        participant=factories.make_address(),
        total_withdraw=factories.make_withdraw_amount(),
        nonce=factories.make_nonce(),
        expiration=factories.make_block_expiration_number(),