# Buggy code
def _handle_message(self, room: Room, event: Dict[str, Any]) -> bool:
    """Handle text messages sent to listening rooms"""
    if self._stop_event.ready():
        return False

    is_valid_type = (
        event["type"] == "m.room.message" and event["content"]["msgtype"] == "m.text"
    )
    if not is_valid_type:
        return False

    sender_id = event["sender"]

    if sender_id == self._user_id:
        # Ignore our own messages
        return False

    user = self._client.get_user(sender_id)
    self._displayname_cache.warm_users([user])

    peer_address = validate_userid_signature(user)
    if not peer_address:
        self.log.debug(
            "Ignoring message from user with an invalid display name signature",
            peer_user=user.user_id,
            room=room,
        )
        return False

    if not self._address_mgr.is_address_known(peer_address):
        self.log.debug(
            "Ignoring message from non-whitelisted peer",
            sender=user,
            sender_address=to_checksum_address(peer_address),
            room=room,
        )
        return False

    # rooms we created and invited user, or were invited specifically by them
    room_ids = self._get_room_ids_for_address(peer_address)

    if room.room_id not in room_ids:
        self.log.debug(
            "Ignoring invalid message",
            peer_user=user.user_id,
            peer_address=to_checksum_address(peer_address),
            room=room,
            expected_room_ids=room_ids,
            reason="unknown room for user",
        )
        return False

    # TODO: With the condition in the TODO above restored this one won't have an effect, check
    #       if it can be removed after the above is solved
    if not room_ids or room.room_id != room_ids[0]:
        if self._is_broadcast_room(room):
            # This must not happen. Nodes must not listen on broadcast rooms.
            raise RuntimeError(f"Received message in broadcast room {room.aliases}.")
        self.log.debug(
            "Received message triggered new comms room for peer",
            peer_user=user.user_id,
            peer_address=to_checksum_address(peer_address),
            known_user_rooms=room_ids,
            room=room,
        )
        self._set_room_id_for_address(peer_address, room.room_id)

    messages = validate_and_parse_message(event["content"]["body"], peer_address)

    if not messages:
        return False

    self.log.debug(
        "Incoming messages",
        messages=messages,
        sender=to_checksum_address(peer_address),
        sender_user=user,
        room=room,
    )

    for message in messages:
        if not isinstance(message, (SignedRetrieableMessage, SignedMessage)):
            self.log.warning(
                "Received invalid message",
                message=redact_secret(DictSerializer.serialize(message)),
            )
        if isinstance(message, Delivered):
            self._receive_delivered(message)
        elif isinstance(message, Processed):
            self._receive_message(message)
        else:
            assert isinstance(message, SignedRetrieableMessage)
            self._receive_message(message)

    return True


# Traceback (nurllib3.exceptions.ProtocolError)
{
"task": "<TransferTask: {'from': 0, 'to': 1, 'amount': 500000000000000000, 'expected_http_status': 200}>",
"event": "Task errored",
"logger": "scenario_player.tasks.base",
"level": "error",
"timestamp": "2019-11-12 01:58:24.322286",
"exception": "Traceback (most recent call last):\n  File \"/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py\", line 603, in urlopen\n    chunked=chunked)\n  File \"/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py\", line 387, in _make_request\n    six.raise_from(e, None)\n  File \"<string>\", line 2, in raise_from\n  File \"/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py\", line 383, in _make_request\n    httplib_response = conn.getresponse()\n  File \"/usr/local/lib/python3.7/http/client.py\", line 1321, in getresponse\n    response.begin()\n  File \"/usr/local/lib/python3.7/http/client.py\", line 296, in begin\n    version, status, reason = self._read_status()\n  File \"/usr/local/lib/python3.7/http/client.py\", line 265, in _read_status\n    raise RemoteDisconnected(\"Remote end closed connection without\"\nhttp.client.RemoteDisconnected: Remote end closed connection without response\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/usr/local/lib/python3.7/site-packages/requests/adapters.py\", line 449, in send\n    timeout=timeout\n  File \"/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py\", line 641, in urlopen\n    _stacktrace=sys.exc_info()[2])\n  File \"/usr/local/lib/python3.7/site-packages/urllib3/util/retry.py\", line 368, in increment\n    raise six.reraise(type(error), error, _stacktrace)\n  File \"/usr/local/lib/python3.7/site-packages/urllib3/packages/six.py\", line 685, in reraise\n    raise value.with_traceback(tb)\n  File \"/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py\", line 603, in urlopen\n    chunked=chunked)\n  File \"/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py\", line 387, in _make_request\n    six.raise_from(e, None)\n  File \"<string>\", line 2, in raise_from\n  File \"/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py\", line 383, in _make_request\n    httplib_response = conn.getresponse()\n  File \"/usr/local/lib/python3.7/http/client.py\", line 1321, in getresponse\n    response.begin()\n  File \"/usr/local/lib/python3.7/http/client.py\", line 296, in begin\n    version, status, reason = self._read_status()\n  File \"/usr/local/lib/python3.7/http/client.py\", line 265, in _read_status\n    raise RemoteDisconnected(\"Remote end closed connection without\"\nurllib3.exceptions.ProtocolError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/usr/local/lib/python3.7/site-packages/scenario_player/tasks/api_base.py\", line 51, in _run\n    method=self._method, url=url, json=self._request_params, timeout=self._timeout\n  File \"/usr/local/lib/python3.7/site-packages/requests/sessions.py\", line 533, in request\n    resp = self.send(prep, **send_kwargs)\n  File \"/usr/local/lib/python3.7/site-packages/requests/sessions.py\", line 646, in send\n    r = adapter.send(request, **kwargs)\n  File \"/usr/local/lib/python3.7/site-packages/requests/adapters.py\", line 498, in send\n    raise ConnectionError(err, request=request)\nrequests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response'))\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n  File \"/usr/local/lib/python3.7/site-packages/scenario_player/tasks/base.py\", line 74, in __call__\n    return self._run(*args, **kwargs)\n  File \"/usr/local/lib/python3.7/site-packages/scenario_player/tasks/api_base.py\", line 56, in _run\n    raise RESTAPIError(f\"Error performing REST-API call: {self._name}\") from ex\nscenario_player.exceptions.legacy.RESTAPIError: Error performing REST-API call: transfer"
}

# Fixed code
def _handle_message(self, room: Room, event: Dict[str, Any]) -> bool:
    """Handle text messages sent to listening rooms"""
    if self._stop_event.ready():
        return False

    is_valid_type = (
        event["type"] == "m.room.message" and event["content"]["msgtype"] == "m.text"
    )
    if not is_valid_type:
        return False

    sender_id = event["sender"]

    if sender_id == self._user_id:
        # Ignore our own messages
        return False

    user = self._client.get_user(sender_id)
    self._displayname_cache.warm_users([user])

    peer_address = validate_userid_signature(user)
    if not peer_address:
        self.log.debug(
            "Ignoring message from user with an invalid display name signature",
            peer_user=user.user_id,
            room=room,
        )
        return False

    if self._is_broadcast_room(room):
        # This must not happen. Nodes must not listen on broadcast rooms.
        raise RuntimeError(
            f"Received message in broadcast room {room.aliases[0]}. Sending user: {user}"
        )

    if not self._address_mgr.is_address_known(peer_address):
        self.log.debug(
            "Ignoring message from non-whitelisted peer",
            sender=user,
            sender_address=to_checksum_address(peer_address),
            room=room,
        )
        return False

    # rooms we created and invited user, or were invited specifically by them
    room_ids = self._get_room_ids_for_address(peer_address)

    if room.room_id not in room_ids:
        self.log.debug(
            "Ignoring invalid message",
            peer_user=user.user_id,
            peer_address=to_checksum_address(peer_address),
            room=room,
            expected_room_ids=room_ids,
            reason="unknown room for user",
        )
        return False

    messages = validate_and_parse_message(event["content"]["body"], peer_address)

    if not messages:
        return False

    self.log.debug(
        "Incoming messages",
        messages=messages,
        sender=to_checksum_address(peer_address),
        sender_user=user,
        room=room,
    )

    for message in messages:
        if not isinstance(message, (SignedRetrieableMessage, SignedMessage)):
            self.log.warning(
                "Received invalid message",
                message=redact_secret(DictSerializer.serialize(message)),
            )
        if isinstance(message, Delivered):
            self._receive_delivered(message)
        elif isinstance(message, Processed):
            self._receive_message(message)
        else:
            assert isinstance(message, SignedRetrieableMessage)
            self._receive_message(message)

    return True