py-libp2p/libp2p/security/secure_session.py

83 lines
2.2 KiB
Python
Raw Normal View History

2020-02-17 17:06:00 +08:00
import io
from libp2p.crypto.keys import PrivateKey, PublicKey
from libp2p.io.abc import EncryptedMsgReadWriter
2020-02-09 00:33:26 +08:00
from libp2p.peer.id import ID
from libp2p.security.base_session import BaseSession
class SecureSession(BaseSession):
2020-02-17 17:06:00 +08:00
buf: io.BytesIO
low_watermark: int
high_watermark: int
2020-02-09 00:33:26 +08:00
def __init__(
self,
*,
2020-02-09 00:33:26 +08:00
local_peer: ID,
local_private_key: PrivateKey,
remote_peer: ID,
remote_permanent_pubkey: PublicKey,
2020-02-09 00:33:26 +08:00
is_initiator: bool,
conn: EncryptedMsgReadWriter,
2020-02-09 00:33:26 +08:00
) -> None:
super().__init__(
local_peer=local_peer,
local_private_key=local_private_key,
remote_peer=remote_peer,
remote_permanent_pubkey=remote_permanent_pubkey,
is_initiator=is_initiator,
)
2020-02-09 00:33:26 +08:00
self.conn = conn
self._reset_internal_buffer()
2020-02-17 17:06:00 +08:00
def _reset_internal_buffer(self) -> None:
self.buf = io.BytesIO()
self.low_watermark = 0
self.high_watermark = 0
def _drain(self, n: int) -> bytes:
if self.low_watermark == self.high_watermark:
return bytes()
data = self.buf.getbuffer()[self.low_watermark : self.high_watermark]
if n is None:
n = len(data)
result = data[:n].tobytes()
self.low_watermark += len(result)
if self.low_watermark == self.high_watermark:
del data # free the memoryview so we can free the underlying BytesIO
self.buf.close()
self._reset_internal_buffer()
return result
def _fill(self, msg: bytes) -> None:
self.buf.write(msg)
self.low_watermark = 0
self.high_watermark = len(msg)
2020-02-09 00:33:26 +08:00
async def read(self, n: int = None) -> bytes:
2020-02-17 17:06:00 +08:00
if n == 0:
return bytes()
data_from_buffer = self._drain(n)
if len(data_from_buffer) > 0:
return data_from_buffer
msg = await self.conn.read_msg()
2020-02-17 17:06:00 +08:00
if n < len(msg):
self._fill(msg)
2020-02-17 17:06:00 +08:00
return self._drain(n)
else:
return msg
2020-02-09 00:33:26 +08:00
async def write(self, data: bytes) -> None:
await self.conn.write_msg(data)
2020-02-09 00:33:26 +08:00
async def close(self) -> None:
await self.conn.close()