2019-10-16 01:02:03 +08:00
|
|
|
from typing import Any, List, Sequence
|
2019-07-27 16:27:01 +08:00
|
|
|
|
2018-11-29 23:06:40 +08:00
|
|
|
import multiaddr
|
2019-01-10 02:38:56 +08:00
|
|
|
|
2019-07-31 19:31:58 +08:00
|
|
|
from .id import ID
|
2018-11-29 23:06:40 +08:00
|
|
|
|
|
|
|
|
2018-10-29 21:09:47 +08:00
|
|
|
class PeerInfo:
|
2019-07-27 16:27:01 +08:00
|
|
|
peer_id: ID
|
|
|
|
addrs: List[multiaddr.Multiaddr]
|
|
|
|
|
2019-09-04 20:49:14 +08:00
|
|
|
def __init__(self, peer_id: ID, addrs: Sequence[multiaddr.Multiaddr]) -> None:
|
2018-10-29 21:09:47 +08:00
|
|
|
self.peer_id = peer_id
|
2019-09-04 20:49:14 +08:00
|
|
|
self.addrs = list(addrs)
|
2018-11-29 23:06:40 +08:00
|
|
|
|
2019-10-15 22:31:20 +08:00
|
|
|
def __eq__(self, other: Any) -> bool:
|
2019-10-16 01:02:03 +08:00
|
|
|
return (
|
|
|
|
isinstance(other, PeerInfo)
|
|
|
|
and self.peer_id == other.peer_id
|
|
|
|
and self.addrs == other.addrs
|
|
|
|
)
|
2019-10-15 07:01:16 +08:00
|
|
|
|
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
|
|
|
|
|
|
|
parts = addr.split()
|
2018-11-29 23:06:40 +08:00
|
|
|
if not parts:
|
2019-08-14 05:36:42 +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)
|
2019-07-31 19:31:58 +08:00
|
|
|
peer_id: ID = ID.from_base58(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
|
|
|
|
2019-09-02 13:52:33 +08:00
|
|
|
return PeerInfo(peer_id, [addr])
|
2018-11-29 23:06:40 +08:00
|
|
|
|
|
|
|
|
|
|
|
class InvalidAddrError(ValueError):
|
|
|
|
pass
|