2018-11-29 23:06:40 +08:00
|
|
|
import multiaddr
|
|
|
|
import multiaddr.util
|
|
|
|
from peer.id import id_b58_decode
|
|
|
|
from peer.peerdata import PeerData
|
|
|
|
|
|
|
|
|
2018-10-29 21:09:47 +08:00
|
|
|
class PeerInfo:
|
2018-11-27 07:24:29 +08:00
|
|
|
# pylint: disable=too-few-public-methods
|
2018-10-29 21:09:47 +08:00
|
|
|
def __init__(self, peer_id, peer_data):
|
|
|
|
self.peer_id = peer_id
|
|
|
|
self.addrs = peer_data.get_addrs()
|
2018-11-29 23:06:40 +08:00
|
|
|
|
|
|
|
|
|
|
|
def info_from_p2p_addr(addr):
|
|
|
|
if not addr:
|
|
|
|
raise InvalidAddrError()
|
|
|
|
|
|
|
|
parts = multiaddr.util.split(addr)
|
|
|
|
if not parts:
|
|
|
|
raise InvalidAddrError()
|
|
|
|
|
2018-12-28 15:01:50 +08:00
|
|
|
p2p_part = parts[-1]
|
|
|
|
if p2p_part.protocols()[0].code != multiaddr.protocols.P_P2P:
|
2018-11-29 23:06:40 +08:00
|
|
|
raise InvalidAddrError()
|
|
|
|
|
2018-12-28 14:56:00 +08:00
|
|
|
# make sure the /p2p value parses as a peer.ID
|
2018-12-28 15:01:50 +08:00
|
|
|
peer_id_str = p2p_part.value_for_protocol(multiaddr.protocols.P_P2P)
|
2018-11-29 23:06:40 +08:00
|
|
|
peer_id = id_b58_decode(peer_id_str)
|
|
|
|
|
2018-12-28 14:56:00 +08:00
|
|
|
# we might have received just an / p2p part, which means there's no addr.
|
2018-11-29 23:06:40 +08:00
|
|
|
if len(parts) > 1:
|
|
|
|
addr = multiaddr.util.join(parts[:-1])
|
|
|
|
|
|
|
|
peer_data = PeerData()
|
|
|
|
peer_data.addrs = [addr]
|
|
|
|
peer_data.protocols = [p.code for p in addr.protocols()]
|
|
|
|
|
|
|
|
return PeerInfo(peer_id, peer_data)
|
|
|
|
|
|
|
|
|
|
|
|
class InvalidAddrError(ValueError):
|
|
|
|
pass
|