2019-12-06 17:06:37 +08:00
|
|
|
from typing import Awaitable, Callable
|
2019-11-21 11:47:54 +08:00
|
|
|
|
|
|
|
from libp2p.host.host_interface import IHost
|
|
|
|
from libp2p.network.stream.net_stream_interface import INetStream
|
|
|
|
from libp2p.network.swarm import Swarm
|
2019-07-25 23:11:27 +08:00
|
|
|
from libp2p.peer.peerinfo import info_from_p2p_addr
|
2019-11-21 11:47:54 +08:00
|
|
|
|
|
|
|
from .constants import MAX_READ_LEN
|
2019-09-06 17:26:40 +08:00
|
|
|
|
2019-07-25 23:11:27 +08:00
|
|
|
|
2019-11-26 19:24:30 +08:00
|
|
|
async def connect_swarm(swarm_0: Swarm, swarm_1: Swarm) -> None:
|
2019-09-14 23:37:01 +08:00
|
|
|
peer_id = swarm_1.get_peer_id()
|
|
|
|
addrs = tuple(
|
|
|
|
addr
|
|
|
|
for transport in swarm_1.listeners.values()
|
|
|
|
for addr in transport.get_addrs()
|
|
|
|
)
|
|
|
|
swarm_0.peerstore.add_addrs(peer_id, addrs, 10000)
|
2019-11-26 19:24:30 +08:00
|
|
|
await swarm_0.dial_peer(peer_id)
|
2019-09-14 23:37:01 +08:00
|
|
|
assert swarm_0.get_peer_id() in swarm_1.connections
|
|
|
|
assert swarm_1.get_peer_id() in swarm_0.connections
|
|
|
|
|
|
|
|
|
2019-11-21 11:47:54 +08:00
|
|
|
async def connect(node1: IHost, node2: IHost) -> None:
|
2019-10-24 14:41:10 +08:00
|
|
|
"""Connect node1 to node2."""
|
2019-07-25 23:11:27 +08:00
|
|
|
addr = node2.get_addrs()[0]
|
|
|
|
info = info_from_p2p_addr(addr)
|
|
|
|
await node1.connect(info)
|
2019-02-25 09:58:23 +08:00
|
|
|
|
|
|
|
|
2019-12-06 17:06:37 +08:00
|
|
|
def create_echo_stream_handler(
|
|
|
|
ack_prefix: str
|
|
|
|
) -> Callable[[INetStream], Awaitable[None]]:
|
2019-12-01 17:43:14 +08:00
|
|
|
async def echo_stream_handler(stream: INetStream) -> None:
|
|
|
|
while True:
|
|
|
|
read_string = (await stream.read(MAX_READ_LEN)).decode()
|
2019-03-18 07:33:10 +08:00
|
|
|
|
2019-12-01 17:43:14 +08:00
|
|
|
resp = ack_prefix + read_string
|
|
|
|
await stream.write(resp.encode())
|
2019-03-18 09:15:14 +08:00
|
|
|
|
2019-12-01 17:43:14 +08:00
|
|
|
return echo_stream_handler
|