Skip to content

Commit

Permalink
replace Function Mapping by singledispatch
Browse files Browse the repository at this point in the history
  • Loading branch information
Fernando Cezar Bernardelli committed Aug 5, 2021
1 parent b034812 commit 1f308ca
Show file tree
Hide file tree
Showing 9 changed files with 303 additions and 229 deletions.
29 changes: 23 additions & 6 deletions raiden/message_handler.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from math import inf

import structlog
from eth_utils import to_hex
from gevent import joinall
Expand Down Expand Up @@ -42,6 +44,7 @@
)
from raiden.transfer.utils import decrypt_secret
from raiden.transfer.views import TransferRole
from raiden.utils.formatting import to_checksum_address
from raiden.utils.transfers import random_secret
from raiden.utils.typing import (
TYPE_CHECKING,
Expand All @@ -51,6 +54,7 @@
Set,
TargetAddress,
Tuple,
Union,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -104,18 +108,21 @@ def on_messages(self, raiden: "RaidenService", messages: List[Message]) -> None:
# (an asynchronous network is assumed) This reduces latency when a
# balance proof is considered invalid because of a race with the
# blockchain view of each node.
def by_canonical_identifier(state_change: StateChange) -> Tuple[int, int]:
def by_canonical_identifier(
state_change: StateChange,
) -> Union[Tuple[int, int], Tuple[float, float]]:
if isinstance(state_change, BalanceProofStateChange):
balance_proof = state_change.balance_proof
return (
balance_proof.canonical_identifier.channel_identifier,
balance_proof.nonce,
)

elif isinstance(state_change, ReceiveSecretReveal):
# ReceiveSecretReveal depends on other state changes happening first.
return inf, inf
return 0, 0

all_state_changes.sort(key=by_canonical_identifier)

raiden.handle_and_track_state_changes(all_state_changes)

@staticmethod
Expand Down Expand Up @@ -343,10 +350,20 @@ def handle_message_lockedtransfer(
if encrypted_secret is not None:
try:
secret = decrypt_secret(encrypted_secret, raiden.rpc_client.privkey)
log.info(f"Using encrypted secret received from {sender.hex()}")
return [ReceiveSecretReveal(secret=secret, sender=message.sender)]
log.info("Using encrypted secret", sender=to_checksum_address(sender))
return [
ActionInitTarget(
from_hop=from_hop,
transfer=from_transfer,
balance_proof=balance_proof,
sender=sender,
received_valid_secret=True,
),
ReceiveSecretReveal(secret=secret, sender=message.sender),
]
except InvalidSecret:
log.error(f"Ignoring invalid encrypted secret received from {sender.hex()}")
sender_addr = to_checksum_address(sender)
log.error("Ignoring invalid encrypted secret", sender=sender_addr)
return [
ActionInitTarget(
from_hop=from_hop,
Expand Down
47 changes: 46 additions & 1 deletion raiden/tests/integration/transfer/test_mediatedtransfer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import List, cast
from unittest.mock import patch

import gevent
import pytest

from raiden.exceptions import RaidenUnrecoverableError
Expand All @@ -16,8 +17,9 @@
from raiden.tests.utils.factories import make_secret
from raiden.tests.utils.mediation_fees import get_amount_for_sending_before_and_after_fees
from raiden.tests.utils.network import CHAIN
from raiden.tests.utils.protocol import WaitForMessage
from raiden.tests.utils.protocol import HoldRaidenEventHandler, WaitForMessage
from raiden.tests.utils.transfer import (
TransferState,
assert_succeeding_transfer_invariants,
assert_synced_channel_state,
block_timeout_for_transfer_by_secrethash,
Expand All @@ -27,6 +29,7 @@
wait_assert,
)
from raiden.transfer import views
from raiden.transfer.mediated_transfer.events import SendSecretRequest
from raiden.transfer.mediated_transfer.initiator import calculate_fee_margin
from raiden.transfer.mediated_transfer.mediation_fee import FeeScheduleState
from raiden.transfer.mediated_transfer.state_change import ActionInitMediator, ActionInitTarget
Expand All @@ -49,6 +52,48 @@
from raiden.waiting import wait_for_block


@raise_on_failure
@pytest.mark.parametrize("channels_per_node", [CHAIN])
@pytest.mark.parametrize("number_of_nodes", [2])
def test_transfer_with_secret(
raiden_network: List[RaidenService], number_of_nodes, deposit, token_addresses, network_wait
):
app0, app1 = raiden_network
token_address = token_addresses[0]
chain_state = views.state_from_raiden(app0)
token_network_registry_address = app0.default_registry.address
token_network_address = views.get_token_network_address_by_token_address(
chain_state, token_network_registry_address, token_address
)

amount = PaymentAmount(10)
secret_hash = transfer(
initiator_app=app0,
target_app=app1,
token_address=token_address,
amount=amount,
transfer_state=TransferState.LOCKED,
identifier=PaymentID(1),
timeout=network_wait * number_of_nodes,
routes=[[app0, app1]],
)

assert isinstance(app1.raiden_event_handler, HoldRaidenEventHandler)
app1.raiden_event_handler.hold(SendSecretRequest, {"secrethash": secret_hash})

with gevent.Timeout(20):
wait_assert(
assert_succeeding_transfer_invariants,
token_network_address,
app0,
deposit - amount,
[],
app1,
deposit + amount,
[],
)


@raise_on_failure
@pytest.mark.parametrize("channels_per_node", [CHAIN])
@pytest.mark.parametrize("number_of_nodes", [3])
Expand Down
70 changes: 35 additions & 35 deletions raiden/tests/unit/test_channelstate.py
Original file line number Diff line number Diff line change
Expand Up @@ -1224,7 +1224,7 @@ def test_channelstate_unlock_without_locks():
block_number=77,
block_hash=make_block_hash(),
)
iteration = channel.handle_channel_closed(channel_state, state_change)
iteration = channel._handle_channel_closed(state_change, channel_state)
assert not iteration.events


Expand Down Expand Up @@ -1313,7 +1313,7 @@ def test_channelstate_unlock_unlocked_onchain():
block_number=closed_block_number,
block_hash=closed_block_hash,
)
iteration = channel.handle_channel_closed(channel_state, close_state_change)
iteration = channel._handle_channel_closed(close_state_change, channel_state)
assert search_for_item(iteration.events, ContractSendChannelBatchUnlock, {}) is None

settle_block_number = lock_expiration + channel_state.reveal_timeout + 1
Expand All @@ -1329,7 +1329,7 @@ def test_channelstate_unlock_unlocked_onchain():
our_onchain_locksroot=LOCKSROOT_OF_NO_LOCKS,
)

iteration = channel.handle_channel_settled(channel_state, settle_state_change)
iteration = channel._handle_channel_settled(settle_state_change, channel_state)
assert search_for_item(iteration.events, ContractSendChannelBatchUnlock, {}) is not None


Expand Down Expand Up @@ -1424,7 +1424,7 @@ def test_update_must_be_called_if_close_lost_race():
block_number=77,
block_hash=make_block_hash(),
)
iteration = channel.handle_channel_closed(channel_state, state_change)
iteration = channel._handle_channel_closed(state_change, channel_state)
assert search_for_item(iteration.events, ContractSendChannelUpdateTransfer, {}) is not None


Expand Down Expand Up @@ -1461,7 +1461,7 @@ def test_update_transfer():
block_number=closed_block_number,
block_hash=closed_block_hash,
)
iteration2 = channel.handle_channel_closed(channel_state, channel_close_state_change)
iteration2 = channel._handle_channel_closed(channel_close_state_change, channel_state)

# update_transaction in channel state should not be set because there was no transfer
channel_state = iteration2.new_state
Expand All @@ -1476,8 +1476,8 @@ def test_update_transfer():
)

update_block_number = 20
iteration3 = channel.handle_channel_updated_transfer(
channel_state, update_transfer_state_change, update_block_number
iteration3 = channel._handle_channel_updated_transfer(
update_transfer_state_change, channel_state, update_block_number
)

# now update_transaction in channel state should be set
Expand Down Expand Up @@ -1591,9 +1591,9 @@ def test_action_withdraw():
canonical_identifier=channel_state.canonical_identifier, total_withdraw=100
)

iteration = channel.handle_action_withdraw(
iteration = channel._handle_action_withdraw(
channel_state=channel_state,
action_withdraw=action_withdraw,
action=action_withdraw,
pseudo_random_generator=pseudo_random_generator,
block_number=2,
)
Expand All @@ -1608,9 +1608,9 @@ def test_action_withdraw():
canonical_identifier=channel_state.canonical_identifier, total_withdraw=our_balance
)

iteration = channel.handle_action_withdraw(
iteration = channel._handle_action_withdraw(
channel_state=channel_state,
action_withdraw=action_withdraw,
action=action_withdraw,
pseudo_random_generator=pseudo_random_generator,
block_number=3,
)
Expand All @@ -1626,9 +1626,9 @@ def test_action_withdraw():
canonical_identifier=channel_state.canonical_identifier, total_withdraw=our_balance
)

iteration = channel.handle_action_withdraw(
iteration = channel._handle_action_withdraw(
channel_state=iteration.new_state,
action_withdraw=action_withdraw,
action=action_withdraw,
pseudo_random_generator=pseudo_random_generator,
block_number=4,
)
Expand Down Expand Up @@ -1664,8 +1664,8 @@ def test_receive_withdraw_request():
expiration=expiration,
)

iteration = channel.handle_receive_withdraw_request(
channel_state=channel_state, withdraw_request=withdraw_request
iteration = channel._handle_receive_withdraw_request(
channel_state=channel_state, action=withdraw_request
)

assert (
Expand Down Expand Up @@ -1698,8 +1698,8 @@ def test_receive_withdraw_request():
expiration=expiration,
)

iteration = channel.handle_receive_withdraw_request(
channel_state=channel_state, withdraw_request=withdraw_request
iteration = channel._handle_receive_withdraw_request(
channel_state=channel_state, action=withdraw_request
)

# pylint: disable=no-member
Expand All @@ -1724,8 +1724,8 @@ def test_receive_withdraw_request():
expiration=10,
)

iteration = channel.handle_receive_withdraw_request(
channel_state=iteration.new_state, withdraw_request=withdraw_request
iteration = channel._handle_receive_withdraw_request(
channel_state=iteration.new_state, action=withdraw_request
)

assert (
Expand All @@ -1749,8 +1749,8 @@ def test_receive_withdraw_request():
expiration=10,
)

iteration = channel.handle_receive_withdraw_request(
channel_state=iteration.new_state, withdraw_request=withdraw_request
iteration = channel._handle_receive_withdraw_request(
channel_state=iteration.new_state, action=withdraw_request
)

assert (
Expand Down Expand Up @@ -1803,9 +1803,9 @@ def test_receive_withdraw_confirmation():
expiration=expiration_block,
)

iteration = channel.handle_receive_withdraw_confirmation(
iteration = channel._handle_receive_withdraw_confirmation(
channel_state=channel_state,
withdraw=receive_withdraw,
action=receive_withdraw,
block_number=10,
block_hash=block_hash,
)
Expand All @@ -1830,9 +1830,9 @@ def test_receive_withdraw_confirmation():
expiration=expiration_block,
)

iteration = channel.handle_receive_withdraw_confirmation(
iteration = channel._handle_receive_withdraw_confirmation(
channel_state=iteration.new_state,
withdraw=receive_withdraw,
action=receive_withdraw,
block_number=10,
block_hash=block_hash,
)
Expand All @@ -1855,9 +1855,9 @@ def test_receive_withdraw_confirmation():
expiration=expiration_block,
)

iteration = channel.handle_receive_withdraw_confirmation(
iteration = channel._handle_receive_withdraw_confirmation(
channel_state=iteration.new_state,
withdraw=receive_withdraw,
action=receive_withdraw,
block_number=10,
block_hash=block_hash,
)
Expand Down Expand Up @@ -1891,9 +1891,9 @@ def test_node_sends_withdraw_expiry():
block_hash = make_transaction_hash()
block = Block(block_number=expiration_threshold - 1, gas_limit=1, block_hash=block_hash)

iteration = channel.handle_block(
iteration = channel._handle_block(
channel_state=channel_state,
state_change=block,
action=block,
block_number=expiration_threshold - 1,
pseudo_random_generator=pseudo_random_generator,
)
Expand All @@ -1903,9 +1903,9 @@ def test_node_sends_withdraw_expiry():
block_hash = make_transaction_hash()
block = Block(block_number=expiration_threshold, gas_limit=1, block_hash=block_hash)

iteration = channel.handle_block(
iteration = channel._handle_block(
channel_state=channel_state,
state_change=block,
action=block,
block_number=expiration_threshold,
pseudo_random_generator=pseudo_random_generator,
)
Expand Down Expand Up @@ -2210,8 +2210,8 @@ def test_receive_contract_withdraw():
fee_config=MediationFeeConfig(),
)

iteration = channel.handle_channel_withdraw(
channel_state=channel_state, state_change=contract_receive_withdraw
iteration = channel._handle_channel_withdraw(
channel_state=channel_state, action=contract_receive_withdraw
)

assert iteration.new_state.our_state.offchain_total_withdraw == 0
Expand All @@ -2232,8 +2232,8 @@ def test_receive_contract_withdraw():
fee_config=MediationFeeConfig(),
)

iteration = channel.handle_channel_withdraw(
channel_state=iteration.new_state, state_change=contract_receive_withdraw
iteration = channel._handle_channel_withdraw(
channel_state=iteration.new_state, action=contract_receive_withdraw
)

assert iteration.new_state.partner_state.offchain_total_withdraw == 0
Expand Down
Loading

0 comments on commit 1f308ca

Please sign in to comment.