2020-09-01 08:32:19 +00:00
|
|
|
## Here's a basic example of how you would start a Waku node, subscribe to
|
|
|
|
## topics, and publish to them.
|
|
|
|
|
|
|
|
import
|
2020-11-18 11:58:46 +00:00
|
|
|
std/[os,options],
|
2020-09-01 08:32:19 +00:00
|
|
|
confutils, chronicles, chronos,
|
|
|
|
stew/shims/net as stewNet,
|
2022-11-04 12:40:24 +00:00
|
|
|
stew/byteutils,
|
2020-09-01 08:32:19 +00:00
|
|
|
libp2p/crypto/[crypto,secp],
|
|
|
|
eth/keys,
|
|
|
|
json_rpc/[rpcclient, rpcserver],
|
2022-10-18 17:35:26 +00:00
|
|
|
../../waku/v2/node/waku_node,
|
|
|
|
../../apps/wakunode2/config,
|
2020-11-17 09:34:53 +00:00
|
|
|
../../waku/common/utils/nat,
|
2021-01-06 09:35:05 +00:00
|
|
|
../../waku/v2/protocol/waku_message
|
2020-09-01 15:20:38 +00:00
|
|
|
|
2020-07-28 08:17:50 +00:00
|
|
|
# Node operations happens asynchronously
|
2020-09-01 08:32:19 +00:00
|
|
|
proc runBackground() {.async.} =
|
|
|
|
let
|
2022-11-03 09:45:06 +00:00
|
|
|
conf = WakuNodeConf.load().tryGet()
|
2020-09-01 08:32:19 +00:00
|
|
|
(extIp, extTcpPort, extUdpPort) = setupNat(conf.nat, clientId,
|
|
|
|
Port(uint16(conf.tcpPort) + conf.portsShift),
|
2021-10-12 11:43:01 +00:00
|
|
|
# This is actually a UDP port but we're only supplying this value
|
|
|
|
# To satisfy the API.
|
|
|
|
Port(uint16(conf.tcpPort) + conf.portsShift))
|
2021-07-14 17:58:46 +00:00
|
|
|
node = WakuNode.new(conf.nodeKey, conf.listenAddress,
|
2020-09-01 08:32:19 +00:00
|
|
|
Port(uint16(conf.tcpPort) + conf.portsShift), extIp, extTcpPort)
|
|
|
|
|
|
|
|
await node.start()
|
2022-09-07 15:31:27 +00:00
|
|
|
await node.mountRelay()
|
2020-07-28 08:17:50 +00:00
|
|
|
|
|
|
|
# Subscribe to a topic
|
2022-11-04 12:40:24 +00:00
|
|
|
let topic = PubsubTopic("foobar")
|
2022-10-27 15:29:09 +00:00
|
|
|
proc handler(topic: PubsubTopic, data: seq[byte]) {.async, gcsafe.} =
|
2022-11-07 15:24:16 +00:00
|
|
|
let message = WakuMessage.decode(data).value
|
2020-09-01 15:20:38 +00:00
|
|
|
let payload = cast[string](message.payload)
|
|
|
|
info "Hit subscribe handler", topic=topic, payload=payload, contentTopic=message.contentTopic
|
2021-02-02 11:33:59 +00:00
|
|
|
node.subscribe(topic, handler)
|
2020-07-28 08:17:50 +00:00
|
|
|
|
2020-07-28 08:18:30 +00:00
|
|
|
# Publish to a topic
|
2022-11-04 12:40:24 +00:00
|
|
|
let payload = toBytes("hello world")
|
2021-04-08 09:55:19 +00:00
|
|
|
let message = WakuMessage(payload: payload, contentTopic: ContentTopic("/waku/2/default-content/proto"))
|
2020-12-02 08:40:53 +00:00
|
|
|
await node.publish(topic, message)
|
2020-07-28 08:18:30 +00:00
|
|
|
|
2020-09-01 08:32:19 +00:00
|
|
|
# TODO Await with try/except here
|
|
|
|
discard runBackground()
|
2020-07-28 08:18:30 +00:00
|
|
|
|
2020-07-28 08:06:00 +00:00
|
|
|
runForever()
|