2019-04-29 05:38:40 +08:00
|
|
|
import ast
|
|
|
|
|
2019-03-27 03:44:01 +08:00
|
|
|
from libp2p.routing.interfaces import IPeerRouting
|
2019-04-29 05:38:40 +08:00
|
|
|
from libp2p.kademlia.kad_peerinfo import create_kad_peerinfo
|
2019-03-27 03:44:01 +08:00
|
|
|
|
|
|
|
|
|
|
|
class KadmeliaPeerRouter(IPeerRouting):
|
2019-04-18 08:21:59 +08:00
|
|
|
# pylint: disable=too-few-public-methods
|
2019-03-27 03:44:01 +08:00
|
|
|
|
|
|
|
def __init__(self, dht_server):
|
|
|
|
self.server = dht_server
|
|
|
|
|
2019-04-28 09:59:25 +08:00
|
|
|
async def find_peer(self, peer_id):
|
2019-03-27 03:44:01 +08:00
|
|
|
"""
|
|
|
|
Find specific Peer
|
|
|
|
FindPeer searches for a peer with given peer_id, returns a peer.PeerInfo
|
|
|
|
with relevant addresses.
|
|
|
|
"""
|
2019-04-25 10:11:54 +08:00
|
|
|
# switching peer_id to xor_id used by kademlia as node_id
|
|
|
|
xor_id = peer_id.get_xor_id()
|
2019-04-28 09:59:25 +08:00
|
|
|
value = await self.server.get(xor_id)
|
2019-04-29 05:38:40 +08:00
|
|
|
return decode_peerinfo(value)
|
2019-03-27 03:44:01 +08:00
|
|
|
|
2019-04-29 05:38:40 +08:00
|
|
|
def decode_peerinfo(encoded):
|
|
|
|
if isinstance(encoded, bytes):
|
|
|
|
encoded = encoded.decode()
|
|
|
|
print(encoded)
|
|
|
|
try:
|
|
|
|
lines = ast.literal_eval(encoded)
|
|
|
|
except SyntaxError:
|
|
|
|
return None
|
|
|
|
# xor_id = lines[0]
|
|
|
|
ip = lines[1] # pylint: disable=invalid-name
|
|
|
|
port = lines[2]
|
|
|
|
peer_id = lines[3]
|
|
|
|
peer_info = create_kad_peerinfo(peer_id, ip, port)
|
|
|
|
return peer_info
|