def test_matrix_invite_private_room_unhappy_case_2(matrix_transports, expected_join_rule0, expected_join_rule1): raiden_service0 = MockRaidenService(None) raiden_service1 = MockRaidenService(None) transport0, transport1 = matrix_transports transport0.start(raiden_service0, raiden_service0.message_handler, None) transport1.start(raiden_service1, raiden_service1.message_handler, None) transport0.start_health_check(raiden_service1.address) transport1.start_health_check(raiden_service0.address) assert is_reachable(transport1, raiden_service0.address) assert is_reachable(transport0, raiden_service1.address) print(transport1._client.user_id) transport1.stop() wait_for_peer_unreachable(transport0, raiden_service1.address) assert not is_reachable(transport0, raiden_service1.address) room_id = transport0._get_room_for_address(raiden_service1.address).room_id transport1.start(raiden_service1, raiden_service1.message_handler, None) transport1.start_health_check(raiden_service0.address) with Timeout(TIMEOUT_MESSAGE_RECEIVE): while True: try: room_state0 = transport0._client.api.get_room_state(room_id) break except MatrixRequestError: gevent.sleep(0.1) join_rule0 = [ event["content"].get("join_rule") for event in room_state0 if event["type"] == "m.room.join_rules" ][0] assert join_rule0 == expected_join_rule0 with Timeout(TIMEOUT_MESSAGE_RECEIVE): while True: try: room_state1 = transport1._client.api.get_room_state(room_id) break except MatrixRequestError as ex: print(ex, transport0._client.user_id, transport1._client.user_id) gevent.sleep(0.5) join_rule1 = [ event["content"].get("join_rule") for event in room_state1 if event["type"] == "m.room.join_rules" ][0] assert join_rule1 == expected_join_rule1
def test_send_to_device(matrix_transports): transport0, transport1 = matrix_transports received_messages0 = set() received_messages1 = set() message_handler0 = MessageHandler(received_messages0) message_handler1 = MessageHandler(received_messages1) raiden_service0 = MockRaidenService(message_handler0) raiden_service1 = MockRaidenService(message_handler1) transport1._receive_to_device = MagicMock() transport0.start(raiden_service0, [], "") transport1.start(raiden_service1, [], "") transport0.start_health_check(raiden_service1.address) transport1.start_health_check(raiden_service0.address) message = Processed(message_identifier=1, signature=EMPTY_SIGNATURE) transport0._raiden_service.sign(message) transport0.send_to_device(raiden_service1.address, message) transport1._receive_to_device.assert_not_called() message = ToDevice(message_identifier=1, signature=EMPTY_SIGNATURE) transport0._raiden_service.sign(message) transport0.send_to_device(raiden_service1.address, message) with gevent.Timeout(2): wait_assert(transport1._receive_to_device.assert_called)
def test_send_to_device(matrix_transports): transport0, transport1 = matrix_transports received_messages0 = set() received_messages1 = set() message_handler0 = MessageHandler(received_messages0) message_handler1 = MessageHandler(received_messages1) raiden_service0 = MockRaidenService(message_handler0) raiden_service1 = MockRaidenService(message_handler1) transport1._receive_to_device = MagicMock() transport0.start(raiden_service0, message_handler0, "") transport1.start(raiden_service1, message_handler1, "") transport0.start_health_check(raiden_service1.address) transport1.start_health_check(raiden_service0.address) message = Processed(message_identifier=1) transport0._raiden_service.sign(message) transport0.send_to_device(raiden_service1.address, message) gevent.sleep(0.5) transport1._receive_to_device.assert_not_called() message = ToDevice(message_identifier=1) transport0._raiden_service.sign(message) transport0.send_to_device(raiden_service1.address, message) gevent.sleep(0.5) transport1._receive_to_device.assert_called()
def test_matrix_cross_server_with_load_balance(matrix_transports): transport0, transport1, transport2 = matrix_transports received_messages0 = set() received_messages1 = set() received_messages2 = set() message_handler0 = MessageHandler(received_messages0) message_handler1 = MessageHandler(received_messages1) message_handler2 = MessageHandler(received_messages2) raiden_service0 = MockRaidenService(message_handler0) raiden_service1 = MockRaidenService(message_handler1) raiden_service2 = MockRaidenService(message_handler2) transport0.start(raiden_service0, [], "") transport1.start(raiden_service1, [], "") transport2.start(raiden_service2, [], "") transport0.immediate_health_check_for(raiden_service1.address) transport0.immediate_health_check_for(raiden_service2.address) transport1.immediate_health_check_for(raiden_service0.address) transport1.immediate_health_check_for(raiden_service2.address) transport2.immediate_health_check_for(raiden_service0.address) transport2.immediate_health_check_for(raiden_service1.address) assert ping_pong_message_success(transport0, transport1) assert ping_pong_message_success(transport0, transport2) assert ping_pong_message_success(transport1, transport0) assert ping_pong_message_success(transport1, transport2) assert ping_pong_message_success(transport2, transport0) assert ping_pong_message_success(transport2, transport1)
def test_matrix_cross_server_with_load_balance(matrix_transports, retry_interval): transport0, transport1, transport2 = matrix_transports received_messages0 = set() received_messages1 = set() received_messages2 = set() message_handler0 = MessageHandler(received_messages0) message_handler1 = MessageHandler(received_messages1) message_handler2 = MessageHandler(received_messages2) raiden_service0 = MockRaidenService(message_handler0) raiden_service1 = MockRaidenService(message_handler1) raiden_service2 = MockRaidenService(message_handler2) transport0.start(raiden_service0, message_handler0, '') transport1.start(raiden_service1, message_handler1, '') transport2.start(raiden_service2, message_handler2, '') transport0.start_health_check(raiden_service1.address) transport0.start_health_check(raiden_service2.address) transport1.start_health_check(raiden_service0.address) transport1.start_health_check(raiden_service2.address) transport2.start_health_check(raiden_service0.address) transport2.start_health_check(raiden_service1.address) queueid1 = QueueIdentifier( recipient=raiden_service1.address, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, ) queueid2 = QueueIdentifier( recipient=raiden_service2.address, channel_identifier=CHANNEL_IDENTIFIER_GLOBAL_QUEUE, ) message = Processed(message_identifier=0) raiden_service0.sign(message) transport0.send_async(queueid1, message) transport0.send_async(queueid2, message) with Timeout(retry_interval * 10, exception=False): all_messages_received = False while not all_messages_received: all_messages_received = (len(received_messages0) == 2 and len(received_messages1) == 1 and len(received_messages2) == 1) gevent.sleep(.1) assert all_messages_received transport0.stop() transport1.stop() transport2.stop() transport0.get() transport1.get() transport2.get()
def test_matrix_invite_private_room_happy_case(matrix_transports): """ Test that a room has been created between two communicating nodes.""" # initialize transport raiden_service0 = MockRaidenService(None) raiden_service1 = MockRaidenService(None) transport0, transport1 = matrix_transports transport0.start(raiden_service0, [], None) transport1.start(raiden_service1, [], None) # start health check to create private room transport0.immediate_health_check_for(transport1._raiden_service.address) transport1.immediate_health_check_for(transport0._raiden_service.address) # wait for room synchronization of transports # due to asynchronous room creation wait_for_room_with_address(transport0, raiden_service1.address) wait_for_room_with_address(transport1, raiden_service0.address) # check that there exist a room state by server # meaning that both user are members of the room room = transport0._get_room_for_address(raiden_service1.address) assert room is not None room_id = room.room_id with Timeout(TIMEOUT_MESSAGE_RECEIVE): while True: try: room_state0 = transport0._client.api.get_room_state(room_id) room_state1 = transport1._client.api.get_room_state(room_id) break except MatrixRequestError: gevent.sleep(0.1) assert room_state0 is not None assert room_state1 is not None
def test_matrix_invitee_receives_invite_on_restart(matrix_transports): raiden_service0 = MockRaidenService(None) raiden_service1 = MockRaidenService(None) transport0, transport1 = matrix_transports room_creator_address = my_place_or_yours(raiden_service0.address, raiden_service1.address) if room_creator_address == raiden_service0.address: inviter_service = raiden_service0 invitee_service = raiden_service1 inviter_transport = transport0 invitee_transport = transport1 else: inviter_service = raiden_service1 invitee_service = raiden_service0 inviter_transport = transport1 invitee_transport = transport0 inviter_transport.start(inviter_service, [], None) invitee_transport.start(invitee_service, [], None) inviter_transport.start_health_check(invitee_service.address) invitee_transport.start_health_check(inviter_service.address) wait_for_peer_reachable(inviter_transport, invitee_service.address) wait_for_peer_reachable(invitee_transport, inviter_service.address) assert is_reachable(invitee_transport, inviter_service.address) assert is_reachable(inviter_transport, invitee_service.address) invitee_transport.stop() wait_for_peer_unreachable(inviter_transport, invitee_service.address) assert not is_reachable(inviter_transport, invitee_service.address) room_id = inviter_transport._get_room_for_address( invitee_service.address).room_id invitee_transport.start(invitee_service, [], None) invitee_transport.start_health_check(inviter_service.address) inviter_transport.stop() with Timeout(TIMEOUT_MESSAGE_RECEIVE): while True: try: room_state1 = invitee_transport._client.api.get_room_state( room_id) break except MatrixRequestError: gevent.sleep(0.1) assert room_state1 is not None
def test_matrix_user_roaming(matrix_transports): transport0, transport1, transport2 = matrix_transports received_messages0 = set() received_messages1 = set() message_handler0 = MessageHandler(received_messages0) message_handler1 = MessageHandler(received_messages1) raiden_service0 = MockRaidenService(message_handler0) raiden_service1 = MockRaidenService(message_handler1) transport0.start(raiden_service0, message_handler0, '') transport1.start(raiden_service1, message_handler1, '') transport0.start_health_check(raiden_service1.address) transport1.start_health_check(raiden_service0.address) assert ping_pong_message_success(transport0, transport1) transport0.stop() with Timeout(40): while not transport1._address_to_presence[ raiden_service0.address].value == 'offline': gevent.sleep(.1) assert transport1._address_to_presence[ raiden_service0.address].value == 'offline' transport2.start(raiden_service0, message_handler0, '') transport2.start_health_check(raiden_service1.address) assert ping_pong_message_success(transport2, transport1) transport2.stop() with Timeout(40): while not transport1._address_to_presence[ raiden_service0.address].value == 'offline': gevent.sleep(.1) assert transport1._address_to_presence[ raiden_service0.address].value == 'offline' transport0.start(raiden_service0, message_handler0, '') with Timeout(40): while not transport1._address_to_presence[ raiden_service0.address].value == 'online': gevent.sleep(.1) assert transport1._address_to_presence[ raiden_service0.address].value == 'online' assert ping_pong_message_success(transport0, transport1)
def test_matrix_invitee_receives_invite_on_restart( matrix_transports: List[MatrixTransport]) -> None: """The invitee should receive the invite, even if the inviter is offline.""" raiden_service0: RaidenService = cast(RaidenService, MockRaidenService(None)) raiden_service1: RaidenService = cast(RaidenService, MockRaidenService(None)) transport0, transport1 = matrix_transports room_creator_address = my_place_or_yours(raiden_service0.address, raiden_service1.address) if room_creator_address == raiden_service0.address: inviter_service = raiden_service0 invitee_service = raiden_service1 inviter_transport = transport0 invitee_transport = transport1 else: inviter_service = raiden_service1 invitee_service = raiden_service0 inviter_transport = transport1 invitee_transport = transport0 # Initialize the invitee and stop it before the invite happens invitee_transport.start(invitee_service, [], None) invitee_transport.stop() inviter_transport.start(inviter_service, [], None) inviter_transport.immediate_health_check_for(invitee_service.address) room = inviter_transport._get_room_for_address(invitee_service.address) assert room, "The inviter should have created the room, even if the invitee is offline." # Now stop the inviter and check the invitee received the invite inviter_transport.stop() invitee_transport.start(invitee_service, [], None) invitee_transport.immediate_health_check_for(inviter_service.address) with Timeout(TIMEOUT_MESSAGE_RECEIVE): while True: try: room_state1 = invitee_transport._client.api.get_room_state( room.room_id) break except MatrixRequestError: gevent.sleep(0.1) assert room_state1 is not None
def test_matrix_user_roaming(matrix_transports, roaming_peer): transport0, transport1, transport2 = matrix_transports received_messages0 = set() received_messages1 = set() message_handler0 = MessageHandler(received_messages0) message_handler1 = MessageHandler(received_messages1) reverse_privkey_order = roaming_peer == "low" privkey0, privkey1 = make_privkeys_ordered(count=2, reverse=reverse_privkey_order) raiden_service0 = MockRaidenService(message_handler0, private_key=privkey0) raiden_service1 = MockRaidenService(message_handler1, private_key=privkey1) transport0.start(raiden_service0, [], "") transport1.start(raiden_service1, [], "") transport0.immediate_health_check_for(raiden_service1.address) transport1.immediate_health_check_for(raiden_service0.address) assert ping_pong_message_success(transport0, transport1) transport0.stop() wait_for_peer_unreachable(transport1, raiden_service0.address) assert not is_reachable(transport1, raiden_service0.address) transport2.start(raiden_service0, [], "") transport2.immediate_health_check_for(raiden_service1.address) assert ping_pong_message_success(transport2, transport1) transport2.stop() wait_for_peer_unreachable(transport1, raiden_service0.address) assert not is_reachable(transport1, raiden_service0.address) transport0.start(raiden_service0, [], "") transport0.immediate_health_check_for(raiden_service1.address) with Timeout(TIMEOUT_MESSAGE_RECEIVE): while not is_reachable(transport1, raiden_service0.address): gevent.sleep(0.1) assert is_reachable(transport1, raiden_service0.address) assert ping_pong_message_success(transport0, transport1)
def test_matrix_discovery_room_offline_server(local_matrix_servers, retries_before_backoff, retry_interval, broadcast_rooms): transport = MatrixTransport({ "broadcast_rooms": broadcast_rooms, "retries_before_backoff": retries_before_backoff, "retry_interval": retry_interval, "server": local_matrix_servers[0], "server_name": local_matrix_servers[0].netloc, "available_servers": [local_matrix_servers[0], "https://localhost:1"], }) transport.start(MockRaidenService(None), [], "") discovery_room_name = make_room_alias(transport.chain_id, "discovery") with gevent.Timeout(1): while not isinstance( transport._broadcast_rooms.get(discovery_room_name), Room): gevent.sleep(0.1) transport.stop() transport.greenlet.get()
def test_matrix_discovery_room_offline_server( local_matrix_servers, retries_before_backoff, retry_interval, private_rooms, ): transport = MatrixTransport({ 'discovery_room': 'discovery', 'retries_before_backoff': retries_before_backoff, 'retry_interval': retry_interval, 'server': local_matrix_servers[0], 'server_name': local_matrix_servers[0].netloc, 'available_servers': [local_matrix_servers[0], 'https://localhost:1'], 'private_rooms': private_rooms, }) transport.start(MockRaidenService(None), MessageHandler(set()), '') gevent.sleep(.2) transport.stop() transport.get()
def mock_udp( raiden_udp_ports, throttle_capacity, throttle_fill_rate, retry_interval, retries_before_backoff, nat_invitation_timeout, nat_keepalive_retries, nat_keepalive_timeout, ): throttle_policy = TokenBucket(throttle_capacity, throttle_fill_rate) host = "127.0.0.1" port = raiden_udp_ports[0] address = make_address() config = dict( retry_interval=retry_interval, retries_before_backoff=retries_before_backoff, nat_invitation_timeout=nat_invitation_timeout, nat_keepalive_retries=nat_keepalive_retries, nat_keepalive_timeout=nat_keepalive_timeout, ) transport = UDPTransport( address, MockDiscovery, server._udp_socket((host, port)), # pylint: disable=protected-access throttle_policy, config, ) transport.raiden = MockRaidenService(ADDR) return transport
def mock_matrix( monkeypatch, retry_interval, retries_before_backoff, local_matrix_servers, private_rooms, ): from raiden.network.transport.matrix.client import User monkeypatch.setattr(User, 'get_display_name', lambda _: 'random_display_name') def mock_get_user(klass, user: Union[User, str]) -> User: # pylint: disable=unused-argument return User(None, USERID1) def mock_get_room_ids_for_address( # pylint: disable=unused-argument klass, address: Address, filter_private: bool = None, ) -> List[str]: return ['!roomID:server'] def mock_set_room_id_for_address( # pylint: disable=unused-argument self, address: Address, room_id: Optional[str], ): pass def mock_receive_message(klass, message): # pylint: disable=unused-argument # We are just unit testing the matrix transport receive so do nothing assert message config = dict( retry_interval=retry_interval, retries_before_backoff=retries_before_backoff, server=local_matrix_servers[0], server_name=local_matrix_servers[0].netloc, available_servers=[], global_rooms=['discovery'], private_rooms=private_rooms, ) transport = MatrixTransport(config) transport._raiden_service = MockRaidenService() transport._stop_event.clear() transport._address_to_userids[HOP1] = USERID1 monkeypatch.setattr(MatrixTransport, '_get_user', mock_get_user) monkeypatch.setattr( MatrixTransport, '_get_room_ids_for_address', mock_get_room_ids_for_address, ) monkeypatch.setattr(MatrixTransport, '_set_room_id_for_address', mock_set_room_id_for_address) monkeypatch.setattr(MatrixTransport, '_receive_message', mock_receive_message) return transport
def test_matrix_discovery_room_offline_server( local_matrix_servers, retries_before_backoff, retry_interval, private_rooms, ): transport = MatrixTransport({ 'global_rooms': ['discovery'], 'retries_before_backoff': retries_before_backoff, 'retry_interval': retry_interval, 'server': local_matrix_servers[0], 'server_name': local_matrix_servers[0].netloc, 'available_servers': [local_matrix_servers[0], 'https://localhost:1'], 'private_rooms': private_rooms, }) transport.start(MockRaidenService(None), MessageHandler(set()), '') gevent.sleep(.2) discovery_room_name = make_room_alias(transport.network_id, 'discovery') assert isinstance(transport._global_rooms.get(discovery_room_name), Room) transport.stop() transport.get()
def test_matrix_discovery_room_offline_server( local_matrix_servers, retries_before_backoff, retry_interval_initial, retry_interval_max, broadcast_rooms, ): transport = MatrixTransport( config=MatrixTransportConfig( broadcast_rooms=broadcast_rooms, retries_before_backoff=retries_before_backoff, retry_interval_initial=retry_interval_initial, retry_interval_max=retry_interval_max, server=local_matrix_servers[0], available_servers=[local_matrix_servers[0], "https://localhost:1"], ), environment=Environment.DEVELOPMENT, ) transport.start(MockRaidenService(None), [], "") discovery_room_name = make_room_alias(transport.chain_id, "discovery") with gevent.Timeout(1): while not isinstance(transport._broadcast_rooms.get(discovery_room_name), Room): gevent.sleep(0.1) transport.stop() transport.greenlet.get()
def test_join_invalid_discovery( local_matrix_servers, retry_interval_initial, retry_interval_max, retries_before_backoff, broadcast_rooms, ): """join_broadcast_room tries to join on all servers on available_servers config If any of the servers isn't reachable by synapse, it'll return a 500 response, which needs to be handled, and if no discovery room is found on any of the available_servers, one in our current server should be created """ transport = MatrixTransport( config=MatrixTransportConfig( broadcast_rooms=broadcast_rooms, retries_before_backoff=retries_before_backoff, retry_interval_initial=retry_interval_initial, retry_interval_max=retry_interval_max, server=local_matrix_servers[0], available_servers=["http://invalid.server"], ), environment=Environment.DEVELOPMENT, ) transport._client.api.retry_timeout = 0 transport._send_raw = MagicMock() raiden_service = MockRaidenService(None) transport.start(raiden_service, [], None) transport.log = MagicMock() discovery_room_name = make_room_alias(transport.chain_id, "discovery") assert isinstance(transport._broadcast_rooms.get(discovery_room_name), Room) transport.stop() transport.greenlet.get()
def test_matrix_discovery_room_offline_server(local_matrix_servers, retries_before_backoff, retry_interval, private_rooms, global_rooms): transport = MatrixTransport({ "global_rooms": global_rooms, "retries_before_backoff": retries_before_backoff, "retry_interval": retry_interval, "server": local_matrix_servers[0], "server_name": local_matrix_servers[0].netloc, "available_servers": [local_matrix_servers[0], "https://localhost:1"], "private_rooms": private_rooms, }) transport.start(MockRaidenService(None), MessageHandler(set()), "") gevent.sleep(0.2) discovery_room_name = make_room_alias(transport.network_id, "discovery") assert isinstance(transport._global_rooms.get(discovery_room_name), Room) transport.stop() transport.get()
def test_handle_contract_send_channelunlock_already_unlocked(): """This is a test for the scenario where the onchain unlock has already happened when we get to handle our own send unlock transaction. Regression test for https://github.com/raiden-network/raiden/issues/3152 """ channel_identifier = 1 token_network_identifier = make_address() token_address = make_address() participant = make_address() raiden = MockRaidenService() def detail_participants(participant1, participant2, block_identifier, channel_identifier): transferred_amount = 1 locked_amount = 1 locksroot = make_32bytes() balance_hash = hash_balance_data(transferred_amount, locked_amount, locksroot) our_details = ParticipantDetails( address=raiden.address, deposit=5, withdrawn=0, is_closer=False, balance_hash=balance_hash, nonce=1, locksroot=locksroot, locked_amount=locked_amount, ) transferred_amount = 1 locked_amount = 1 # Let's mock here that partner locksroot is 0x0 locksroot = EMPTY_HASH balance_hash = hash_balance_data(transferred_amount, locked_amount, locksroot) partner_details = ParticipantDetails( address=participant, deposit=5, withdrawn=0, is_closer=True, balance_hash=balance_hash, nonce=1, locksroot=locksroot, locked_amount=locked_amount, ) return ParticipantsDetails(our_details, partner_details) # make sure detail_participants returns partner data with a locksroot of 0x0 raiden.chain.token_network.detail_participants = detail_participants event = ContractSendChannelBatchUnlock( token_address=token_address, token_network_identifier=token_network_identifier, channel_identifier=channel_identifier, participant=participant, ) # This should not throw an unrecoverable error RaidenEventHandler().on_raiden_event(raiden=raiden, event=event)
def test_join_invalid_discovery(local_matrix_servers, private_rooms, retry_interval, retries_before_backoff, global_rooms): """join_global_room tries to join on all servers on available_servers config If any of the servers isn't reachable by synapse, it'll return a 500 response, which needs to be handled, and if no discovery room is found on any of the available_servers, one in our current server should be created """ transport = MatrixTransport({ "global_rooms": global_rooms, "retries_before_backoff": retries_before_backoff, "retry_interval": retry_interval, "server": local_matrix_servers[0], "server_name": local_matrix_servers[0].netloc, "available_servers": ["http://invalid.server"], "private_rooms": private_rooms, }) transport._client.api.retry_timeout = 0 transport._send_raw = MagicMock() raiden_service = MockRaidenService(None) transport.start(raiden_service, raiden_service.message_handler, None) transport.log = MagicMock() discovery_room_name = make_room_alias(transport.network_id, "discovery") assert isinstance(transport._global_rooms.get(discovery_room_name), Room) transport.stop() transport.get()
def test_matrix_invite_private_room_unhappy_case_3( matrix_transports, expected_join_rule, ): raiden_service0 = MockRaidenService(None) raiden_service1 = MockRaidenService(None) transport0, transport1 = matrix_transports transport0.start(raiden_service0, raiden_service0.message_handler, None) transport1.start(raiden_service1, raiden_service1.message_handler, None) transport0.start_health_check(raiden_service1.address) transport1.start_health_check(raiden_service0.address) assert transport1._address_to_presence[ raiden_service0.address].value == 'online' assert transport0._address_to_presence[ raiden_service1.address].value == 'online' transport1.stop() with Timeout(40): while not transport0._address_to_presence[ raiden_service1.address].value == 'offline': gevent.sleep(.1) assert transport0._address_to_presence[ raiden_service1.address].value == 'offline' room_id = transport0._get_room_for_address(raiden_service1.address).room_id transport1.start(raiden_service1, raiden_service1.message_handler, None) transport0.stop() with Timeout(40): while True: try: room_state1 = transport1._client.api.get_room_state(room_id) break except MatrixRequestError: gevent.sleep(.1) join_rule1 = [ event['content'].get('join_rule') for event in room_state1 if event['type'] == 'm.room.join_rules' ][0] assert join_rule1 == expected_join_rule
def test_matrix_user_roaming(matrix_transports): transport0, transport1, transport2 = matrix_transports received_messages0 = set() received_messages1 = set() message_handler0 = MessageHandler(received_messages0) message_handler1 = MessageHandler(received_messages1) raiden_service0 = MockRaidenService(message_handler0) raiden_service1 = MockRaidenService(message_handler1) transport0.start(raiden_service0, message_handler0, "") transport1.start(raiden_service1, message_handler1, "") transport0.start_health_check(raiden_service1.address) transport1.start_health_check(raiden_service0.address) assert ping_pong_message_success(transport0, transport1) transport0.stop() with Timeout(40): while is_reachable(transport1, raiden_service0.address): gevent.sleep(0.1) assert not is_reachable(transport1, raiden_service0.address) transport2.start(raiden_service0, message_handler0, "") transport2.start_health_check(raiden_service1.address) assert ping_pong_message_success(transport2, transport1) transport2.stop() with Timeout(40): while is_reachable(transport1, raiden_service0.address): gevent.sleep(0.1) assert not is_reachable(transport1, raiden_service0.address) transport0.start(raiden_service0, message_handler0, "") with Timeout(40): while not is_reachable(transport1, raiden_service0.address): gevent.sleep(0.1) assert is_reachable(transport1, raiden_service0.address) assert ping_pong_message_success(transport0, transport1)
def test_reproduce_handle_invite_send_race_issue_3588(matrix_transports): transport0, transport1 = matrix_transports received_messages0 = set() received_messages1 = set() message_handler0 = MessageHandler(received_messages0) message_handler1 = MessageHandler(received_messages1) raiden_service0 = MockRaidenService(message_handler0) raiden_service1 = MockRaidenService(message_handler1) transport0.start(raiden_service0, [], "") transport1.start(raiden_service1, [], "") transport0.immediate_health_check_for(raiden_service1.address) transport1.immediate_health_check_for(raiden_service0.address) assert ping_pong_message_success(transport0, transport1)
def test_pfs_global_messages( local_matrix_servers, private_rooms, retry_interval, retries_before_backoff, monkeypatch, global_rooms, ): """ Test that RaidenService sends UpdatePFS messages to global PATH_FINDING_BROADCASTING_ROOM room on newly received balance proofs. """ transport = MatrixTransport({ "global_rooms": global_rooms, # FIXME: #3735 "retries_before_backoff": retries_before_backoff, "retry_interval": retry_interval, "server": local_matrix_servers[0], "server_name": local_matrix_servers[0].netloc, "available_servers": [local_matrix_servers[0]], "private_rooms": private_rooms, }) transport._client.api.retry_timeout = 0 transport._send_raw = MagicMock() raiden_service = MockRaidenService(None) raiden_service.config = dict(services=dict(monitoring_enabled=True)) transport.start(raiden_service, raiden_service.message_handler, None) pfs_room_name = make_room_alias(transport.network_id, PATH_FINDING_BROADCASTING_ROOM) pfs_room = transport._global_rooms.get(pfs_room_name) assert isinstance(pfs_room, Room) pfs_room.send_text = MagicMock(spec=pfs_room.send_text) raiden_service.transport = transport transport.log = MagicMock() balance_proof = factories.create(HOP1_BALANCE_PROOF) channel_state = factories.create(factories.NettingChannelStateProperties()) channel_state.our_state.balance_proof = balance_proof channel_state.partner_state.balance_proof = balance_proof monkeypatch.setattr( raiden.transfer.views, "get_channelstate_by_canonical_identifier", lambda *a, **kw: channel_state, ) update_path_finding_service_from_balance_proof( raiden=raiden_service, chain_state=None, new_balance_proof=balance_proof) gevent.idle() with gevent.Timeout(2): while pfs_room.send_text.call_count < 1: gevent.idle() assert pfs_room.send_text.call_count == 1 transport.stop() transport.get()
def test_matrix_invite_private_room_happy_case( matrix_transports, expected_join_rule, ): raiden_service0 = MockRaidenService(None) raiden_service1 = MockRaidenService(None) transport0, transport1 = matrix_transports transport0.start(raiden_service0, raiden_service0.message_handler, None) transport1.start(raiden_service1, raiden_service1.message_handler, None) transport0.start_health_check(transport1._raiden_service.address) transport1.start_health_check(transport0._raiden_service.address) room_id = transport0._get_room_for_address(raiden_service1.address).room_id with Timeout(40): while True: try: room_state0 = transport0._client.api.get_room_state(room_id) break except MatrixRequestError: gevent.sleep(.1) join_rule0 = [ event['content'].get('join_rule') for event in room_state0 if event['type'] == 'm.room.join_rules' ][0] assert join_rule0 == expected_join_rule with Timeout(40): while True: try: room_state1 = transport1._client.api.get_room_state(room_id) break except MatrixRequestError: gevent.sleep(.1) join_rule1 = [ event['content'].get('join_rule') for event in room_state1 if event['type'] == 'm.room.join_rules' ][0] assert join_rule1 == expected_join_rule
def test_web_rtc_message_sync(matrix_transports): transport0, transport1 = matrix_transports transport1_messages = set() raiden_service0 = MockRaidenService() raiden_service1 = MockRaidenService() def mock_handle_web_rtc_messages(message_data, partner_address): messages = validate_and_parse_message(message_data, partner_address) transport1_messages.update(messages) # set mock function to make sure messages are sent via web rtc transport1._web_rtc_manager._handle_message_callback = mock_handle_web_rtc_messages transport0.start(raiden_service0, [], None) transport1.start(raiden_service1, [], None) transport0.immediate_health_check_for(transport1._raiden_service.address) transport1.immediate_health_check_for(transport0._raiden_service.address) with Timeout(TIMEOUT_WEB_RTC_CONNECTION): # wait until web rtc connection is ready while not transport0._web_rtc_manager.has_ready_channel(raiden_service1.address): gevent.sleep(1) while not transport1._web_rtc_manager.has_ready_channel(raiden_service0.address): gevent.sleep(1) queue_identifier = QueueIdentifier( recipient=transport1._raiden_service.address, canonical_identifier=factories.UNIT_CANONICAL_ID, ) raiden0_queues = views.get_all_messagequeues(views.state_from_raiden(raiden_service0)) raiden0_queues[queue_identifier] = [] for i in range(5): message = Processed(message_identifier=MessageID(i), signature=EMPTY_SIGNATURE) raiden0_queues[queue_identifier].append(message) transport0._raiden_service.sign(message) transport0.send_async([MessagesQueue(queue_identifier, [message])]) with Timeout(TIMEOUT_MESSAGE_RECEIVE): while not len(transport1_messages) == 5: gevent.sleep(0.1)
def test_assumption_receive_all_state_events_upon_first_sync_after_join( matrix_transports, number_of_transports, monkeypatch ): """ Test that independently of the number of timeline events in the room the first sync after the join always contains all room state events more explicitly all member joins. This means the user always knows all members of a room at the first sync after the joining the room. (Some state events are placed in the timeline history. That does not change the logic but it must be given that no state events are filtered due to limitation of the timeline limit filter) """ transports: List[MatrixTransport] = list() # it is necessary to monkeypatch leave_unexpected_rooms # otherwise rooms would be left automatically when members > 2 monkeypatch.setattr( MatrixTransport, "_leave_unexpected_rooms", lambda self, rooms_to_leave, reason: None ) # start all transports for transport in matrix_transports: raiden_service = MockRaidenService() transport.start(raiden_service, [], None) transports.append(transport) transport0 = transports[0] transport1 = transports[1] room0 = transport0._client.create_room() # invite every user but transport[1] for transport in transports[2:]: room0.invite_user(transport._user_id) transport0._client.synced.wait() # wait for every user to be joined while len(room0.get_joined_members()) < number_of_transports - 1: transport0._client.synced.wait() # start filling timeline events by sending messages for i in range(1, 100): room0.send_text(f"ping{i}") gevent.sleep(0.05) # finally invite transport[1] room0.invite_user(transport1._user_id) # wait for the first sync after join while room0.room_id not in transport1._client.rooms: transport1._client.synced.wait() transport1._client.synced.wait() # check that all information about existing members are received assert ( len(transport1._client.rooms[room0.room_id].get_joined_members()) == number_of_transports )
def test_matrix_invite_private_room_happy_case(matrix_transports): """ Test that a room has been created between two communicating nodes.""" raiden_service0 = MockRaidenService(None) raiden_service1 = MockRaidenService(None) transport0, transport1 = matrix_transports transport0.start(raiden_service0, [], None) transport1.start(raiden_service1, [], None) transport0.start_health_check(transport1._raiden_service.address) transport1.start_health_check(transport0._raiden_service.address) room = transport0._get_room_for_address(raiden_service1.address) # Transport0 is on the higher end of the lexical order of the addresses. # It did not create the room and therefore we check that the other # node creates it. if room is None: room = transport1._maybe_create_room_for_address( raiden_service0.address) room_id = room.room_id with Timeout(TIMEOUT_MESSAGE_RECEIVE): while True: try: room_state0 = transport0._client.api.get_room_state(room_id) break except MatrixRequestError: gevent.sleep(0.1) assert room_state0 is not None with Timeout(TIMEOUT_MESSAGE_RECEIVE): while True: try: room_state1 = transport1._client.api.get_room_state(room_id) break except MatrixRequestError: gevent.sleep(0.1) assert room_state1 is not None
def mock_matrix(monkeypatch, retry_interval, retries_before_backoff): from raiden.network.transport.matrix.client import User from raiden.network.transport.matrix import transport as transport_module monkeypatch.setattr(User, "get_display_name", lambda _: "random_display_name") monkeypatch.setattr(transport_module, "make_client", lambda url, *a, **kw: GMatrixClient(url[0])) def mock_get_user(klass, user: Union[User, str]) -> User: # pylint: disable=unused-argument return User(None, USERID1) def mock_get_room_ids_for_address( # pylint: disable=unused-argument klass, address: Address, filter_private: bool = None) -> List[str]: return ["!roomID:server"] def mock_set_room_id_for_address( # pylint: disable=unused-argument self, address: Address, room_id: Optional[str]): pass def mock_receive_message(klass, message): # pylint: disable=unused-argument # We are just unit testing the matrix transport receive so do nothing assert message assert message.sender config = dict( retry_interval=retry_interval, retries_before_backoff=retries_before_backoff, server="http://none", server_name="none", available_servers=[], global_rooms=[], private_rooms=False, ) transport = MatrixTransport(config) transport._raiden_service = MockRaidenService() transport._stop_event.clear() transport._address_mgr.add_userid_for_address(factories.HOP1, USERID1) transport._client.user_id = USERID0 monkeypatch.setattr(MatrixTransport, "_get_user", mock_get_user) monkeypatch.setattr(MatrixTransport, "_get_room_ids_for_address", mock_get_room_ids_for_address) monkeypatch.setattr(MatrixTransport, "_set_room_id_for_address", mock_set_room_id_for_address) monkeypatch.setattr(MatrixTransport, "_receive_message", mock_receive_message) return transport
def test_monitoring_global_messages( local_matrix_servers, private_rooms, retry_interval, retries_before_backoff, ): """ Test that RaidenService sends RequestMonitoring messages to global MONITORING_BROADCASTING_ROOM room on newly received balance proofs. """ transport = MatrixTransport({ 'global_rooms': ['discovery', MONITORING_BROADCASTING_ROOM], 'retries_before_backoff': retries_before_backoff, 'retry_interval': retry_interval, 'server': local_matrix_servers[0], 'server_name': local_matrix_servers[0].netloc, 'available_servers': [local_matrix_servers[0]], 'private_rooms': private_rooms, }) transport._client.api.retry_timeout = 0 transport._send_raw = MagicMock() raiden_service = MockRaidenService(None) raiden_service.config = dict(services=dict(monitoring_enabled=True)) transport.start( raiden_service, raiden_service.message_handler, None, ) ms_room_name = make_room_alias(transport.network_id, MONITORING_BROADCASTING_ROOM) ms_room = transport._global_rooms.get(ms_room_name) assert isinstance(ms_room, Room) ms_room.send_text = MagicMock(spec=ms_room.send_text) raiden_service.transport = transport transport.log = MagicMock() balance_proof = make_balance_proof(signer=LocalSigner(HOP1_KEY), amount=1) update_monitoring_service_from_balance_proof( raiden_service, balance_proof, ) gevent.idle() assert ms_room.send_text.call_count == 1 transport.stop() transport.get()