py-libp2p/libp2p/routing/kademlia/kademlia_peer_router.py

24 lines
828 B
Python
Raw Normal View History

2019-07-27 17:10:03 +08:00
from libp2p.kademlia.network import KademliaServer
from libp2p.peer.id import ID
from libp2p.peer.peerinfo import PeerInfo
2019-03-27 03:44:01 +08:00
from libp2p.routing.interfaces import IPeerRouting
class KadmeliaPeerRouter(IPeerRouting):
2019-07-27 17:10:03 +08:00
server: KademliaServer
def __init__(self, dht_server: KademliaServer) -> None:
2019-03-27 03:44:01 +08:00
self.server = dht_server
async def find_peer(self, peer_id: ID) -> PeerInfo:
2019-03-27 03:44:01 +08:00
"""
2019-05-06 02:32:41 +08:00
Find a specific peer
:param peer_id: peer to search for
:return: PeerInfo of specified peer
2019-03-27 03:44:01 +08:00
"""
# switching peer_id to xor_id used by kademlia as node_id
2019-07-31 19:26:13 +08:00
xor_id = peer_id.xor_id
# ignore type for kad
value = await self.server.get(xor_id) # type: ignore
return PeerInfo.info_from_string(value) if value else None # TODO: should raise error if None?