Beispiel #1
0
 async def _swarm_stream_handler(self, net_stream: INetStream) -> None:
     # Perform protocol muxing to determine protocol to use
     try:
         protocol, handler = await self.multiselect.negotiate(
             MultiselectCommunicator(net_stream))
     except MultiselectError:
         await net_stream.reset()
         return
     net_stream.set_protocol(protocol)
     await handler(net_stream)
Beispiel #2
0
 async def stream_handler(self, stream: INetStream) -> None:
     """
     Stream handler for pubsub. Gets invoked whenever a new stream is created
     on one of the supported pubsub protocols.
     :param stream: newly created stream
     """
     try:
         await self.continuously_read_stream(stream)
     except (StreamEOF, StreamReset) as error:
         logger.debug("fail to read from stream, error=%s", error)
         stream.reset()
Beispiel #3
0
 async def _swarm_stream_handler(self, net_stream: INetStream) -> None:
     # Perform protocol muxing to determine protocol to use
     try:
         protocol, handler = await self.multiselect.negotiate(
             MultiselectCommunicator(net_stream))
     except MultiselectError as error:
         peer_id = net_stream.muxed_conn.peer_id
         logger.debug("failed to accept a stream from peer %s, error=%s",
                      peer_id, error)
         await net_stream.reset()
         return
     net_stream.set_protocol(protocol)
     await handler(net_stream)
Beispiel #4
0
async def _handle_ping(stream: INetStream, peer_id: PeerID) -> bool:
    """Return a boolean indicating if we expect more pings from the peer at
    ``peer_id``."""
    try:
        payload = await asyncio.wait_for(stream.read(PING_LENGTH),
                                         RESP_TIMEOUT)
    except asyncio.TimeoutError as error:
        logger.debug("Timed out waiting for ping from %s: %s", peer_id, error)
        raise
    except StreamEOF:
        logger.debug("Other side closed while waiting for ping from %s",
                     peer_id)
        return False
    except StreamReset as error:
        logger.debug("Other side reset while waiting for ping from %s: %s",
                     peer_id, error)
        raise
    except Exception as error:
        logger.debug("Error while waiting to read ping for %s: %s", peer_id,
                     error)
        raise

    logger.debug("Received ping from %s with data: 0x%s", peer_id,
                 payload.hex())

    await stream.write(payload)
    return True
Beispiel #5
0
async def read_resp(
    stream: INetStream,
    msg_type: Type[MsgType],
) -> Tuple[ResponseCode, Union[MsgType, str]]:
    """
    Read a `MsgType` response message from the `stream`.
    `ReadMessageFailure` is raised if fail to read the message.
    Returns the error message(type `str`) if the response code is not SUCCESS, otherwise returns
    the `MsgType` response message.
    """
    try:
        result_bytes = await asyncio.wait_for(stream.read(1),
                                              timeout=TTFB_TIMEOUT)
    # TODO: Catch more errors?
    except asyncio.TimeoutError as error:
        raise ReadMessageFailure("failed to read `result_bytes`") from error
    if len(result_bytes) != 1:
        raise ReadMessageFailure(
            f"result bytes should be of length 1: result_bytes={result_bytes}")
    try:
        resp_code = ResponseCode(result_bytes[0])
    except ValueError:
        raise ReadMessageFailure(f"unknown resp_code={result_bytes[0]}")
    msg: Union[MsgType, str]
    # `MsgType`
    if resp_code == ResponseCode.SUCCESS:
        msg = await _read_ssz_msg(stream, msg_type, timeout=RESP_TIMEOUT)
    # error message
    else:
        msg_bytes = await _read_varint_prefixed_bytes(stream,
                                                      timeout=RESP_TIMEOUT)
        msg = msg_bytes.decode("utf-8")
    return resp_code, msg
Beispiel #6
0
async def _read_stream(stream: INetStream, len_payload: int, timeout: float) -> bytes:
    try:
        return await asyncio.wait_for(stream.read(len_payload), timeout)
    except asyncio.TimeoutError:
        raise ReadMessageFailure("Timeout")
    except StreamEOF as error:
        await stream.close()
        raise ReadMessageFailure() from error
    except StreamReset as error:
        raise ReadMessageFailure() from error
Beispiel #7
0
    async def stream_handler(self, stream: INetStream) -> None:
        """
        Stream handler for pubsub. Gets invoked whenever a new stream is created
        on one of the supported pubsub protocols.
        :param stream: newly created stream
        """
        # Add peer
        # Map peer to stream
        peer_id = stream.mplex_conn.peer_id
        self.peers[str(peer_id)] = stream
        self.router.add_peer(peer_id, stream.get_protocol())

        # Send hello packet
        hello = self.get_hello_packet()

        await stream.write(hello)
        # Pass stream off to stream reader
        asyncio.ensure_future(self.continuously_read_stream(stream))
Beispiel #8
0
async def _read_varint_prefixed_bytes(
    stream: INetStream,
    timeout: float = None,
) -> bytes:
    try:
        len_payload = await decode_uvarint_from_stream(stream, timeout)
    # TODO: Catch more errors?
    except asyncio.TimeoutError as error:
        raise ReadMessageFailure(
            "failed to read the length of the payload") from error
    if len_payload > REQ_RESP_MAX_SIZE:
        raise ReadMessageFailure(
            f"size_of_payload={len_payload} is larger than maximum={REQ_RESP_MAX_SIZE}"
        )
    try:
        payload = await asyncio.wait_for(stream.read(len_payload), timeout)
    # TODO: Catch more errors?
    except asyncio.TimeoutError as error:
        raise ReadMessageFailure("failed to read the payload") from error
    if len(payload) != len_payload:
        raise ReadMessageFailure(
            f"expected {len_payload} bytes, but only read {len(payload)}")
    return payload