2020-02-17 16:30:44 +08:00
|
|
|
from noise.connection import NoiseConnection as NoiseState
|
|
|
|
|
2020-02-09 00:33:26 +08:00
|
|
|
from libp2p.crypto.keys import PrivateKey
|
|
|
|
from libp2p.network.connection.raw_connection_interface import IRawConnection
|
|
|
|
from libp2p.peer.id import ID
|
|
|
|
from libp2p.security.base_session import BaseSession
|
2020-02-17 16:30:44 +08:00
|
|
|
from libp2p.security.noise.io import MsgReadWriter, NoiseTransportReadWriter
|
2020-02-09 00:33:26 +08:00
|
|
|
|
|
|
|
|
|
|
|
class NoiseConnection(BaseSession):
|
2020-02-17 16:30:44 +08:00
|
|
|
read_writer: IRawConnection
|
|
|
|
noise_state: NoiseState
|
2020-02-09 00:33:26 +08:00
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
local_peer: ID,
|
|
|
|
local_private_key: PrivateKey,
|
|
|
|
remote_peer: ID,
|
|
|
|
conn: IRawConnection,
|
|
|
|
is_initiator: bool,
|
2020-02-17 16:30:44 +08:00
|
|
|
noise_state: NoiseState,
|
2020-02-09 00:33:26 +08:00
|
|
|
) -> None:
|
|
|
|
super().__init__(local_peer, local_private_key, is_initiator, remote_peer)
|
|
|
|
self.conn = conn
|
2020-02-17 16:30:44 +08:00
|
|
|
self.noise_state = noise_state
|
|
|
|
|
|
|
|
def get_msg_read_writer(self) -> MsgReadWriter:
|
|
|
|
return NoiseTransportReadWriter(self.conn, self.noise_state)
|
2020-02-09 00:33:26 +08:00
|
|
|
|
|
|
|
async def read(self, n: int = None) -> bytes:
|
2020-02-17 16:30:44 +08:00
|
|
|
# TODO: Use a buffer to handle buffered messages.
|
|
|
|
return await self.get_msg_read_writer().read_msg()
|
2020-02-09 00:33:26 +08:00
|
|
|
|
|
|
|
async def write(self, data: bytes) -> None:
|
2020-02-17 16:30:44 +08:00
|
|
|
await self.get_msg_read_writer().write_msg(data)
|
2020-02-09 00:33:26 +08:00
|
|
|
|
|
|
|
async def close(self) -> None:
|
|
|
|
await self.conn.close()
|