2019-10-25 17:51:24 +08:00
|
|
|
import logging
|
|
|
|
|
|
|
|
from multiaddr import Multiaddr
|
|
|
|
|
2019-10-28 17:47:10 +08:00
|
|
|
from libp2p.host.host_interface import IHost
|
2019-11-12 18:07:30 +08:00
|
|
|
from libp2p.network.stream.exceptions import StreamClosed
|
2019-10-25 17:51:24 +08:00
|
|
|
from libp2p.network.stream.net_stream_interface import INetStream
|
2019-11-07 07:21:30 +08:00
|
|
|
from libp2p.typing import StreamHandlerFn, TProtocol
|
2019-10-25 17:51:24 +08:00
|
|
|
|
|
|
|
from .pb.identify_pb2 import Identify
|
|
|
|
|
2019-11-07 07:21:30 +08:00
|
|
|
ID = TProtocol("/ipfs/id/1.0.0")
|
2019-10-25 17:51:24 +08:00
|
|
|
PROTOCOL_VERSION = "ipfs/0.1.0"
|
|
|
|
# TODO dynamically generate the agent version
|
|
|
|
AGENT_VERSION = "py-libp2p/alpha"
|
|
|
|
logger = logging.getLogger("libp2p.identity.identify")
|
|
|
|
|
|
|
|
|
|
|
|
def _multiaddr_to_bytes(maddr: Multiaddr) -> bytes:
|
|
|
|
return maddr.to_bytes()
|
|
|
|
|
|
|
|
|
2019-11-07 07:18:40 +08:00
|
|
|
def _mk_identify_protobuf(host: IHost) -> Identify:
|
|
|
|
public_key = host.get_public_key()
|
|
|
|
laddrs = host.get_addrs()
|
|
|
|
protocols = host.get_mux().get_protocols()
|
|
|
|
|
|
|
|
return Identify(
|
|
|
|
protocol_version=PROTOCOL_VERSION,
|
|
|
|
agent_version=AGENT_VERSION,
|
|
|
|
public_key=public_key.serialize(),
|
|
|
|
listen_addrs=map(_multiaddr_to_bytes, laddrs),
|
|
|
|
# TODO send observed address from ``stream``
|
|
|
|
observed_addr=b"",
|
|
|
|
protocols=protocols,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2019-10-28 17:47:10 +08:00
|
|
|
def identify_handler_for(host: IHost) -> StreamHandlerFn:
|
2019-10-25 17:51:24 +08:00
|
|
|
async def handle_identify(stream: INetStream) -> None:
|
2019-10-25 19:18:40 +08:00
|
|
|
peer_id = stream.muxed_conn.peer_id
|
2019-11-06 09:17:07 +08:00
|
|
|
logger.debug("received a request for %s from %s", ID, peer_id)
|
2019-10-25 17:51:24 +08:00
|
|
|
|
2019-11-07 07:18:40 +08:00
|
|
|
protobuf = _mk_identify_protobuf(host)
|
2019-10-25 17:51:24 +08:00
|
|
|
response = protobuf.SerializeToString()
|
|
|
|
|
2019-11-12 18:07:30 +08:00
|
|
|
try:
|
|
|
|
await stream.write(response)
|
|
|
|
except StreamClosed:
|
|
|
|
logger.debug("Fail to respond to %s request: stream closed", ID)
|
|
|
|
else:
|
|
|
|
await stream.close()
|
|
|
|
logger.debug("successfully handled request for %s from %s", ID, peer_id)
|
2019-10-25 17:51:24 +08:00
|
|
|
|
|
|
|
return handle_identify
|