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-05-21 16:27:01 +00:00
|
|
|
{.push raises: [Defect].}
|
|
|
|
|
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
|
2021-04-18 08:08:33 +00:00
|
|
|
import ./pubsubpeer,
|
|
|
|
./rpc/[message, messages, protobuf],
|
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
|
2021-05-21 16:27:01 +00:00
|
|
|
InitializationError* = object of LPError
|
|
|
|
|
2019-12-17 05:24:03 +00:00
|
|
|
TopicHandler* = proc(topic: string,
|
2021-05-06 22:43:45 +00:00
|
|
|
data: seq[byte]): Future[void] {.gcsafe, raises: [Defect].}
|
2019-12-17 05:24:03 +00:00
|
|
|
|
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,
|
2021-05-06 22:43:45 +00:00
|
|
|
message: Message): Future[ValidationResult] {.gcsafe, raises: [Defect].}
|
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* =
|
2021-01-13 14:49:44 +00:00
|
|
|
proc(m: Message): MessageID {.noSideEffect, raises: [Defect], gcsafe.}
|
|
|
|
|
|
|
|
SubscriptionValidator* =
|
|
|
|
proc(topic: string): bool {.raises: [Defect], gcsafe.}
|
2020-06-28 15:56:38 +00:00
|
|
|
|
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
|
2021-05-06 22:43:45 +00:00
|
|
|
topics*: Table[string, seq[TopicHandler]] # the topics that _we_ are interested in
|
2020-09-22 07:05:53 +00:00
|
|
|
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
|
2021-01-13 14:49:44 +00:00
|
|
|
subscriptionValidator*: SubscriptionValidator # callback used to validate subscriptions
|
2021-05-06 22:43:45 +00:00
|
|
|
topicsHigh*: int # the maximum number of topics a peer is allowed to subscribe to
|
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
|
|
|
|
2021-03-09 12:22:52 +00:00
|
|
|
proc send*(p: PubSub, peer: PubSubPeer, msg: RPCMsg) {.raises: [Defect].} =
|
2020-09-04 16:31:43 +00:00
|
|
|
## 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,
|
2021-04-18 08:08:33 +00:00
|
|
|
sendPeers: auto, # Iteratble[PubSubPeer]
|
2021-03-09 12:22:52 +00:00
|
|
|
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)
|
2021-04-18 08:08:33 +00:00
|
|
|
|
|
|
|
if anyIt(sendPeers, it.hasObservers):
|
|
|
|
for peer in sendPeers:
|
|
|
|
p.send(peer, msg)
|
|
|
|
else:
|
|
|
|
# Fast path that only encodes message once
|
|
|
|
let encoded = encodeRpcMsg(msg, p.anonymize)
|
|
|
|
for peer in sendPeers:
|
|
|
|
peer.sendEncoded(encoded)
|
2020-07-17 19:46:24 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
proc sendSubs*(p: PubSub,
|
|
|
|
peer: PubSubPeer,
|
2021-05-06 22:43:45 +00:00
|
|
|
topics: openArray[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-05-06 22:43:45 +00:00
|
|
|
|
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
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
proc updateMetrics*(p: PubSub, rpcMsg: RPCMsg) =
|
2021-02-12 03:27:26 +00:00
|
|
|
for i in 0..<min(rpcMsg.subscriptions.len, p.topicsHigh):
|
2021-05-06 22:43:45 +00:00
|
|
|
template sub(): untyped = rpcMsg.subscriptions[i]
|
2021-01-08 05:21:24 +00:00
|
|
|
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"])
|
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
for i in 0..<rpcMsg.messages.len():
|
|
|
|
template smsg: untyped = rpcMsg.messages[i]
|
|
|
|
for j in 0..<smsg.topicIDs.len():
|
|
|
|
template topic: untyped = smsg.topicIDs[j]
|
2021-01-08 05:21:24 +00:00
|
|
|
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)
|
2021-05-06 22:43:45 +00:00
|
|
|
template control: untyped = rpcMsg.control.unsafeGet()
|
2021-01-08 05:21:24 +00:00
|
|
|
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"])
|
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
method rpcHandler*(p: PubSub,
|
|
|
|
peer: PubSubPeer,
|
|
|
|
rpcMsg: RPCMsg): Future[void] {.base.} =
|
|
|
|
## Handler that must be overridden by concrete implementation
|
|
|
|
raiseAssert "Unimplemented"
|
2021-04-18 08:08:33 +00:00
|
|
|
|
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*(
|
2021-05-06 22:43:45 +00:00
|
|
|
p: PubSub,
|
|
|
|
peerId: PeerID,
|
|
|
|
protos: seq[string]): PubSubPeer =
|
|
|
|
p.peers.withValue(peerId, peer):
|
|
|
|
return peer[]
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-09-22 07:05:53 +00:00
|
|
|
proc getConn(): Future[Connection] =
|
2021-05-06 22:43:45 +00:00
|
|
|
p.switch.dial(peerId, protos)
|
2020-09-22 07:05:53 +00:00
|
|
|
|
2021-03-02 23:23:40 +00:00
|
|
|
proc dropConn(peer: PubSubPeer) =
|
|
|
|
proc dropConnAsync(peer: PubsubPeer) {.async.} =
|
|
|
|
try:
|
|
|
|
await p.switch.disconnect(peer.peerId)
|
2021-03-09 12:22:52 +00:00
|
|
|
except CatchableError as exc: # never cancelled
|
2021-03-02 23:23:40 +00:00
|
|
|
trace "Failed to close connection", peer, error = exc.name, msg = exc.msg
|
|
|
|
asyncSpawn dropConnAsync(peer)
|
|
|
|
|
2020-09-22 07:05:53 +00:00
|
|
|
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
|
2021-05-06 22:43:45 +00:00
|
|
|
let pubSubPeer = newPubSubPeer(peerId, getConn, dropConn, onEvent, protos[0])
|
|
|
|
debug "created new pubsub peer", peerId
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
p.peers[peerId] = pubSubPeer
|
2020-08-12 00:05:49 +00:00
|
|
|
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
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
proc handleData*(p: PubSub, topic: string, data: seq[byte]): Future[void] =
|
|
|
|
# Start work on all data handlers without copying data into closure like
|
|
|
|
# happens on {.async.} transformation
|
|
|
|
p.topics.withValue(topic, handlers) do:
|
|
|
|
var futs = newSeq[Future[void]]()
|
|
|
|
|
|
|
|
for handler in handlers[]:
|
|
|
|
if handler != nil: # allow nil handlers
|
|
|
|
let fut = handler(topic, data)
|
|
|
|
if not fut.completed(): # Fast path for successful sync handlers
|
|
|
|
futs.add(fut)
|
|
|
|
|
|
|
|
if futs.len() > 0:
|
|
|
|
proc waiter(): Future[void] {.async.} =
|
|
|
|
# slow path - we have to wait for the handlers to complete
|
|
|
|
try:
|
|
|
|
futs = await allFinished(futs)
|
|
|
|
except CancelledError:
|
|
|
|
# propagate cancellation
|
|
|
|
for fut in futs:
|
|
|
|
if not(fut.finished):
|
|
|
|
fut.cancel()
|
|
|
|
|
|
|
|
# check for errors in futures
|
|
|
|
for fut in futs:
|
|
|
|
if fut.failed:
|
|
|
|
let err = fut.readError()
|
|
|
|
warn "Error in topic handler", msg = err.msg
|
|
|
|
return waiter()
|
|
|
|
|
|
|
|
# Fast path - futures finished synchronously or nobody cared about data
|
|
|
|
var res = newFuture[void]()
|
|
|
|
res.complete()
|
|
|
|
return res
|
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
|
|
|
|
2021-02-06 00:13:04 +00:00
|
|
|
discard p.getOrCreatePeer(peer, p.codecs)
|
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)
|
2021-05-06 22:43:45 +00:00
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
if p.knownTopics.contains(topic):
|
2021-05-06 22:43:45 +00:00
|
|
|
p.topics.withValue(topic, handlers) do:
|
|
|
|
libp2p_pubsub_topic_handlers.set(handlers[].len.int64, labelValues = [topic])
|
|
|
|
do:
|
|
|
|
libp2p_pubsub_topic_handlers.set(0, labelValues = [topic])
|
2021-01-08 05:21:24 +00:00
|
|
|
else:
|
2021-05-06 22:43:45 +00:00
|
|
|
var others: int64 = 0
|
2021-01-08 05:21:24 +00:00
|
|
|
for key, val in p.topics:
|
2021-05-06 22:43:45 +00:00
|
|
|
if key notin p.knownTopics: others += 1
|
2021-01-08 05:21:24 +00:00
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
libp2p_pubsub_topic_handlers.set(others, labelValues = ["other"])
|
2020-10-30 12:49:54 +00:00
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
method onTopicSubscription*(p: PubSub, topic: string, subscribed: bool) {.base.} =
|
|
|
|
# Called when subscribe is called the first time for a topic or unsubscribe
|
|
|
|
# removes the last handler
|
2020-10-30 12:49:54 +00:00
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
# Notify others that we are no longer interested in the topic
|
|
|
|
for _, peer in p.peers:
|
|
|
|
p.sendSubs(peer, [topic], subscribed)
|
2021-01-08 05:21:24 +00:00
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
if subscribed:
|
|
|
|
libp2p_pubsub_subscriptions.inc()
|
|
|
|
else:
|
|
|
|
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
|
|
|
##
|
2021-05-06 22:43:45 +00:00
|
|
|
p.topics.withValue(topic, handlers):
|
|
|
|
handlers[].keepItIf(it != handler)
|
|
|
|
|
|
|
|
if handlers[].len() == 0:
|
|
|
|
p.topics.del(topic)
|
|
|
|
|
|
|
|
p.onTopicSubscription(topic, false)
|
|
|
|
|
|
|
|
p.updateTopicMetrics(topic)
|
|
|
|
|
|
|
|
proc unsubscribe*(p: PubSub, topics: openArray[TopicPair]) =
|
|
|
|
## unsubscribe from a list of ``topic`` handlers
|
|
|
|
for t in topics:
|
|
|
|
p.unsubscribe(t.topic, t.handler)
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
proc unsubscribeAll*(p: PubSub, topic: string) =
|
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)
|
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
p.onTopicSubscription(topic, false)
|
2021-01-08 05:21:24 +00:00
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
p.updateTopicMetrics(topic)
|
2020-07-20 16:16:13 +00:00
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
proc subscribe*(p: PubSub,
|
|
|
|
topic: string,
|
|
|
|
handler: TopicHandler) =
|
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-09-28 19:55:35 +00:00
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
p.topics.withValue(topic, handlers) do:
|
|
|
|
# Already subscribed, just adding another handler
|
|
|
|
handlers[].add(handler)
|
|
|
|
do:
|
|
|
|
trace "subscribing to topic", name = topic
|
|
|
|
p.topics[topic] = @[handler]
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2021-05-06 22:43:45 +00:00
|
|
|
# Notify on first handler
|
|
|
|
p.onTopicSubscription(topic, true)
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2021-01-08 05:21:24 +00:00
|
|
|
p.updateTopicMetrics(topic)
|
|
|
|
|
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
|
|
|
|
|
2021-05-21 16:27:01 +00:00
|
|
|
method initPubSub*(p: PubSub)
|
|
|
|
{.base, raises: [Defect, InitializationError].} =
|
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:
|
|
|
|
trace "adding validator for topic", topicId = t
|
2021-05-06 22:43:45 +00:00
|
|
|
p.validators.mgetOrPut(t, HashSet[ValidatorHandler]()).incl(hook)
|
2019-12-17 05:24:03 +00:00
|
|
|
|
|
|
|
method removeValidator*(p: PubSub,
|
|
|
|
topic: varargs[string],
|
|
|
|
hook: ValidatorHandler) {.base.} =
|
|
|
|
for t in topic:
|
2021-05-06 22:43:45 +00:00
|
|
|
p.validators.withValue(t, validators):
|
|
|
|
validators[].excl(hook)
|
|
|
|
if validators[].len() == 0:
|
|
|
|
p.validators.del(t)
|
2019-12-17 05:24:03 +00:00
|
|
|
|
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
|
2021-04-18 08:08:33 +00:00
|
|
|
for validator in p.validators[topic]:
|
|
|
|
pending.add(validator(topic, message))
|
2019-12-17 05:24:03 +00:00
|
|
|
|
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
|
2021-04-18 08:08:33 +00:00
|
|
|
if res == ValidationResult.Reject:
|
|
|
|
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,
|
2021-01-13 14:49:44 +00:00
|
|
|
subscriptionValidator: SubscriptionValidator = nil,
|
2021-05-21 16:27:01 +00:00
|
|
|
parameters: PubParams = false): P
|
|
|
|
{.raises: [Defect, InitializationError].} =
|
2020-09-21 09:16:29 +00:00
|
|
|
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,
|
2021-01-13 14:49:44 +00:00
|
|
|
msgIdProvider: msgIdProvider,
|
2021-02-12 03:27:26 +00:00
|
|
|
subscriptionValidator: subscriptionValidator,
|
|
|
|
topicsHigh: int.high)
|
2020-09-21 09:16:29 +00:00
|
|
|
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,
|
|
|
|
msgIdProvider: msgIdProvider,
|
2021-01-13 14:49:44 +00:00
|
|
|
subscriptionValidator: subscriptionValidator,
|
2021-02-12 03:27:26 +00:00
|
|
|
parameters: parameters,
|
|
|
|
topicsHigh: int.high)
|
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)
|