2021-07-16 15:13:36 +00:00
|
|
|
{.push raises: [Defect].}
|
|
|
|
|
2021-05-06 13:43:43 +00:00
|
|
|
import
|
2021-05-07 08:05:11 +00:00
|
|
|
std/[tables, times, strutils, hashes, sequtils],
|
2021-11-10 12:05:36 +00:00
|
|
|
chronos, confutils, chronicles, chronicles/topics_registry, chronos/streams/tlsstream,
|
2021-06-10 14:18:41 +00:00
|
|
|
metrics, metrics/chronos_httpserver,
|
2022-11-04 09:52:08 +00:00
|
|
|
stew/byteutils,
|
2021-05-06 13:43:43 +00:00
|
|
|
stew/shims/net as stewNet, json_rpc/rpcserver,
|
|
|
|
# Matterbridge client imports
|
2022-10-12 19:41:25 +00:00
|
|
|
../../waku/common/utils/matterbridge_client,
|
2021-05-06 13:43:43 +00:00
|
|
|
# Waku v2 imports
|
|
|
|
libp2p/crypto/crypto,
|
2022-09-06 21:54:48 +00:00
|
|
|
libp2p/errors,
|
2022-09-06 22:18:56 +00:00
|
|
|
../../../waku/v2/protocol/waku_message,
|
2022-10-18 14:05:53 +00:00
|
|
|
../../../waku/v2/node/waku_node,
|
2021-05-06 13:43:43 +00:00
|
|
|
# Chat 2 imports
|
2022-10-12 19:41:25 +00:00
|
|
|
../chat2/chat2,
|
2021-05-06 13:43:43 +00:00
|
|
|
# Common cli config
|
|
|
|
./config_chat2bridge
|
|
|
|
|
|
|
|
declarePublicCounter chat2_mb_transfers, "Number of messages transferred between chat2 and Matterbridge", ["type"]
|
2021-05-07 08:05:11 +00:00
|
|
|
declarePublicCounter chat2_mb_dropped, "Number of messages dropped", ["reason"]
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
logScope:
|
|
|
|
topics = "chat2bridge"
|
|
|
|
|
|
|
|
##################
|
|
|
|
# Default values #
|
|
|
|
##################
|
|
|
|
|
|
|
|
const
|
|
|
|
DefaultTopic* = chat2.DefaultTopic
|
2021-05-07 08:05:11 +00:00
|
|
|
DeduplQSize = 20 # Maximum number of seen messages to keep in deduplication queue
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
#########
|
|
|
|
# Types #
|
|
|
|
#########
|
|
|
|
|
|
|
|
type
|
|
|
|
Chat2MatterBridge* = ref object of RootObj
|
|
|
|
mbClient*: MatterbridgeClient
|
|
|
|
nodev2*: WakuNode
|
|
|
|
running: bool
|
|
|
|
pollPeriod: chronos.Duration
|
2021-05-07 08:05:11 +00:00
|
|
|
seen: seq[Hash] #FIFO queue
|
2021-05-26 13:48:09 +00:00
|
|
|
contentTopic: string
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
MbMessageHandler* = proc (jsonNode: JsonNode) {.gcsafe.}
|
|
|
|
|
|
|
|
###################
|
|
|
|
# Helper funtions #
|
|
|
|
###################S
|
|
|
|
|
2021-05-07 08:05:11 +00:00
|
|
|
proc containsOrAdd(sequence: var seq[Hash], hash: Hash): bool =
|
|
|
|
if sequence.contains(hash):
|
|
|
|
return true
|
|
|
|
|
|
|
|
if sequence.len >= DeduplQSize:
|
|
|
|
trace "Deduplication queue full. Removing oldest item."
|
|
|
|
sequence.delete 0, 0 # Remove first item in queue
|
|
|
|
|
|
|
|
sequence.add(hash)
|
|
|
|
|
|
|
|
return false
|
|
|
|
|
2021-06-09 14:37:08 +00:00
|
|
|
proc toWakuMessage(cmb: Chat2MatterBridge, jsonNode: JsonNode): WakuMessage {.raises: [Defect, KeyError]} =
|
2021-05-06 13:43:43 +00:00
|
|
|
# Translates a Matterbridge API JSON response to a Waku v2 message
|
|
|
|
let msgFields = jsonNode.getFields()
|
|
|
|
|
|
|
|
# @TODO error handling here - verify expected fields
|
|
|
|
|
|
|
|
let chat2pb = Chat2Message(timestamp: getTime().toUnix(), # @TODO use provided timestamp
|
|
|
|
nick: msgFields["username"].getStr(),
|
|
|
|
payload: msgFields["text"].getStr().toBytes()).encode()
|
|
|
|
|
|
|
|
WakuMessage(payload: chat2pb.buffer,
|
2021-05-26 13:48:09 +00:00
|
|
|
contentTopic: cmb.contentTopic,
|
2021-05-06 13:43:43 +00:00
|
|
|
version: 0)
|
|
|
|
|
|
|
|
proc toChat2(cmb: Chat2MatterBridge, jsonNode: JsonNode) {.async.} =
|
2021-05-26 13:48:09 +00:00
|
|
|
let msg = cmb.toWakuMessage(jsonNode)
|
2021-05-07 08:05:11 +00:00
|
|
|
|
|
|
|
if cmb.seen.containsOrAdd(msg.payload.hash()):
|
|
|
|
# This is a duplicate message. Return.
|
|
|
|
chat2_mb_dropped.inc(labelValues = ["duplicate"])
|
|
|
|
return
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
trace "Post Matterbridge message to chat2"
|
2021-05-07 08:05:11 +00:00
|
|
|
|
|
|
|
chat2_mb_transfers.inc(labelValues = ["mb_to_chat2"])
|
2021-05-06 13:43:43 +00:00
|
|
|
|
2021-05-07 08:05:11 +00:00
|
|
|
await cmb.nodev2.publish(DefaultTopic, msg)
|
2021-05-06 13:43:43 +00:00
|
|
|
|
2021-06-09 14:37:08 +00:00
|
|
|
proc toMatterbridge(cmb: Chat2MatterBridge, msg: WakuMessage) {.gcsafe, raises: [Exception].} =
|
2021-05-07 08:05:11 +00:00
|
|
|
if cmb.seen.containsOrAdd(msg.payload.hash()):
|
|
|
|
# This is a duplicate message. Return.
|
|
|
|
chat2_mb_dropped.inc(labelValues = ["duplicate"])
|
|
|
|
return
|
2021-05-06 13:43:43 +00:00
|
|
|
|
2021-06-02 14:54:38 +00:00
|
|
|
if msg.contentTopic != cmb.contentTopic:
|
|
|
|
# Only bridge messages on the configured content topic
|
|
|
|
chat2_mb_dropped.inc(labelValues = ["filtered"])
|
|
|
|
return
|
|
|
|
|
2021-05-06 13:43:43 +00:00
|
|
|
trace "Post chat2 message to Matterbridge"
|
|
|
|
|
2021-05-07 08:05:11 +00:00
|
|
|
chat2_mb_transfers.inc(labelValues = ["chat2_to_mb"])
|
|
|
|
|
2021-05-06 13:43:43 +00:00
|
|
|
let chat2Msg = Chat2Message.init(msg.payload)
|
|
|
|
|
|
|
|
assert chat2Msg.isOk
|
|
|
|
|
2021-07-16 15:13:36 +00:00
|
|
|
let postRes = cmb.mbClient.postMessage(text = string.fromBytes(chat2Msg[].payload),
|
|
|
|
username = chat2Msg[].nick)
|
|
|
|
|
|
|
|
if postRes.isErr() or (postRes[] == false):
|
2021-05-07 08:05:11 +00:00
|
|
|
chat2_mb_dropped.inc(labelValues = ["duplicate"])
|
|
|
|
error "Matterbridge host unreachable. Dropping message."
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
proc pollMatterbridge(cmb: Chat2MatterBridge, handler: MbMessageHandler) {.async.} =
|
|
|
|
while cmb.running:
|
2021-07-16 15:13:36 +00:00
|
|
|
let getRes = cmb.mbClient.getMessages()
|
|
|
|
|
|
|
|
if getRes.isOk():
|
|
|
|
for jsonNode in getRes[]:
|
2021-05-07 08:05:11 +00:00
|
|
|
handler(jsonNode)
|
2021-07-16 15:13:36 +00:00
|
|
|
else:
|
2021-05-07 08:05:11 +00:00
|
|
|
error "Matterbridge host unreachable. Sleeping before retrying."
|
|
|
|
await sleepAsync(chronos.seconds(10))
|
|
|
|
|
2021-05-06 13:43:43 +00:00
|
|
|
await sleepAsync(cmb.pollPeriod)
|
|
|
|
|
|
|
|
##############
|
|
|
|
# Public API #
|
|
|
|
##############
|
|
|
|
proc new*(T: type Chat2MatterBridge,
|
|
|
|
# Matterbridge initialisation
|
|
|
|
mbHostUri: string,
|
|
|
|
mbGateway: string,
|
|
|
|
# NodeV2 initialisation
|
|
|
|
nodev2Key: crypto.PrivateKey,
|
|
|
|
nodev2BindIp: ValidIpAddress, nodev2BindPort: Port,
|
2021-05-26 13:48:09 +00:00
|
|
|
nodev2ExtIp = none[ValidIpAddress](), nodev2ExtPort = none[Port](),
|
2021-07-16 15:13:36 +00:00
|
|
|
contentTopic: string): T
|
2021-11-10 12:05:36 +00:00
|
|
|
{.raises: [Defect, ValueError, KeyError, TLSStreamProtocolError, IOError, LPError].} =
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
# Setup Matterbridge
|
|
|
|
let
|
|
|
|
mbClient = MatterbridgeClient.new(mbHostUri, mbGateway)
|
2021-05-07 08:05:11 +00:00
|
|
|
|
|
|
|
# Let's verify the Matterbridge configuration before continuing
|
2021-07-16 15:13:36 +00:00
|
|
|
let clientHealth = mbClient.isHealthy()
|
|
|
|
|
|
|
|
if clientHealth.isOk() and clientHealth[]:
|
|
|
|
info "Reached Matterbridge host", host=mbClient.host
|
|
|
|
else:
|
|
|
|
raise newException(ValueError, "Matterbridge client not reachable/healthy")
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
# Setup Waku v2 node
|
|
|
|
let
|
2021-07-14 17:58:46 +00:00
|
|
|
nodev2 = WakuNode.new(nodev2Key,
|
2021-05-06 13:43:43 +00:00
|
|
|
nodev2BindIp, nodev2BindPort,
|
|
|
|
nodev2ExtIp, nodev2ExtPort)
|
|
|
|
|
2021-05-26 13:48:09 +00:00
|
|
|
return Chat2MatterBridge(mbClient: mbClient,
|
|
|
|
nodev2: nodev2,
|
|
|
|
running: false,
|
|
|
|
pollPeriod: chronos.seconds(1),
|
|
|
|
contentTopic: contentTopic)
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
proc start*(cmb: Chat2MatterBridge) {.async.} =
|
|
|
|
info "Starting Chat2MatterBridge"
|
|
|
|
|
|
|
|
cmb.running = true
|
|
|
|
|
|
|
|
debug "Start polling Matterbridge"
|
|
|
|
|
|
|
|
# Start Matterbridge polling (@TODO: use streaming interface)
|
2021-06-09 14:37:08 +00:00
|
|
|
proc mbHandler(jsonNode: JsonNode) {.gcsafe, raises: [Exception].} =
|
2021-05-06 13:43:43 +00:00
|
|
|
trace "Bridging message from Matterbridge to chat2", jsonNode=jsonNode
|
|
|
|
waitFor cmb.toChat2(jsonNode)
|
|
|
|
|
|
|
|
asyncSpawn cmb.pollMatterbridge(mbHandler)
|
|
|
|
|
|
|
|
# Start Waku v2 node
|
|
|
|
debug "Start listening on Waku v2"
|
|
|
|
await cmb.nodev2.start()
|
|
|
|
|
2021-05-24 11:19:33 +00:00
|
|
|
# Always mount relay for bridge
|
|
|
|
# `triggerSelf` is false on a `bridge` to avoid duplicates
|
2022-09-07 15:31:27 +00:00
|
|
|
await cmb.nodev2.mountRelay(triggerSelf = false)
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
# Bridging
|
|
|
|
# Handle messages on Waku v2 and bridge to Matterbridge
|
2021-06-09 14:37:08 +00:00
|
|
|
proc relayHandler(pubsubTopic: string, data: seq[byte]) {.async, gcsafe, raises: [Defect].} =
|
2021-05-06 13:43:43 +00:00
|
|
|
let msg = WakuMessage.init(data)
|
|
|
|
if msg.isOk():
|
|
|
|
trace "Bridging message from Chat2 to Matterbridge", msg=msg[]
|
|
|
|
cmb.toMatterbridge(msg[])
|
|
|
|
|
|
|
|
cmb.nodev2.subscribe(DefaultTopic, relayHandler)
|
|
|
|
|
|
|
|
proc stop*(cmb: Chat2MatterBridge) {.async.} =
|
|
|
|
info "Stopping Chat2MatterBridge"
|
|
|
|
|
|
|
|
cmb.running = false
|
|
|
|
|
|
|
|
await cmb.nodev2.stop()
|
|
|
|
|
2021-07-16 15:13:36 +00:00
|
|
|
{.pop.} # @TODO confutils.nim(775, 17) Error: can raise an unlisted exception: ref IOError
|
2021-05-06 13:43:43 +00:00
|
|
|
when isMainModule:
|
|
|
|
import
|
|
|
|
../../../waku/common/utils/nat,
|
|
|
|
../../../waku/v2/node/jsonrpc/[debug_api,
|
|
|
|
filter_api,
|
|
|
|
relay_api,
|
|
|
|
store_api]
|
|
|
|
|
2021-06-09 14:37:08 +00:00
|
|
|
proc startV2Rpc(node: WakuNode, rpcServer: RpcHttpServer, conf: Chat2MatterbridgeConf) {.raises: [Exception].} =
|
2021-05-06 13:43:43 +00:00
|
|
|
installDebugApiHandlers(node, rpcServer)
|
|
|
|
|
|
|
|
# Install enabled API handlers:
|
|
|
|
if conf.relay:
|
|
|
|
let topicCache = newTable[string, seq[WakuMessage]]()
|
|
|
|
installRelayApiHandlers(node, rpcServer, topicCache)
|
|
|
|
|
|
|
|
if conf.filter:
|
|
|
|
let messageCache = newTable[ContentTopic, seq[WakuMessage]]()
|
|
|
|
installFilterApiHandlers(node, rpcServer, messageCache)
|
|
|
|
|
|
|
|
if conf.store:
|
|
|
|
installStoreApiHandlers(node, rpcServer)
|
|
|
|
|
|
|
|
rpcServer.start()
|
|
|
|
|
|
|
|
let
|
|
|
|
rng = newRng()
|
|
|
|
conf = Chat2MatterbridgeConf.load()
|
|
|
|
|
|
|
|
if conf.logLevel != LogLevel.NONE:
|
|
|
|
setLogLevel(conf.logLevel)
|
|
|
|
|
|
|
|
# Load address configuration
|
|
|
|
let
|
|
|
|
(nodev2ExtIp, nodev2ExtPort, _) = setupNat(conf.nat, clientId,
|
|
|
|
Port(uint16(conf.libp2pTcpPort) + conf.portsShift),
|
|
|
|
Port(uint16(conf.udpPort) + conf.portsShift))
|
2021-08-30 09:01:28 +00:00
|
|
|
## The following heuristic assumes that, in absence of manual
|
|
|
|
## config, the external port is the same as the bind port.
|
|
|
|
extPort = if nodev2ExtIp.isSome() and nodev2ExtPort.isNone():
|
|
|
|
some(Port(uint16(conf.libp2pTcpPort) + conf.portsShift))
|
|
|
|
else:
|
|
|
|
nodev2ExtPort
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
let
|
|
|
|
bridge = Chat2Matterbridge.new(
|
2021-05-07 08:05:11 +00:00
|
|
|
mbHostUri = "http://" & $initTAddress(conf.mbHostAddress, Port(conf.mbHostPort)),
|
2021-05-06 13:43:43 +00:00
|
|
|
mbGateway = conf.mbGateway,
|
2021-05-10 07:34:43 +00:00
|
|
|
nodev2Key = conf.nodekey,
|
2021-05-06 13:43:43 +00:00
|
|
|
nodev2BindIp = conf.listenAddress, nodev2BindPort = Port(uint16(conf.libp2pTcpPort) + conf.portsShift),
|
2021-08-30 09:01:28 +00:00
|
|
|
nodev2ExtIp = nodev2ExtIp, nodev2ExtPort = extPort,
|
2021-05-26 13:48:09 +00:00
|
|
|
contentTopic = conf.contentTopic)
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
waitFor bridge.start()
|
|
|
|
|
|
|
|
# Now load rest of config
|
|
|
|
# Mount configured Waku v2 protocols
|
2022-09-07 15:31:27 +00:00
|
|
|
waitFor mountLibp2pPing(bridge.nodev2)
|
2021-06-02 14:54:38 +00:00
|
|
|
|
2021-05-06 13:43:43 +00:00
|
|
|
if conf.store:
|
2022-09-07 15:31:27 +00:00
|
|
|
waitFor mountStore(bridge.nodev2)
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
if conf.filter:
|
2022-09-07 15:31:27 +00:00
|
|
|
waitFor mountFilter(bridge.nodev2)
|
2021-05-06 13:43:43 +00:00
|
|
|
|
2021-05-10 07:34:43 +00:00
|
|
|
if conf.staticnodes.len > 0:
|
|
|
|
waitFor connectToNodes(bridge.nodev2, conf.staticnodes)
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
if conf.storenode != "":
|
|
|
|
setStorePeer(bridge.nodev2, conf.storenode)
|
|
|
|
|
|
|
|
if conf.filternode != "":
|
|
|
|
setFilterPeer(bridge.nodev2, conf.filternode)
|
|
|
|
|
|
|
|
if conf.rpc:
|
|
|
|
let ta = initTAddress(conf.rpcAddress,
|
|
|
|
Port(conf.rpcPort + conf.portsShift))
|
|
|
|
var rpcServer = newRpcHttpServer([ta])
|
|
|
|
# Waku v2 rpc
|
|
|
|
startV2Rpc(bridge.nodev2, rpcServer, conf)
|
|
|
|
|
|
|
|
rpcServer.start()
|
|
|
|
|
2021-06-10 14:18:41 +00:00
|
|
|
if conf.metricsServer:
|
|
|
|
let
|
|
|
|
address = conf.metricsServerAddress
|
|
|
|
port = conf.metricsServerPort + conf.portsShift
|
|
|
|
info "Starting metrics HTTP server", address, port
|
|
|
|
startMetricsHttpServer($address, Port(port))
|
2021-05-06 13:43:43 +00:00
|
|
|
|
|
|
|
runForever()
|