2019-09-10 02:15:52 +00:00
|
|
|
## Nim-LibP2P
|
2019-09-24 17:48:23 +00:00
|
|
|
## Copyright (c) 2019 Status Research & Development GmbH
|
2019-09-10 02:15:52 +00:00
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
import std/[tables, sequtils, sets, strutils]
|
2020-08-21 02:50:33 +00:00
|
|
|
import chronos, chronicles, metrics
|
2019-09-10 02:15:52 +00:00
|
|
|
import pubsubpeer,
|
2020-06-28 15:56:38 +00:00
|
|
|
rpc/[message, messages],
|
2020-08-12 00:05:49 +00:00
|
|
|
../../switch,
|
2019-09-10 02:15:52 +00:00
|
|
|
../protocol,
|
2020-06-19 17:29:43 +00:00
|
|
|
../../stream/connection,
|
2020-07-01 06:25:09 +00:00
|
|
|
../../peerid,
|
2020-07-17 15:36:48 +00:00
|
|
|
../../peerinfo,
|
2021-01-08 05:21:24 +00:00
|
|
|
../../errors,
|
|
|
|
../../utility
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2020-09-21 09:16:29 +00:00
|
|
|
import metrics
|
|
|
|
import stew/results
|
|
|
|
export results
|
|
|
|
|
2019-09-10 02:15:52 +00:00
|
|
|
export PubSubPeer
|
2020-04-30 13:22:31 +00:00
|
|
|
export PubSubObserver
|
2020-09-21 09:16:29 +00:00
|
|
|
export protocol
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2019-09-12 02:10:38 +00:00
|
|
|
logScope:
|
2020-12-01 17:34:27 +00:00
|
|
|
topics = "libp2p pubsub"
|
2019-09-12 02:10:38 +00:00
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
const
|
|
|
|
KnownLibP2PTopics* {.strdefine.} = ""
|
|
|
|
KnownLibP2PTopicsSeq* = KnownLibP2PTopics.toLowerAscii().split(",")
|
|
|
|
|
2020-06-07 07:15:21 +00:00
|
|
|
declareGauge(libp2p_pubsub_peers, "pubsub peer instances")
|
|
|
|
declareGauge(libp2p_pubsub_topics, "pubsub subscribed topics")
|
2021-01-08 05:21:24 +00:00
|
|
|
declareCounter(libp2p_pubsub_subscriptions, "pubsub subscription operations")
|
|
|
|
declareCounter(libp2p_pubsub_unsubscriptions, "pubsub unsubscription operations")
|
|
|
|
declareGauge(libp2p_pubsub_topic_handlers, "pubsub subscribed topics handlers count", labels = ["topic"])
|
|
|
|
|
2020-06-07 07:41:23 +00:00
|
|
|
declareCounter(libp2p_pubsub_validation_success, "pubsub successfully validated messages")
|
|
|
|
declareCounter(libp2p_pubsub_validation_failure, "pubsub failed validated messages")
|
2020-10-12 07:56:00 +00:00
|
|
|
declareCounter(libp2p_pubsub_validation_ignore, "pubsub ignore validated messages")
|
2021-01-08 05:21:24 +00:00
|
|
|
|
|
|
|
declarePublicCounter(libp2p_pubsub_messages_published, "published messages", labels = ["topic"])
|
|
|
|
declarePublicCounter(libp2p_pubsub_messages_rebroadcasted, "re-broadcasted messages", labels = ["topic"])
|
|
|
|
|
|
|
|
declarePublicCounter(libp2p_pubsub_broadcast_subscriptions, "pubsub broadcast subscriptions", labels = ["topic"])
|
|
|
|
declarePublicCounter(libp2p_pubsub_broadcast_unsubscriptions, "pubsub broadcast unsubscriptions", labels = ["topic"])
|
|
|
|
declarePublicCounter(libp2p_pubsub_broadcast_messages, "pubsub broadcast messages", labels = ["topic"])
|
|
|
|
|
|
|
|
declarePublicCounter(libp2p_pubsub_received_subscriptions, "pubsub received subscriptions", labels = ["topic"])
|
|
|
|
declarePublicCounter(libp2p_pubsub_received_unsubscriptions, "pubsub received subscriptions", labels = ["topic"])
|
|
|
|
declarePublicCounter(libp2p_pubsub_received_messages, "pubsub received messages", labels = ["topic"])
|
|
|
|
|
|
|
|
declarePublicCounter(libp2p_pubsub_broadcast_iwant, "pubsub broadcast iwant")
|
|
|
|
|
|
|
|
declarePublicCounter(libp2p_pubsub_broadcast_ihave, "pubsub broadcast ihave", labels = ["topic"])
|
|
|
|
declarePublicCounter(libp2p_pubsub_broadcast_graft, "pubsub broadcast graft", labels = ["topic"])
|
|
|
|
declarePublicCounter(libp2p_pubsub_broadcast_prune, "pubsub broadcast prune", labels = ["topic"])
|
|
|
|
|
|
|
|
declarePublicCounter(libp2p_pubsub_received_iwant, "pubsub broadcast iwant")
|
|
|
|
|
|
|
|
declarePublicCounter(libp2p_pubsub_received_ihave, "pubsub broadcast ihave", labels = ["topic"])
|
|
|
|
declarePublicCounter(libp2p_pubsub_received_graft, "pubsub broadcast graft", labels = ["topic"])
|
|
|
|
declarePublicCounter(libp2p_pubsub_received_prune, "pubsub broadcast prune", labels = ["topic"])
|
2020-06-07 07:15:21 +00:00
|
|
|
|
2019-09-10 02:15:52 +00:00
|
|
|
type
|
2019-12-17 05:24:03 +00:00
|
|
|
TopicHandler* = proc(topic: string,
|
|
|
|
data: seq[byte]): Future[void] {.gcsafe.}
|
|
|
|
|
2020-10-12 07:56:00 +00:00
|
|
|
ValidationResult* {.pure.} = enum
|
|
|
|
Accept, Reject, Ignore
|
|
|
|
|
2019-12-17 05:24:03 +00:00
|
|
|
ValidatorHandler* = proc(topic: string,
|
2020-10-12 07:56:00 +00:00
|
|
|
message: Message): Future[ValidationResult] {.gcsafe, closure.}
|
2019-09-24 16:16:39 +00:00
|
|
|
|
|
|
|
TopicPair* = tuple[topic: string, handler: TopicHandler]
|
2019-09-12 02:10:38 +00:00
|
|
|
|
2020-06-28 15:56:38 +00:00
|
|
|
MsgIdProvider* =
|
2020-10-21 03:26:04 +00:00
|
|
|
proc(m: Message): MessageID {.noSideEffect, raises: [Defect], nimcall, gcsafe.}
|
2020-06-28 15:56:38 +00:00
|
|
|
|
2019-09-10 02:15:52 +00:00
|
|
|
Topic* = object
|
2020-09-21 09:16:29 +00:00
|
|
|
# make this a variant type if one day we have different Params structs
|
2019-09-10 02:15:52 +00:00
|
|
|
name*: string
|
2019-09-24 16:16:39 +00:00
|
|
|
handler*: seq[TopicHandler]
|
2019-09-10 02:15:52 +00:00
|
|
|
|
|
|
|
PubSub* = ref object of LPProtocol
|
2020-09-22 07:05:53 +00:00
|
|
|
switch*: Switch # the switch used to dial/connect to peers
|
|
|
|
peerInfo*: PeerInfo # this peer's info
|
|
|
|
topics*: Table[string, Topic] # local topics
|
|
|
|
peers*: Table[PeerID, PubSubPeer] ##\
|
|
|
|
## Peers that we are interested to gossip with (but not necessarily
|
|
|
|
## yet connected to)
|
|
|
|
triggerSelf*: bool # trigger own local handler on publish
|
|
|
|
verifySignature*: bool # enable signature verification
|
|
|
|
sign*: bool # enable message signing
|
2019-12-17 05:24:03 +00:00
|
|
|
validators*: Table[string, HashSet[ValidatorHandler]]
|
2020-09-22 07:05:53 +00:00
|
|
|
observers: ref seq[PubSubObserver] # ref as in smart_ptr
|
|
|
|
msgIdProvider*: MsgIdProvider # Turn message into message id (not nil)
|
2020-07-15 03:51:33 +00:00
|
|
|
msgSeqno*: uint64
|
2020-09-23 15:56:33 +00:00
|
|
|
anonymize*: bool # if we omit fromPeer and seqno from RPC messages we send
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
knownTopics*: HashSet[string]
|
|
|
|
|
2020-11-01 20:49:25 +00:00
|
|
|
method unsubscribePeer*(p: PubSub, peerId: PeerID) {.base.} =
|
2020-07-08 00:33:05 +00:00
|
|
|
## handle peer disconnects
|
|
|
|
##
|
|
|
|
|
2020-11-10 04:14:46 +00:00
|
|
|
debug "unsubscribing pubsub peer", peerId
|
2020-11-01 20:49:25 +00:00
|
|
|
p.peers.del(peerId)
|
2020-07-08 00:33:05 +00:00
|
|
|
|
2020-08-12 00:05:49 +00:00
|
|
|
libp2p_pubsub_peers.set(p.peers.len.int64)
|
2020-07-17 19:46:24 +00:00
|
|
|
|
2020-09-04 16:31:43 +00:00
|
|
|
proc send*(p: PubSub, peer: PubSubPeer, msg: RPCMsg) =
|
|
|
|
## Attempt to send `msg` to remote peer
|
2020-08-12 00:05:49 +00:00
|
|
|
##
|
2020-07-17 19:46:24 +00:00
|
|
|
|
2020-09-22 07:05:53 +00:00
|
|
|
trace "sending pubsub message to peer", peer, msg = shortLog(msg)
|
2020-09-25 16:39:34 +00:00
|
|
|
peer.send(msg, p.anonymize)
|
2020-08-12 00:05:49 +00:00
|
|
|
|
|
|
|
proc broadcast*(
|
|
|
|
p: PubSub,
|
2020-09-01 07:33:03 +00:00
|
|
|
sendPeers: openArray[PubSubPeer],
|
|
|
|
msg: RPCMsg) = # raises: [Defect]
|
2020-09-04 16:31:43 +00:00
|
|
|
## Attempt to send `msg` to the given peers
|
2020-08-12 00:05:49 +00:00
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
let npeers = sendPeers.len.int64
|
|
|
|
for sub in msg.subscriptions:
|
|
|
|
if sub.subscribe:
|
|
|
|
if p.knownTopics.contains(sub.topic):
|
|
|
|
libp2p_pubsub_broadcast_subscriptions.inc(npeers, labelValues = [sub.topic])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_broadcast_subscriptions.inc(npeers, labelValues = ["generic"])
|
|
|
|
else:
|
|
|
|
if p.knownTopics.contains(sub.topic):
|
|
|
|
libp2p_pubsub_broadcast_unsubscriptions.inc(npeers, labelValues = [sub.topic])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_broadcast_unsubscriptions.inc(npeers, labelValues = ["generic"])
|
|
|
|
|
|
|
|
for smsg in msg.messages:
|
|
|
|
for topic in smsg.topicIDs:
|
|
|
|
if p.knownTopics.contains(topic):
|
|
|
|
libp2p_pubsub_broadcast_messages.inc(npeers, labelValues = [topic])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_broadcast_messages.inc(npeers, labelValues = ["generic"])
|
|
|
|
|
|
|
|
if msg.control.isSome():
|
|
|
|
libp2p_pubsub_broadcast_iwant.inc(npeers * msg.control.get().iwant.len.int64)
|
|
|
|
|
|
|
|
let control = msg.control.get()
|
|
|
|
for ihave in control.ihave:
|
|
|
|
if p.knownTopics.contains(ihave.topicID):
|
|
|
|
libp2p_pubsub_broadcast_ihave.inc(npeers, labelValues = [ihave.topicID])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_broadcast_ihave.inc(npeers, labelValues = ["generic"])
|
|
|
|
for graft in control.graft:
|
|
|
|
if p.knownTopics.contains(graft.topicID):
|
|
|
|
libp2p_pubsub_broadcast_graft.inc(npeers, labelValues = [graft.topicID])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_broadcast_graft.inc(npeers, labelValues = ["generic"])
|
|
|
|
for prune in control.prune:
|
|
|
|
if p.knownTopics.contains(prune.topicID):
|
|
|
|
libp2p_pubsub_broadcast_prune.inc(npeers, labelValues = [prune.topicID])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_broadcast_prune.inc(npeers, labelValues = ["generic"])
|
|
|
|
|
2020-08-15 19:50:31 +00:00
|
|
|
trace "broadcasting messages to peers",
|
2020-09-04 16:31:43 +00:00
|
|
|
peers = sendPeers.len, msg = shortLog(msg)
|
2020-09-01 07:33:03 +00:00
|
|
|
for peer in sendPeers:
|
|
|
|
p.send(peer, msg)
|
2020-07-17 19:46:24 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
proc sendSubs*(p: PubSub,
|
|
|
|
peer: PubSubPeer,
|
|
|
|
topics: seq[string],
|
2020-09-01 07:33:03 +00:00
|
|
|
subscribe: bool) =
|
2019-12-06 02:16:18 +00:00
|
|
|
## send subscriptions to remote peer
|
2020-09-01 07:33:03 +00:00
|
|
|
p.send(peer, RPCMsg.withSubs(topics, subscribe))
|
2021-01-08 05:21:24 +00:00
|
|
|
for topic in topics:
|
|
|
|
if subscribe:
|
|
|
|
if p.knownTopics.contains(topic):
|
|
|
|
libp2p_pubsub_broadcast_subscriptions.inc(labelValues = [topic])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_broadcast_subscriptions.inc(labelValues = ["generic"])
|
|
|
|
else:
|
|
|
|
if p.knownTopics.contains(topic):
|
|
|
|
libp2p_pubsub_broadcast_unsubscriptions.inc(labelValues = [topic])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_broadcast_unsubscriptions.inc(labelValues = ["generic"])
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2019-12-17 05:24:03 +00:00
|
|
|
method subscribeTopic*(p: PubSub,
|
|
|
|
topic: string,
|
|
|
|
subscribe: bool,
|
2020-08-17 10:10:22 +00:00
|
|
|
peer: PubSubPeer) {.base.} =
|
2020-07-16 10:06:57 +00:00
|
|
|
# called when remote peer subscribes to a topic
|
2020-07-08 00:33:05 +00:00
|
|
|
discard
|
2019-12-17 05:24:03 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
method rpcHandler*(p: PubSub,
|
|
|
|
peer: PubSubPeer,
|
2020-09-01 07:33:03 +00:00
|
|
|
rpcMsg: RPCMsg) {.async, base.} =
|
2019-12-06 02:16:18 +00:00
|
|
|
## handle rpc messages
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "processing RPC message", msg = rpcMsg.shortLog, peer
|
2020-09-01 07:33:03 +00:00
|
|
|
for s in rpcMsg.subscriptions: # subscribe/unsubscribe the peer for each topic
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "about to subscribe to topic", topicId = s.topic, peer
|
2020-09-01 07:33:03 +00:00
|
|
|
p.subscribeTopic(s.topic, s.subscribe, peer)
|
2019-12-17 05:24:03 +00:00
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
for sub in rpcMsg.subscriptions:
|
|
|
|
if sub.subscribe:
|
|
|
|
if p.knownTopics.contains(sub.topic):
|
|
|
|
libp2p_pubsub_received_subscriptions.inc(labelValues = [sub.topic])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_received_subscriptions.inc(labelValues = ["generic"])
|
|
|
|
else:
|
|
|
|
if p.knownTopics.contains(sub.topic):
|
|
|
|
libp2p_pubsub_received_unsubscriptions.inc(labelValues = [sub.topic])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_received_unsubscriptions.inc(labelValues = ["generic"])
|
|
|
|
|
|
|
|
for smsg in rpcMsg.messages:
|
|
|
|
for topic in smsg.topicIDs:
|
|
|
|
if p.knownTopics.contains(topic):
|
|
|
|
libp2p_pubsub_received_messages.inc(labelValues = [topic])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_received_messages.inc(labelValues = ["generic"])
|
|
|
|
|
|
|
|
if rpcMsg.control.isSome():
|
|
|
|
libp2p_pubsub_received_iwant.inc(rpcMsg.control.get().iwant.len.int64)
|
|
|
|
|
|
|
|
let control = rpcMsg.control.get()
|
|
|
|
for ihave in control.ihave:
|
|
|
|
if p.knownTopics.contains(ihave.topicID):
|
|
|
|
libp2p_pubsub_received_ihave.inc(labelValues = [ihave.topicID])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_received_ihave.inc(labelValues = ["generic"])
|
|
|
|
for graft in control.graft:
|
|
|
|
if p.knownTopics.contains(graft.topicID):
|
|
|
|
libp2p_pubsub_received_graft.inc(labelValues = [graft.topicID])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_received_graft.inc(labelValues = ["generic"])
|
|
|
|
for prune in control.prune:
|
|
|
|
if p.knownTopics.contains(prune.topicID):
|
|
|
|
libp2p_pubsub_received_prune.inc(labelValues = [prune.topicID])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_received_prune.inc(labelValues = ["generic"])
|
|
|
|
|
2020-09-21 09:16:29 +00:00
|
|
|
method onNewPeer(p: PubSub, peer: PubSubPeer) {.base.} = discard
|
|
|
|
|
2020-09-22 07:05:53 +00:00
|
|
|
method onPubSubPeerEvent*(p: PubSub, peer: PubsubPeer, event: PubsubPeerEvent) {.base, gcsafe.} =
|
|
|
|
# Peer event is raised for the send connection in particular
|
|
|
|
case event.kind
|
|
|
|
of PubSubPeerEventKind.Connected:
|
2020-09-28 07:11:18 +00:00
|
|
|
if p.topics.len > 0:
|
|
|
|
p.sendSubs(peer, toSeq(p.topics.keys), true)
|
2020-09-22 07:05:53 +00:00
|
|
|
of PubSubPeerEventKind.Disconnected:
|
|
|
|
discard
|
|
|
|
|
2020-08-12 00:05:49 +00:00
|
|
|
proc getOrCreatePeer*(
|
|
|
|
p: PubSub,
|
|
|
|
peer: PeerID,
|
2020-09-21 09:16:29 +00:00
|
|
|
protos: seq[string]): PubSubPeer =
|
2020-08-12 00:05:49 +00:00
|
|
|
if peer in p.peers:
|
|
|
|
return p.peers[peer]
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-09-22 07:05:53 +00:00
|
|
|
proc getConn(): Future[Connection] =
|
|
|
|
p.switch.dial(peer, protos)
|
|
|
|
|
|
|
|
proc onEvent(peer: PubsubPeer, event: PubsubPeerEvent) {.gcsafe.} =
|
|
|
|
p.onPubSubPeerEvent(peer, event)
|
2020-09-01 07:33:03 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
# create new pubsub peer
|
2020-09-22 07:05:53 +00:00
|
|
|
let pubSubPeer = newPubSubPeer(peer, getConn, onEvent, protos[0])
|
2020-11-10 04:14:46 +00:00
|
|
|
debug "created new pubsub peer", peer
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-08-12 00:05:49 +00:00
|
|
|
p.peers[peer] = pubSubPeer
|
|
|
|
pubSubPeer.observers = p.observers
|
2020-07-13 14:15:27 +00:00
|
|
|
|
2020-09-21 09:16:29 +00:00
|
|
|
onNewPeer(p, pubSubPeer)
|
|
|
|
|
|
|
|
# metrics
|
2020-07-13 14:15:27 +00:00
|
|
|
libp2p_pubsub_peers.set(p.peers.len.int64)
|
2020-09-01 07:33:03 +00:00
|
|
|
|
|
|
|
pubsubPeer.connect()
|
|
|
|
|
2020-08-12 00:05:49 +00:00
|
|
|
return pubSubPeer
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-09-01 07:33:03 +00:00
|
|
|
proc handleData*(p: PubSub, topic: string, data: seq[byte]): Future[void] {.async.} =
|
|
|
|
if topic notin p.topics: return # Not subscribed
|
|
|
|
|
2020-12-18 15:56:46 +00:00
|
|
|
# gather all futures without yielding to scheduler
|
|
|
|
var futs = p.topics[topic].handler.mapIt(it(topic, data))
|
2021-01-08 05:21:24 +00:00
|
|
|
|
2020-12-18 15:56:46 +00:00
|
|
|
try:
|
|
|
|
futs = await allFinished(futs)
|
|
|
|
except CancelledError:
|
|
|
|
# propagate cancellation
|
|
|
|
for fut in futs:
|
|
|
|
if not(fut.finished):
|
|
|
|
fut.cancel()
|
2021-01-08 05:21:24 +00:00
|
|
|
|
2020-12-18 15:56:46 +00:00
|
|
|
# check for errors in futures
|
|
|
|
for fut in futs:
|
|
|
|
if fut.failed:
|
|
|
|
let err = fut.readError()
|
|
|
|
warn "Error in topic handler", msg = err.msg
|
2020-09-01 07:33:03 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
method handleConn*(p: PubSub,
|
|
|
|
conn: Connection,
|
2019-12-17 05:24:03 +00:00
|
|
|
proto: string) {.base, async.} =
|
2019-12-06 02:16:18 +00:00
|
|
|
## handle incoming connections
|
|
|
|
##
|
|
|
|
## this proc will:
|
|
|
|
## 1) register a new PubSubPeer for the connection
|
|
|
|
## 2) register a handler with the peer;
|
|
|
|
## this handler gets called on every rpc message
|
|
|
|
## that the peer receives
|
|
|
|
## 3) ask the peer to subscribe us to every topic
|
|
|
|
## that we're interested in
|
|
|
|
##
|
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
if isNil(conn.peerInfo):
|
|
|
|
trace "no valid PeerId for peer"
|
|
|
|
await conn.close()
|
|
|
|
return
|
2020-05-21 15:01:36 +00:00
|
|
|
|
2020-09-01 07:33:03 +00:00
|
|
|
proc handler(peer: PubSubPeer, msg: RPCMsg): Future[void] =
|
2020-07-08 00:33:05 +00:00
|
|
|
# call pubsub rpc handler
|
2020-09-01 07:33:03 +00:00
|
|
|
p.rpcHandler(peer, msg)
|
2020-05-21 15:01:36 +00:00
|
|
|
|
2020-09-21 09:16:29 +00:00
|
|
|
let peer = p.getOrCreatePeer(conn.peerInfo.peerId, @[proto])
|
2020-08-21 02:50:33 +00:00
|
|
|
|
2020-09-01 07:33:03 +00:00
|
|
|
try:
|
2020-05-21 15:01:36 +00:00
|
|
|
peer.handler = handler
|
|
|
|
await peer.handle(conn) # spawn peer read loop
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "pubsub peer handler ended", conn
|
2020-06-29 15:15:31 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
2020-05-21 15:01:36 +00:00
|
|
|
except CatchableError as exc:
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "exception ocurred in pubsub handle", exc = exc.msg, conn
|
2020-07-08 00:33:05 +00:00
|
|
|
finally:
|
2020-09-24 05:30:19 +00:00
|
|
|
await conn.closeWithEOF()
|
2020-04-07 15:49:43 +00:00
|
|
|
|
2020-08-12 00:05:49 +00:00
|
|
|
method subscribePeer*(p: PubSub, peer: PeerID) {.base.} =
|
|
|
|
## subscribe to remote peer to receive/send pubsub
|
|
|
|
## messages
|
|
|
|
##
|
2020-07-08 00:33:05 +00:00
|
|
|
|
2020-09-21 09:16:29 +00:00
|
|
|
let peer = p.getOrCreatePeer(peer, p.codecs)
|
|
|
|
peer.outbound = true # flag as outbound
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
proc updateTopicMetrics(p: PubSub, topic: string) =
|
|
|
|
# metrics
|
|
|
|
libp2p_pubsub_topics.set(p.topics.len.int64)
|
|
|
|
if p.knownTopics.contains(topic):
|
|
|
|
libp2p_pubsub_topic_handlers.set(p.topics[topic].handler.len.int64, labelValues = [topic])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_topic_handlers.set(0, labelValues = ["other"])
|
|
|
|
for key, val in p.topics:
|
|
|
|
if not p.knownTopics.contains(key):
|
|
|
|
libp2p_pubsub_topic_handlers.inc(val.handler.len.int64, labelValues = ["other"])
|
|
|
|
|
2019-09-24 16:16:39 +00:00
|
|
|
method unsubscribe*(p: PubSub,
|
2020-12-19 14:43:32 +00:00
|
|
|
topics: seq[TopicPair]) {.base.} =
|
2019-09-10 02:15:52 +00:00
|
|
|
## unsubscribe from a list of ``topic`` strings
|
2019-09-24 16:16:39 +00:00
|
|
|
for t in topics:
|
2020-11-10 04:14:46 +00:00
|
|
|
let
|
2020-10-30 12:49:54 +00:00
|
|
|
handler = t.handler
|
|
|
|
ttopic = t.topic
|
|
|
|
closureScope:
|
|
|
|
p.topics.withValue(ttopic, topic):
|
|
|
|
topic[].handler.keepIf(proc (x: auto): bool = x != handler)
|
|
|
|
|
|
|
|
if topic[].handler.len == 0:
|
|
|
|
# make sure we delete the topic if
|
|
|
|
# no more handlers are left
|
|
|
|
p.topics.del(ttopic)
|
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
p.updateTopicMetrics(ttopic)
|
|
|
|
|
|
|
|
libp2p_pubsub_unsubscriptions.inc()
|
2020-07-09 20:21:47 +00:00
|
|
|
|
2020-07-16 19:26:57 +00:00
|
|
|
proc unsubscribe*(p: PubSub,
|
2020-07-27 19:33:51 +00:00
|
|
|
topic: string,
|
2020-12-19 14:43:32 +00:00
|
|
|
handler: TopicHandler) =
|
2019-09-24 16:16:39 +00:00
|
|
|
## unsubscribe from a ``topic`` string
|
2020-07-27 19:33:51 +00:00
|
|
|
##
|
2020-06-07 07:15:21 +00:00
|
|
|
p.unsubscribe(@[(topic, handler)])
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2020-12-19 14:43:32 +00:00
|
|
|
method unsubscribeAll*(p: PubSub, topic: string) {.base.} =
|
2021-01-08 05:21:24 +00:00
|
|
|
if topic notin p.topics:
|
|
|
|
debug "unsubscribeAll called for an unknown topic", topic
|
|
|
|
else:
|
|
|
|
p.topics.del(topic)
|
|
|
|
|
|
|
|
p.updateTopicMetrics(topic)
|
|
|
|
|
|
|
|
libp2p_pubsub_unsubscriptions.inc()
|
2020-07-20 16:16:13 +00:00
|
|
|
|
2019-09-24 16:16:39 +00:00
|
|
|
method subscribe*(p: PubSub,
|
|
|
|
topic: string,
|
2020-12-19 14:43:32 +00:00
|
|
|
handler: TopicHandler) {.base.} =
|
2019-09-10 02:15:52 +00:00
|
|
|
## subscribe to a topic
|
|
|
|
##
|
|
|
|
## ``topic`` - a string topic to subscribe to
|
|
|
|
##
|
2019-12-10 20:50:35 +00:00
|
|
|
## ``handler`` - is a user provided proc
|
|
|
|
## that will be triggered
|
2019-09-10 02:15:52 +00:00
|
|
|
## on every received message
|
|
|
|
##
|
2019-12-06 02:16:18 +00:00
|
|
|
if topic notin p.topics:
|
2019-09-28 19:55:35 +00:00
|
|
|
trace "subscribing to topic", name = topic
|
2019-09-24 16:16:39 +00:00
|
|
|
p.topics[topic] = Topic(name: topic)
|
2019-09-28 19:55:35 +00:00
|
|
|
|
2019-09-24 16:16:39 +00:00
|
|
|
p.topics[topic].handler.add(handler)
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2020-09-01 07:33:03 +00:00
|
|
|
for _, peer in p.peers:
|
|
|
|
p.sendSubs(peer, @[topic], true)
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
p.updateTopicMetrics(topic)
|
|
|
|
|
|
|
|
libp2p_pubsub_subscriptions.inc()
|
2020-06-07 07:15:21 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
method publish*(p: PubSub,
|
|
|
|
topic: string,
|
2020-09-01 07:33:03 +00:00
|
|
|
data: seq[byte]): Future[int] {.base, async.} =
|
2019-09-10 02:15:52 +00:00
|
|
|
## publish to a ``topic``
|
2020-09-04 16:31:43 +00:00
|
|
|
## The return value is the number of neighbours that we attempted to send the
|
|
|
|
## message to, excluding self. Note that this is an optimistic number of
|
|
|
|
## attempts - the number of peers that actually receive the message might
|
|
|
|
## be lower.
|
2020-09-01 07:33:03 +00:00
|
|
|
if p.triggerSelf:
|
|
|
|
await handleData(p, topic, data)
|
2019-10-03 22:22:49 +00:00
|
|
|
|
2020-07-08 00:33:05 +00:00
|
|
|
return 0
|
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
method initPubSub*(p: PubSub) {.base.} =
|
2020-05-27 18:33:49 +00:00
|
|
|
## perform pubsub initialization
|
2020-04-30 13:22:31 +00:00
|
|
|
p.observers = new(seq[PubSubObserver])
|
2020-06-28 15:56:38 +00:00
|
|
|
if p.msgIdProvider == nil:
|
|
|
|
p.msgIdProvider = defaultMsgIdProvider
|
2019-12-06 02:16:18 +00:00
|
|
|
|
|
|
|
method start*(p: PubSub) {.async, base.} =
|
|
|
|
## start pubsub
|
|
|
|
discard
|
|
|
|
|
|
|
|
method stop*(p: PubSub) {.async, base.} =
|
|
|
|
## stopt pubsub
|
2019-09-10 02:15:52 +00:00
|
|
|
discard
|
2019-10-03 22:22:49 +00:00
|
|
|
|
2019-12-17 05:24:03 +00:00
|
|
|
method addValidator*(p: PubSub,
|
|
|
|
topic: varargs[string],
|
|
|
|
hook: ValidatorHandler) {.base.} =
|
|
|
|
for t in topic:
|
|
|
|
if t notin p.validators:
|
|
|
|
p.validators[t] = initHashSet[ValidatorHandler]()
|
|
|
|
|
|
|
|
trace "adding validator for topic", topicId = t
|
|
|
|
p.validators[t].incl(hook)
|
|
|
|
|
|
|
|
method removeValidator*(p: PubSub,
|
|
|
|
topic: varargs[string],
|
|
|
|
hook: ValidatorHandler) {.base.} =
|
|
|
|
for t in topic:
|
|
|
|
if t in p.validators:
|
|
|
|
p.validators[t].excl(hook)
|
|
|
|
|
2020-10-12 07:56:00 +00:00
|
|
|
method validate*(p: PubSub, message: Message): Future[ValidationResult] {.async, base.} =
|
|
|
|
var pending: seq[Future[ValidationResult]]
|
2019-12-17 05:24:03 +00:00
|
|
|
trace "about to validate message"
|
|
|
|
for topic in message.topicIDs:
|
|
|
|
trace "looking for validators on topic", topicID = topic,
|
|
|
|
registered = toSeq(p.validators.keys)
|
|
|
|
if topic in p.validators:
|
|
|
|
trace "running validators for topic", topicID = topic
|
|
|
|
# TODO: add timeout to validator
|
|
|
|
pending.add(p.validators[topic].mapIt(it(topic, message)))
|
|
|
|
|
2020-10-12 07:56:00 +00:00
|
|
|
result = ValidationResult.Accept
|
2020-04-11 04:08:25 +00:00
|
|
|
let futs = await allFinished(pending)
|
2020-10-12 07:56:00 +00:00
|
|
|
for fut in futs:
|
|
|
|
if fut.failed:
|
|
|
|
result = ValidationResult.Reject
|
|
|
|
break
|
|
|
|
let res = fut.read()
|
|
|
|
if res != ValidationResult.Accept:
|
|
|
|
result = res
|
|
|
|
break
|
2020-11-10 04:14:46 +00:00
|
|
|
|
2020-10-12 07:56:00 +00:00
|
|
|
case result
|
2020-11-10 04:14:46 +00:00
|
|
|
of ValidationResult.Accept:
|
2020-06-07 07:15:21 +00:00
|
|
|
libp2p_pubsub_validation_success.inc()
|
2020-10-12 07:56:00 +00:00
|
|
|
of ValidationResult.Reject:
|
2020-06-07 07:15:21 +00:00
|
|
|
libp2p_pubsub_validation_failure.inc()
|
2020-10-12 07:56:00 +00:00
|
|
|
of ValidationResult.Ignore:
|
|
|
|
libp2p_pubsub_validation_ignore.inc()
|
2019-12-17 05:24:03 +00:00
|
|
|
|
2020-09-21 09:16:29 +00:00
|
|
|
proc init*[PubParams: object | bool](
|
2020-08-12 00:05:49 +00:00
|
|
|
P: typedesc[PubSub],
|
|
|
|
switch: Switch,
|
|
|
|
triggerSelf: bool = false,
|
2020-09-23 15:56:33 +00:00
|
|
|
anonymize: bool = false,
|
2020-08-12 00:05:49 +00:00
|
|
|
verifySignature: bool = true,
|
|
|
|
sign: bool = true,
|
2020-09-21 09:16:29 +00:00
|
|
|
msgIdProvider: MsgIdProvider = defaultMsgIdProvider,
|
|
|
|
parameters: PubParams = false): P =
|
|
|
|
let pubsub =
|
|
|
|
when PubParams is bool:
|
|
|
|
P(switch: switch,
|
|
|
|
peerInfo: switch.peerInfo,
|
|
|
|
triggerSelf: triggerSelf,
|
2020-09-23 15:56:33 +00:00
|
|
|
anonymize: anonymize,
|
2020-09-21 09:16:29 +00:00
|
|
|
verifySignature: verifySignature,
|
|
|
|
sign: sign,
|
|
|
|
peers: initTable[PeerID, PubSubPeer](),
|
|
|
|
topics: initTable[string, Topic](),
|
|
|
|
msgIdProvider: msgIdProvider)
|
|
|
|
else:
|
|
|
|
P(switch: switch,
|
|
|
|
peerInfo: switch.peerInfo,
|
|
|
|
triggerSelf: triggerSelf,
|
2020-09-23 15:56:33 +00:00
|
|
|
anonymize: anonymize,
|
2020-09-21 09:16:29 +00:00
|
|
|
verifySignature: verifySignature,
|
|
|
|
sign: sign,
|
|
|
|
peers: initTable[PeerID, PubSubPeer](),
|
|
|
|
topics: initTable[string, Topic](),
|
|
|
|
msgIdProvider: msgIdProvider,
|
|
|
|
parameters: parameters)
|
2020-09-15 20:19:22 +00:00
|
|
|
|
|
|
|
proc peerEventHandler(peerId: PeerID, event: PeerEvent) {.async.} =
|
2020-11-28 16:59:47 +00:00
|
|
|
if event.kind == PeerEventKind.Joined:
|
2020-09-15 20:19:22 +00:00
|
|
|
pubsub.subscribePeer(peerId)
|
|
|
|
else:
|
|
|
|
pubsub.unsubscribePeer(peerId)
|
|
|
|
|
2020-11-28 16:59:47 +00:00
|
|
|
switch.addPeerEventHandler(peerEventHandler, PeerEventKind.Joined)
|
|
|
|
switch.addPeerEventHandler(peerEventHandler, PeerEventKind.Left)
|
2020-09-15 20:19:22 +00:00
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
pubsub.knownTopics = KnownLibP2PTopicsSeq.toHashSet()
|
|
|
|
|
2020-09-15 20:19:22 +00:00
|
|
|
pubsub.initPubSub()
|
2020-11-10 04:14:46 +00:00
|
|
|
|
2020-09-15 20:19:22 +00:00
|
|
|
return pubsub
|
2020-04-30 13:22:31 +00:00
|
|
|
|
2020-09-21 09:16:29 +00:00
|
|
|
proc addObserver*(p: PubSub; observer: PubSubObserver) = p.observers[] &= observer
|
2020-04-30 13:22:31 +00:00
|
|
|
|
|
|
|
proc removeObserver*(p: PubSub; observer: PubSubObserver) =
|
|
|
|
let idx = p.observers[].find(observer)
|
|
|
|
if idx != -1:
|
|
|
|
p.observers[].del(idx)
|