2019-09-12 23:20:30 +00:00
|
|
|
when not(compileOption("threads")):
|
|
|
|
{.fatal: "Please, compile this program with the --threads:on option!".}
|
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
import
|
2022-06-16 08:08:52 +00:00
|
|
|
strformat, strutils,
|
2021-11-08 12:00:44 +00:00
|
|
|
stew/byteutils,
|
|
|
|
chronos,
|
|
|
|
../libp2p
|
2019-09-12 21:54:12 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
const DefaultAddr = "/ip4/127.0.0.1/tcp/0"
|
2019-09-13 00:05:20 +00:00
|
|
|
|
2019-09-12 23:20:30 +00:00
|
|
|
const Help = """
|
2021-11-08 12:00:44 +00:00
|
|
|
Commands: /[?|help|connect|disconnect|exit]
|
2019-09-12 23:20:30 +00:00
|
|
|
help: Prints this help
|
|
|
|
connect: dials a remote peer
|
|
|
|
disconnect: ends current session
|
|
|
|
exit: closes the chat
|
|
|
|
"""
|
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
type
|
|
|
|
Chat = ref object
|
|
|
|
switch: Switch # a single entry point for dialing and listening to peer
|
|
|
|
stdinReader: StreamTransport # transport streams between read & write file descriptor
|
|
|
|
conn: Connection # connection to the other peer
|
|
|
|
connected: bool # if the node is connected to another peer
|
|
|
|
|
|
|
|
##
|
|
|
|
# Stdout helpers, to write the prompt
|
|
|
|
##
|
|
|
|
proc writePrompt(c: Chat) =
|
|
|
|
if c.connected:
|
|
|
|
stdout.write '\r' & $c.switch.peerInfo.peerId & ": "
|
|
|
|
stdout.flushFile()
|
|
|
|
|
|
|
|
proc writeStdout(c: Chat, str: string) =
|
|
|
|
echo '\r' & str
|
|
|
|
c.writePrompt()
|
|
|
|
|
|
|
|
##
|
|
|
|
# Chat Protocol
|
|
|
|
##
|
|
|
|
const ChatCodec = "/nim-libp2p/chat/1.0.0"
|
2019-09-13 00:05:20 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
type
|
|
|
|
ChatProto = ref object of LPProtocol
|
2019-09-12 21:54:12 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
proc new(T: typedesc[ChatProto], c: Chat): T =
|
|
|
|
let chatproto = T()
|
|
|
|
|
|
|
|
# create handler for incoming connection
|
|
|
|
proc handle(stream: Connection, proto: string) {.async.} =
|
|
|
|
if c.connected and not c.conn.closed:
|
|
|
|
c.writeStdout "a chat session is already in progress - refusing incoming peer!"
|
|
|
|
await stream.close()
|
|
|
|
else:
|
|
|
|
await c.handlePeer(stream)
|
|
|
|
await stream.close()
|
|
|
|
|
|
|
|
# assign the new handler
|
|
|
|
chatproto.handler = handle
|
|
|
|
chatproto.codec = ChatCodec
|
|
|
|
return chatproto
|
|
|
|
|
|
|
|
##
|
|
|
|
# Chat application
|
|
|
|
##
|
|
|
|
proc handlePeer(c: Chat, conn: Connection) {.async.} =
|
|
|
|
# Handle a peer (incoming or outgoing)
|
|
|
|
try:
|
|
|
|
c.conn = conn
|
|
|
|
c.connected = true
|
|
|
|
c.writeStdout $conn.peerId & " connected"
|
|
|
|
|
|
|
|
# Read loop
|
|
|
|
while true:
|
|
|
|
let
|
|
|
|
strData = await conn.readLp(1024)
|
|
|
|
str = string.fromBytes(strData)
|
|
|
|
c.writeStdout $conn.peerId & ": " & $str
|
|
|
|
|
|
|
|
except LPStreamEOFError:
|
2021-12-02 12:45:55 +00:00
|
|
|
defer: c.writeStdout $conn.peerId & " disconnected"
|
|
|
|
await c.conn.close()
|
|
|
|
c.connected = false
|
2021-11-08 12:00:44 +00:00
|
|
|
|
|
|
|
proc dialPeer(c: Chat, address: string) {.async.} =
|
|
|
|
# Parse and dial address
|
2021-06-28 02:37:00 +00:00
|
|
|
let
|
|
|
|
multiAddr = MultiAddress.init(address).tryGet()
|
|
|
|
# split the peerId part /p2p/...
|
|
|
|
peerIdBytes = multiAddr[multiCodec("p2p")]
|
|
|
|
.tryGet()
|
|
|
|
.protoAddress()
|
|
|
|
.tryGet()
|
2021-12-16 10:05:20 +00:00
|
|
|
remotePeer = PeerId.init(peerIdBytes).tryGet()
|
2021-06-28 02:37:00 +00:00
|
|
|
# split the wire address
|
|
|
|
ip4Addr = multiAddr[multiCodec("ip4")].tryGet()
|
|
|
|
tcpAddr = multiAddr[multiCodec("tcp")].tryGet()
|
|
|
|
wireAddr = ip4Addr & tcpAddr
|
2019-09-12 21:54:12 +00:00
|
|
|
|
2020-04-08 17:21:06 +00:00
|
|
|
echo &"dialing peer: {multiAddr}"
|
2021-11-08 12:00:44 +00:00
|
|
|
asyncSpawn c.handlePeer(await c.switch.dial(remotePeer, @[wireAddr], ChatCodec))
|
2020-04-08 17:21:06 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
proc readLoop(c: Chat) {.async.} =
|
2019-09-12 21:54:12 +00:00
|
|
|
while true:
|
2021-11-08 12:00:44 +00:00
|
|
|
if not c.connected:
|
2019-09-12 21:54:12 +00:00
|
|
|
echo "type an address or wait for a connection:"
|
2019-09-12 23:20:30 +00:00
|
|
|
echo "type /[help|?] for help"
|
2019-09-12 21:54:12 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
c.writePrompt()
|
|
|
|
|
|
|
|
let line = await c.stdinReader.readLine()
|
|
|
|
if line.startsWith("/help") or line.startsWith("/?"):
|
2019-09-12 23:20:30 +00:00
|
|
|
echo Help
|
|
|
|
continue
|
2019-12-08 21:06:58 +00:00
|
|
|
|
2019-09-12 23:20:30 +00:00
|
|
|
if line.startsWith("/disconnect"):
|
2021-11-08 12:00:44 +00:00
|
|
|
c.writeStdout "Ending current session"
|
|
|
|
if c.connected and c.conn.closed.not:
|
|
|
|
await c.conn.close()
|
|
|
|
c.connected = false
|
2019-09-12 23:20:30 +00:00
|
|
|
elif line.startsWith("/connect"):
|
2021-11-08 12:00:44 +00:00
|
|
|
c.writeStdout "enter address of remote peer"
|
|
|
|
let address = await c.stdinReader.readLine()
|
2019-09-12 23:20:30 +00:00
|
|
|
if address.len > 0:
|
2021-11-08 12:00:44 +00:00
|
|
|
await c.dialPeer(address)
|
2019-09-12 23:20:30 +00:00
|
|
|
|
|
|
|
elif line.startsWith("/exit"):
|
2021-11-08 12:00:44 +00:00
|
|
|
if c.connected and c.conn.closed.not:
|
|
|
|
await c.conn.close()
|
|
|
|
c.connected = false
|
2019-09-13 00:05:20 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
await c.switch.stop()
|
|
|
|
c.writeStdout "quitting..."
|
2021-12-02 12:45:55 +00:00
|
|
|
return
|
2019-09-12 21:54:12 +00:00
|
|
|
else:
|
2021-11-08 12:00:44 +00:00
|
|
|
if c.connected:
|
|
|
|
await c.conn.writeLp(line)
|
2019-09-12 23:20:30 +00:00
|
|
|
else:
|
|
|
|
try:
|
2021-06-28 02:37:00 +00:00
|
|
|
if line.startsWith("/") and "p2p" in line:
|
2021-11-08 12:00:44 +00:00
|
|
|
await c.dialPeer(line)
|
|
|
|
except CatchableError as exc:
|
2019-10-04 21:20:19 +00:00
|
|
|
echo &"unable to dial remote peer {line}"
|
2021-11-08 12:00:44 +00:00
|
|
|
echo exc.msg
|
2019-09-12 21:54:12 +00:00
|
|
|
|
2020-04-08 17:21:06 +00:00
|
|
|
proc readInput(wfd: AsyncFD) {.thread.} =
|
2021-11-08 12:00:44 +00:00
|
|
|
## This thread performs reading from `stdin` and sends data over
|
2019-09-12 21:54:12 +00:00
|
|
|
## pipe to main thread.
|
2020-04-08 17:21:06 +00:00
|
|
|
let transp = fromPipe(wfd)
|
2019-12-08 21:06:58 +00:00
|
|
|
|
2019-09-12 21:54:12 +00:00
|
|
|
while true:
|
2020-04-08 17:21:06 +00:00
|
|
|
let line = stdin.readLine()
|
2019-09-25 19:33:50 +00:00
|
|
|
discard waitFor transp.write(line & "\r\n")
|
2019-09-12 21:54:12 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
proc main() {.async.} =
|
|
|
|
let
|
|
|
|
rng = newRng() # Single random number source for the whole application
|
2019-09-12 21:54:12 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
# Pipe to read stdin from main thread
|
|
|
|
(rfd, wfd) = createAsyncPipe()
|
|
|
|
stdinReader = fromPipe(rfd)
|
|
|
|
|
|
|
|
var thread: Thread[AsyncFD]
|
2022-01-05 15:27:33 +00:00
|
|
|
try:
|
|
|
|
thread.createThread(readInput, wfd)
|
|
|
|
except Exception as exc:
|
|
|
|
quit("Failed to create thread: " & exc.msg)
|
2021-11-08 12:00:44 +00:00
|
|
|
|
|
|
|
var localAddress = MultiAddress.init(DefaultAddr).tryGet()
|
2019-09-13 00:05:20 +00:00
|
|
|
|
2021-06-28 02:37:00 +00:00
|
|
|
var switch = SwitchBuilder
|
2021-11-08 12:00:44 +00:00
|
|
|
.new()
|
|
|
|
.withRng(rng) # Give the application RNG
|
|
|
|
.withAddress(localAddress)
|
|
|
|
.withTcpTransport() # Use TCP as transport
|
|
|
|
.withMplex() # Use Mplex as muxer
|
|
|
|
.withNoise() # Use Noise as secure manager
|
2021-06-28 02:37:00 +00:00
|
|
|
.build()
|
2019-09-12 21:54:12 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
let chat = Chat(
|
|
|
|
switch: switch,
|
|
|
|
stdinReader: stdinReader)
|
|
|
|
|
|
|
|
switch.mount(ChatProto.new(chat))
|
|
|
|
|
2021-12-03 18:23:12 +00:00
|
|
|
await switch.start()
|
2019-09-12 23:20:30 +00:00
|
|
|
|
2021-06-28 02:37:00 +00:00
|
|
|
let id = $switch.peerInfo.peerId
|
2021-12-16 10:05:20 +00:00
|
|
|
echo "PeerId: " & id
|
2019-09-12 21:54:12 +00:00
|
|
|
echo "listening on: "
|
2021-06-28 02:37:00 +00:00
|
|
|
for a in switch.peerInfo.addrs:
|
|
|
|
echo &"{a}/p2p/{id}"
|
2019-09-12 21:54:12 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
await chat.readLoop()
|
2021-12-02 12:45:55 +00:00
|
|
|
quit(0)
|
2019-09-12 21:54:12 +00:00
|
|
|
|
2021-11-08 12:00:44 +00:00
|
|
|
waitFor(main())
|