2019-09-02 18:40:12 +08:00
|
|
|
from typing import Union
|
|
|
|
|
|
|
|
from multiaddr import Multiaddr
|
2020-01-07 14:14:34 +08:00
|
|
|
import trio
|
2019-09-02 18:40:12 +08:00
|
|
|
|
|
|
|
from libp2p.host.host_interface import IHost
|
2019-09-02 21:01:13 +08:00
|
|
|
from libp2p.peer.id import ID
|
2019-09-02 23:21:57 +08:00
|
|
|
from libp2p.peer.peerinfo import PeerInfo
|
2019-09-02 18:40:12 +08:00
|
|
|
|
|
|
|
from .daemon import Daemon
|
|
|
|
|
|
|
|
TDaemonOrHost = Union[IHost, Daemon]
|
|
|
|
|
|
|
|
|
2019-09-02 21:01:13 +08:00
|
|
|
def _get_peer_info(node: TDaemonOrHost) -> PeerInfo:
|
|
|
|
peer_info: PeerInfo
|
|
|
|
if isinstance(node, Daemon):
|
|
|
|
peer_info = node.peer_info
|
|
|
|
else: # isinstance(node, IHost)
|
|
|
|
peer_id = node.get_id()
|
|
|
|
maddrs = [
|
|
|
|
node.get_addrs()[0].decapsulate(Multiaddr(f"/p2p/{peer_id.to_string()}"))
|
|
|
|
]
|
|
|
|
peer_info = PeerInfo(peer_id, maddrs)
|
|
|
|
return peer_info
|
|
|
|
|
|
|
|
|
|
|
|
async def _is_peer(peer_id: ID, node: TDaemonOrHost) -> bool:
|
|
|
|
if isinstance(node, Daemon):
|
|
|
|
pinfos = await node.control.list_peers()
|
|
|
|
peers = tuple([pinfo.peer_id for pinfo in pinfos])
|
|
|
|
return peer_id in peers
|
|
|
|
else: # isinstance(node, IHost)
|
|
|
|
return peer_id in node.get_network().connections
|
|
|
|
|
|
|
|
|
2019-09-02 18:40:12 +08:00
|
|
|
async def connect(a: TDaemonOrHost, b: TDaemonOrHost) -> None:
|
|
|
|
# Type check
|
|
|
|
err_msg = (
|
2019-09-04 20:38:38 +08:00
|
|
|
f"Type of a={type(a)} or type of b={type(b)} is wrong."
|
2019-09-02 18:40:12 +08:00
|
|
|
"Should be either `IHost` or `Daemon`"
|
|
|
|
)
|
|
|
|
assert all(
|
|
|
|
[isinstance(node, IHost) or isinstance(node, Daemon) for node in (a, b)]
|
|
|
|
), err_msg
|
|
|
|
|
2019-09-02 21:01:13 +08:00
|
|
|
b_peer_info = _get_peer_info(b)
|
2019-09-02 18:40:12 +08:00
|
|
|
if isinstance(a, Daemon):
|
2019-09-02 21:01:13 +08:00
|
|
|
await a.control.connect(b_peer_info.peer_id, b_peer_info.addrs)
|
2019-09-02 18:40:12 +08:00
|
|
|
else: # isinstance(b, IHost)
|
2019-09-02 21:01:13 +08:00
|
|
|
await a.connect(b_peer_info)
|
2019-09-02 18:40:12 +08:00
|
|
|
# Allow additional sleep for both side to establish the connection.
|
2020-01-07 14:14:34 +08:00
|
|
|
await trio.sleep(0.1)
|
2019-09-02 21:01:13 +08:00
|
|
|
|
|
|
|
a_peer_info = _get_peer_info(a)
|
|
|
|
|
|
|
|
assert await _is_peer(b_peer_info.peer_id, a)
|
|
|
|
assert await _is_peer(a_peer_info.peer_id, b)
|