nim-libp2p-experimental/examples/directchat.nim

230 lines
6.5 KiB
Nim
Raw Normal View History

2019-09-12 23:20:30 +00:00
when not(compileOption("threads")):
{.fatal: "Please, compile this program with the --threads:on option!".}
2019-09-12 21:54:12 +00:00
import tables, options, sequtils, algorithm, strformat, os, strutils
2019-09-12 23:20:30 +00:00
import chronos
import ../libp2p/[switch,
multistream,
crypto/crypto,
protocols/identify,
connection,
transports/transport,
transports/tcptransport,
multiaddress,
peerinfo,
peer,
protocols/protocol,
protocols/secure/secure,
protocols/secure/secio,
protocols/pubsub/pubsub,
protocols/pubsub/floodsub,
muxers/muxer,
muxers/mplex/mplex,
muxers/mplex/types]
2019-09-12 21:54:12 +00:00
const ChatCodec = "/nim-libp2p/chat/1.0.0"
2019-09-13 00:05:20 +00:00
const DefaultAddr = "/ip4/127.0.0.1/tcp/55505"
2019-09-12 23:20:30 +00:00
const Help = """
Commands: /[?|hep|connect|disconnect|exit]
help: Prints this help
connect: dials a remote peer
disconnect: ends current session
exit: closes the chat
"""
2019-09-12 21:54:12 +00:00
type
CustomData = ref object
consoleFd: AsyncFD
serveFut: Future[void]
ChatProto = ref object of LPProtocol
customData*: CustomData
switch: Switch
transp: StreamTransport
conn: Connection
client: bool
connected: bool
2019-09-12 23:20:30 +00:00
started: bool
2019-09-12 21:54:12 +00:00
2019-09-13 00:05:20 +00:00
proc id (p: ChatProto): string =
result = "unknown"
if p.conn.peerInfo.peerId.isSome:
result = $p.conn.peerInfo.peerId.get()
2019-09-12 21:54:12 +00:00
# forward declaration
proc readWriteLoop(p: ChatProto) {.async, gcsafe.}
proc readAndPrint(p: ChatProto) {.async, gcsafe.} =
while true:
while p.connected:
2019-09-13 00:05:20 +00:00
# echo &"{p.id} -> "
2019-09-12 21:54:12 +00:00
echo cast[string](await p.conn.readLp())
2019-09-12 23:20:30 +00:00
await sleepAsync(100.millis)
2019-09-12 21:54:12 +00:00
proc dialPeer(p: ChatProto, address: string) {.async, gcsafe.} =
var parts = address.split("/")
2019-09-25 19:24:09 +00:00
if parts.len == 11 and parts[^2] notin ["ipfs", "p2p"]:
2019-09-12 21:54:12 +00:00
quit("invalid or incompelete peerId")
var remotePeer: PeerInfo
remotePeer.peerId = some(PeerID.init(parts[^1]))
remotePeer.addrs.add(MultiAddress.init(address))
echo &"dialing peer: {address}"
p.conn = await p.switch.dial(remotePeer, ChatCodec)
p.connected = true
proc writeAndPrint(p: ChatProto) {.async, gcsafe.} =
while true:
2019-09-13 00:05:20 +00:00
if not p.connected:
# echo &"{p.id} ->"
# else:
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
var line = await p.transp.readLine()
2019-09-12 23:20:30 +00:00
if line.startsWith("/help") or line.startsWith("/?") or not p.started:
echo Help
continue
if line.startsWith("/disconnect"):
echo "Ending current session"
2019-09-13 00:05:20 +00:00
if p.connected and p.conn.closed.not:
await p.conn.close()
2019-09-12 23:20:30 +00:00
p.connected = false
elif line.startsWith("/connect"):
if p.connected:
2019-09-14 13:54:09 +00:00
var yesno = "N"
2019-09-12 23:20:30 +00:00
echo "a session is already in progress, do you want end it [y/N]?"
2019-09-14 13:54:09 +00:00
yesno = await p.transp.readLine()
2019-09-12 23:20:30 +00:00
if yesno.cmpIgnoreCase("y") == 0:
await p.conn.close()
p.connected = false
elif yesno.cmpIgnoreCase("n") == 0:
continue
else:
echo "unrecognized response"
continue
echo "enter address of remote peer"
let address = await p.transp.readLine()
if address.len > 0:
await p.dialPeer(address)
elif line.startsWith("/exit"):
2019-09-13 00:05:20 +00:00
if p.connected and p.conn.closed.not:
await p.conn.close()
p.connected = false
await p.switch.stop()
echo "quitting..."
2019-09-12 23:20:30 +00:00
quit(0)
2019-09-12 21:54:12 +00:00
else:
2019-09-12 23:20:30 +00:00
if p.connected:
await p.conn.writeLp(line)
else:
try:
if line.startsWith("/") and "ipfs" in line:
await p.dialPeer(line)
except:
echo &"unable to dial remote peer {line}"
2019-09-12 23:20:30 +00:00
# echo getCurrentExceptionMsg()
2019-09-12 21:54:12 +00:00
proc readWriteLoop(p: ChatProto) {.async, gcsafe.} =
asyncCheck p.writeAndPrint()
asyncCheck p.readAndPrint()
method init(p: ChatProto) {.gcsafe.} =
proc handle(stream: Connection, proto: string) {.async, gcsafe.} =
2019-09-12 23:20:30 +00:00
if p.connected and not p.conn.closed:
echo "a chat session is already in progress - disconnecting!"
await stream.close()
2019-09-12 21:54:12 +00:00
p.conn = stream
p.connected = true
p.codec = ChatCodec
p.handler = handle
proc newChatProto(switch: Switch, transp: StreamTransport): ChatProto =
new result
result.switch = switch
result.transp = transp
result.init()
proc threadMain(wfd: AsyncFD) {.thread.} =
## This procedure performs reading from `stdin` and sends data over
## pipe to main thread.
var transp = fromPipe(wfd)
while true:
var 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
proc serveThread(customData: CustomData) {.async.} =
var transp = fromPipe(customData.consoleFd)
let seckey = PrivateKey.random(RSA)
var peerInfo: PeerInfo
peerInfo.peerId = some(PeerID.init(seckey))
2019-09-13 00:05:20 +00:00
var localAddress = DefaultAddr
while true:
echo &"Type an address to bind to or Enter to use the default {DefaultAddr}"
let a = await transp.readLine()
try:
if a.len > 0:
peerInfo.addrs.add(Multiaddress.init(a))
break
peerInfo.addrs.add(Multiaddress.init(localAddress))
break
except:
echo "invalid address"
localAddress = DefaultAddr
continue
2019-09-12 21:54:12 +00:00
proc createMplex(conn: Connection): Muxer =
result = newMplex(conn)
var mplexProvider = newMuxerProvider(createMplex, MplexCodec)
var transports = @[Transport(newTransport(TcpTransport))]
var muxers = [(MplexCodec, mplexProvider)].toTable()
var identify = newIdentify(peerInfo)
2019-09-14 13:54:09 +00:00
var secureManagers = [(SecioCodec, Secure(newSecio(seckey)))].toTable()
var switch = newSwitch(peerInfo,
transports,
identify,
muxers,
secureManagers = secureManagers)
2019-09-12 21:54:12 +00:00
var chatProto = newChatProto(switch, transp)
switch.mount(chatProto)
2019-09-12 23:20:30 +00:00
var libp2pFuts = await switch.start()
chatProto.started = true
let id = peerInfo.peerId.get().pretty
echo "PeerID: " & id
2019-09-12 21:54:12 +00:00
echo "listening on: "
2019-09-12 23:20:30 +00:00
for a in peerInfo.addrs:
echo &"{a}/ipfs/{id}"
2019-09-12 21:54:12 +00:00
await chatProto.readWriteLoop()
await allFutures(libp2pFuts)
proc main() {.async.} =
var data = new CustomData
var (rfd, wfd) = createAsyncPipe()
if rfd == asyncInvalidPipe or wfd == asyncInvalidPipe:
raise newException(ValueError, "Could not initialize pipe!")
data.consoleFd = rfd
data.serveFut = serveThread(data)
var thread: Thread[AsyncFD]
thread.createThread(threadMain, wfd)
await data.serveFut
when isMainModule:
waitFor(main())