Fix examples and modify new_node

- Fix examples `chat.py` and `echo.py`
    - Use trio directly, instead of `trio-asyncio`
    - Remove redundant code
- Change entry API `new_node` to `new_host_trio`
This commit is contained in:
mhchia
2019-12-24 18:03:18 +08:00
parent 6fe5871d96
commit 3372c32432
7 changed files with 129 additions and 183 deletions

View File

@ -1,13 +1,10 @@
import argparse
import asyncio
import sys
import urllib.request
import multiaddr
import trio
import trio_asyncio
from libp2p import new_node
from libp2p import new_host_trio
from libp2p.network.stream.net_stream_interface import INetStream
from libp2p.peer.peerinfo import info_from_p2p_addr
from libp2p.typing import TProtocol
@ -28,60 +25,48 @@ async def read_data(stream: INetStream) -> None:
async def write_data(stream: INetStream) -> None:
loop = asyncio.get_event_loop()
async_f = trio.wrap_file(sys.stdin)
while True:
line = await loop.run_in_executor(None, sys.stdin.readline)
line = await async_f.readline()
await stream.write(line.encode())
async def run(port: int, destination: str, localhost: bool) -> None:
if localhost:
ip = "127.0.0.1"
else:
ip = urllib.request.urlopen("https://v4.ident.me/").read().decode("utf8")
transport_opt = f"/ip4/{ip}/tcp/{port}"
host = new_node(transport_opt=[transport_opt])
async def run(port: int, destination: str) -> None:
localhost_ip = "127.0.0.1"
listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}")
async with new_host_trio(
listen_addrs=[listen_addr]
) as host, trio.open_nursery() as nursery:
if not destination: # its the server
await trio_asyncio.run_asyncio(
host.get_network().listen, multiaddr.Multiaddr(transport_opt)
)
async def stream_handler(stream: INetStream) -> None:
nursery.start_soon(read_data, stream)
nursery.start_soon(write_data, stream)
if not destination: # its the server
host.set_stream_handler(PROTOCOL_ID, stream_handler)
async def stream_handler(stream: INetStream) -> None:
asyncio.ensure_future(read_data(stream))
asyncio.ensure_future(write_data(stream))
print(
f"Run 'python ./examples/chat/chat.py "
f"-p {int(port) + 1} "
f"-d /ip4/{localhost_ip}/tcp/{port}/p2p/{host.get_id().pretty()}' "
"on another console."
)
print("Waiting for incoming connection...")
host.set_stream_handler(PROTOCOL_ID, stream_handler)
else: # its the client
maddr = multiaddr.Multiaddr(destination)
info = info_from_p2p_addr(maddr)
# Associate the peer with local ip address
await host.connect(info)
# Start a stream with the destination.
# Multiaddress of the destination peer is fetched from the peerstore using 'peerId'.
stream = await host.new_stream(info.peer_id, [PROTOCOL_ID])
localhost_opt = " --localhost" if localhost else ""
nursery.start_soon(read_data, stream)
nursery.start_soon(write_data, stream)
print("Connected to peer %s" % info.addrs[0])
print(
f"Run 'python ./examples/chat/chat.py"
+ localhost_opt
+ f" -p {int(port) + 1} -d /ip4/{ip}/tcp/{port}/p2p/{host.get_id().pretty()}'"
+ " on another console."
)
print("Waiting for incoming connection...")
else: # its the client
maddr = multiaddr.Multiaddr(destination)
info = info_from_p2p_addr(maddr)
# Associate the peer with local ip address
await trio_asyncio.run_asyncio(host.connect, info)
# Start a stream with the destination.
# Multiaddress of the destination peer is fetched from the peerstore using 'peerId'.
stream = await trio_asyncio.run_asyncio(
host.new_stream, *(info.peer_id, [PROTOCOL_ID])
)
asyncio.ensure_future(read_data(stream))
asyncio.ensure_future(write_data(stream))
print("Connected to peer %s" % info.addrs[0])
stopped_event = trio.Event()
await stopped_event.wait()
await trio.sleep_forever()
def main() -> None:
@ -95,11 +80,6 @@ def main() -> None:
"/ip4/127.0.0.1/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q"
)
parser = argparse.ArgumentParser(description=description)
parser.add_argument(
"--debug",
action="store_true",
help="generate the same node ID on every execution",
)
parser.add_argument(
"-p", "--port", default=8000, type=int, help="source port number"
)
@ -109,19 +89,15 @@ def main() -> None:
type=str,
help=f"destination multiaddr string, e.g. {example_maddr}",
)
parser.add_argument(
"-l",
"--localhost",
dest="localhost",
action="store_true",
help="flag indicating if localhost should be used or an external IP",
)
args = parser.parse_args()
if not args.port:
raise RuntimeError("was not able to determine a local port")
trio_asyncio.run(run, *(args.port, args.destination, args.localhost))
try:
trio.run(run, *(args.port, args.destination))
except KeyboardInterrupt:
pass
if __name__ == "__main__":

View File

@ -1,10 +1,9 @@
import argparse
import asyncio
import urllib.request
import multiaddr
import trio
from libp2p import new_node
from libp2p import new_host_trio
from libp2p.crypto.secp256k1 import create_new_key_pair
from libp2p.network.stream.net_stream_interface import INetStream
from libp2p.peer.peerinfo import info_from_p2p_addr
@ -20,12 +19,9 @@ async def _echo_stream_handler(stream: INetStream) -> None:
await stream.close()
async def run(port: int, destination: str, localhost: bool, seed: int = None) -> None:
if localhost:
ip = "127.0.0.1"
else:
ip = urllib.request.urlopen("https://v4.ident.me/").read().decode("utf8")
transport_opt = f"/ip4/{ip}/tcp/{port}"
async def run(port: int, destination: str, seed: int = None) -> None:
localhost_ip = "127.0.0.1"
listen_addr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}")
if seed:
import random
@ -38,47 +34,44 @@ async def run(port: int, destination: str, localhost: bool, seed: int = None) ->
secret = secrets.token_bytes(32)
host = await new_node(
key_pair=create_new_key_pair(secret), transport_opt=[transport_opt]
)
async with new_host_trio(
listen_addrs=[listen_addr], key_pair=create_new_key_pair(secret)
) as host:
print(f"I am {host.get_id().to_string()}")
print(f"I am {host.get_id().to_string()}")
await host.get_network().listen(multiaddr.Multiaddr(transport_opt))
if not destination: # its the server
if not destination: # its the server
host.set_stream_handler(PROTOCOL_ID, _echo_stream_handler)
host.set_stream_handler(PROTOCOL_ID, _echo_stream_handler)
print(
f"Run 'python ./examples/echo/echo.py "
f"-p {int(port) + 1} "
f"-d /ip4/{localhost_ip}/tcp/{port}/p2p/{host.get_id().pretty()}' "
"on another console."
)
print("Waiting for incoming connections...")
await trio.sleep_forever()
localhost_opt = " --localhost" if localhost else ""
else: # its the client
maddr = multiaddr.Multiaddr(destination)
info = info_from_p2p_addr(maddr)
# Associate the peer with local ip address
await host.connect(info)
print(
f"Run 'python ./examples/echo/echo.py"
+ localhost_opt
+ f" -p {int(port) + 1} -d /ip4/{ip}/tcp/{port}/p2p/{host.get_id().pretty()}'"
+ " on another console."
)
print("Waiting for incoming connections...")
# Start a stream with the destination.
# Multiaddress of the destination peer is fetched from the peerstore using 'peerId'.
stream = await host.new_stream(info.peer_id, [PROTOCOL_ID])
else: # its the client
maddr = multiaddr.Multiaddr(destination)
info = info_from_p2p_addr(maddr)
# Associate the peer with local ip address
await host.connect(info)
msg = b"hi, there!\n"
# Start a stream with the destination.
# Multiaddress of the destination peer is fetched from the peerstore using 'peerId'.
stream = await host.new_stream(info.peer_id, [PROTOCOL_ID])
await stream.write(msg)
# Notify the other side about EOF
await stream.close()
response = await stream.read()
msg = b"hi, there!\n"
await stream.write(msg)
# Notify the other side about EOF
await stream.close()
response = await stream.read()
print(f"Sent: {msg}")
print(f"Got: {response}")
print(f"Sent: {msg}")
print(f"Got: {response}")
def main() -> None:
@ -94,11 +87,6 @@ def main() -> None:
"/ip4/127.0.0.1/tcp/8000/p2p/QmQn4SwGkDZKkUEpBRBvTmheQycxAHJUNmVEnjA2v1qe8Q"
)
parser = argparse.ArgumentParser(description=description)
parser.add_argument(
"--debug",
action="store_true",
help="generate the same node ID on every execution",
)
parser.add_argument(
"-p", "--port", default=8000, type=int, help="source port number"
)
@ -108,13 +96,6 @@ def main() -> None:
type=str,
help=f"destination multiaddr string, e.g. {example_maddr}",
)
parser.add_argument(
"-l",
"--localhost",
dest="localhost",
action="store_true",
help="flag indicating if localhost should be used or an external IP",
)
parser.add_argument(
"-s",
"--seed",
@ -126,16 +107,10 @@ def main() -> None:
if not args.port:
raise RuntimeError("was not able to determine a local port")
loop = asyncio.get_event_loop()
try:
asyncio.ensure_future(
run(args.port, args.destination, args.localhost, args.seed)
)
loop.run_forever()
trio.run(run, args.port, args.destination, args.seed)
except KeyboardInterrupt:
pass
finally:
loop.close()
if __name__ == "__main__":