2019-07-27 16:27:01 +08:00
|
|
|
from typing import (
|
|
|
|
List,
|
|
|
|
)
|
|
|
|
|
2018-11-29 23:06:40 +08:00
|
|
|
import multiaddr
|
2019-01-10 02:38:56 +08:00
|
|
|
|
2019-07-27 16:27:01 +08:00
|
|
|
from .id import (
|
|
|
|
ID,
|
|
|
|
id_b58_decode,
|
|
|
|
)
|
2019-01-10 02:38:56 +08:00
|
|
|
from .peerdata import PeerData
|
2018-11-29 23:06:40 +08:00
|
|
|
|
|
|
|
|
2018-10-29 21:09:47 +08:00
|
|
|
class PeerInfo:
|
2019-01-10 02:38:56 +08:00
|
|
|
# pylint: disable=too-few-public-methods
|
2019-07-27 16:27:01 +08:00
|
|
|
|
|
|
|
peer_id: ID
|
|
|
|
addrs: List[multiaddr.Multiaddr]
|
|
|
|
|
|
|
|
def __init__(self, peer_id: ID, peer_data: PeerData=None) -> None:
|
2018-10-29 21:09:47 +08:00
|
|
|
self.peer_id = peer_id
|
2019-04-20 04:29:15 +08:00
|
|
|
self.addrs = peer_data.get_addrs() if peer_data else None
|
2018-11-29 23:06:40 +08:00
|
|
|
|
|
|
|
|
2019-07-08 17:13:08 +08:00
|
|
|
def info_from_p2p_addr(addr: multiaddr.Multiaddr) -> PeerInfo:
|
2018-11-29 23:06:40 +08:00
|
|
|
if not addr:
|
2019-07-20 22:38:56 +08:00
|
|
|
raise InvalidAddrError("`addr` should not be `None`")
|
2019-07-08 17:13:08 +08:00
|
|
|
|
|
|
|
if not isinstance(addr, multiaddr.Multiaddr):
|
2019-07-20 22:38:56 +08:00
|
|
|
raise InvalidAddrError(f"`addr`={addr} should be of type `Multiaddr`")
|
2018-11-29 23:06:40 +08:00
|
|
|
|
2019-07-08 17:13:08 +08:00
|
|
|
parts = addr.split()
|
2018-11-29 23:06:40 +08:00
|
|
|
if not parts:
|
2019-07-20 22:47:37 +08:00
|
|
|
raise InvalidAddrError(f"`parts`={parts} should at least have a protocol `P_P2P`")
|
2018-11-29 23:06:40 +08:00
|
|
|
|
2018-12-28 15:01:50 +08:00
|
|
|
p2p_part = parts[-1]
|
2019-07-08 17:13:08 +08:00
|
|
|
last_protocol_code = p2p_part.protocols()[0].code
|
|
|
|
if last_protocol_code != multiaddr.protocols.P_P2P:
|
|
|
|
raise InvalidAddrError(
|
2019-07-20 22:38:56 +08:00
|
|
|
f"The last protocol should be `P_P2P` instead of `{last_protocol_code}`"
|
2019-07-08 17:13:08 +08:00
|
|
|
)
|
2018-11-29 23:06:40 +08:00
|
|
|
|
2018-12-28 14:56:00 +08:00
|
|
|
# make sure the /p2p value parses as a peer.ID
|
2019-07-27 16:27:01 +08:00
|
|
|
peer_id_str: str = p2p_part.value_for_protocol(multiaddr.protocols.P_P2P)
|
|
|
|
peer_id: ID = id_b58_decode(peer_id_str)
|
2018-11-29 23:06:40 +08:00
|
|
|
|
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:
|
2019-07-08 17:13:08 +08:00
|
|
|
addr = multiaddr.Multiaddr.join(*parts[:-1])
|
2018-11-29 23:06:40 +08:00
|
|
|
|
|
|
|
peer_data = PeerData()
|
2019-07-27 16:27:01 +08:00
|
|
|
peer_data.add_addrs(addr)
|
|
|
|
peer_data.set_protocols([p.code for p in addr.protocols()])
|
2018-11-29 23:06:40 +08:00
|
|
|
|
|
|
|
return PeerInfo(peer_id, peer_data)
|
|
|
|
|
|
|
|
|
|
|
|
class InvalidAddrError(ValueError):
|
|
|
|
pass
|