py-libp2p/libp2p/tools/utils.py

49 lines
1.5 KiB
Python
Raw Normal View History

2019-12-06 17:06:37 +08:00
from typing import Awaitable, Callable
from libp2p.host.host_interface import IHost
from libp2p.network.stream.exceptions import StreamError
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
from .constants import MAX_READ_LEN
2019-09-06 17:26:40 +08:00
2019-07-25 23:11:27 +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)
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
async def connect(node1: IHost, node2: IHost) -> None:
"""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-12-06 17:06:37 +08:00
def create_echo_stream_handler(
ack_prefix: str
) -> Callable[[INetStream], Awaitable[None]]:
async def echo_stream_handler(stream: INetStream) -> None:
while True:
try:
read_string = (await stream.read(MAX_READ_LEN)).decode()
except StreamError:
break
2019-03-18 07:33:10 +08:00
resp = ack_prefix + read_string
try:
await stream.write(resp.encode())
except StreamError:
break
2019-03-18 09:15:14 +08:00
return echo_stream_handler