示例#1
0
    def read_connection_packet(self):
        if len(self.recvbuf) < 3:
            return None

        packet_size = struct.unpack("<L", rzpad(self.recvbuf[:3], 4))[0]
        if len(self.recvbuf) < 3 + packet_size:
            return

        self.recvbuf = self.recvbuf[3:]
        packet = self.recvbuf[:packet_size]
        self.recvbuf = self.recvbuf[packet_size:]

        if len(packet) > 3:
            packet = packet[-3:] + packet[:-3]

        return packet
示例#2
0
    def _on_data(self):
        """Try to read P2P messages from the recv buffer.

        This method reads data from the buffer in a loop. It deserializes,
        parses and verifies the P2P header, then passes the P2P payload to
        the on_message callback for processing."""
        try:
            while True:
                if len(self.recvbuf) < 3:
                    return
                packet_size = struct.unpack("<L", rzpad(self.recvbuf[:3],
                                                        4))[0]
                if len(self.recvbuf) < 3 + packet_size:
                    return
                packet_id = self.recvbuf[3]
                if packet_id != PACKET_HELLO and packet_id != PACKET_DISCONNECT and (
                        not self.had_hello):
                    raise ValueError("bad protocol")
                payload = self.recvbuf[4:3 + packet_size]
                self.recvbuf = self.recvbuf[3 + packet_size:]
                self._log_message("receive", packet_id)
                if packet_id == PACKET_HELLO:
                    self.on_hello(payload)
                elif packet_id == PACKET_DISCONNECT:
                    disconnect = rlp.decode(payload, Disconnect)
                    self.on_disconnect(disconnect)
                elif packet_id == PACKET_PING:
                    self.on_ping()
                elif packet_id == PACKET_PONG:
                    self.on_pong()
                elif packet_id == PACKET_PONG:
                    pass
                else:
                    assert packet_id == PACKET_PROTOCOL
                    self.on_protocol_packet(payload)
        except Exception as e:
            logger.exception('Error reading message: ' + repr(e))
            raise