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.
|
|
|
|
|
2019-12-17 05:24:03 +00:00
|
|
|
import tables, sequtils, sets
|
2019-09-12 02:10:38 +00:00
|
|
|
import chronos, chronicles
|
2019-09-10 02:15:52 +00:00
|
|
|
import pubsubpeer,
|
2019-12-06 02:16:18 +00:00
|
|
|
rpc/messages,
|
2019-09-10 02:15:52 +00:00
|
|
|
../protocol,
|
|
|
|
../../connection,
|
2020-05-06 16:31:47 +00:00
|
|
|
../../peerinfo
|
2020-06-07 07:15:21 +00:00
|
|
|
import metrics
|
2019-09-10 02:15:52 +00:00
|
|
|
|
|
|
|
export PubSubPeer
|
2020-04-30 13:22:31 +00:00
|
|
|
export PubSubObserver
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2019-09-12 02:10:38 +00:00
|
|
|
logScope:
|
2020-06-10 08:48:01 +00:00
|
|
|
topics = "pubsub"
|
2019-09-12 02:10:38 +00:00
|
|
|
|
2020-06-07 07:15:21 +00:00
|
|
|
declareGauge(libp2p_pubsub_peers, "pubsub peer instances")
|
|
|
|
declareGauge(libp2p_pubsub_topics, "pubsub subscribed topics")
|
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-06-07 07:15:21 +00:00
|
|
|
declareGauge(libp2p_pubsub_peers_per_topic, "pubsub peers per topic", labels = ["topic"])
|
|
|
|
|
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.}
|
|
|
|
|
|
|
|
ValidatorHandler* = proc(topic: string,
|
2020-03-24 07:48:05 +00:00
|
|
|
message: Message): Future[bool] {.gcsafe, closure.}
|
2019-09-24 16:16:39 +00:00
|
|
|
|
|
|
|
TopicPair* = tuple[topic: string, handler: TopicHandler]
|
2019-09-12 02:10:38 +00:00
|
|
|
|
2019-09-10 02:15:52 +00:00
|
|
|
Topic* = object
|
|
|
|
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
|
2019-12-10 20:50:35 +00:00
|
|
|
peerInfo*: PeerInfo # this peer's info
|
|
|
|
topics*: Table[string, Topic] # local topics
|
2019-12-06 02:16:18 +00:00
|
|
|
peers*: Table[string, PubSubPeer] # peerid to peer map
|
2019-12-10 20:50:35 +00:00
|
|
|
triggerSelf*: bool # trigger own local handler on publish
|
2020-05-06 09:26:08 +00:00
|
|
|
verifySignature*: bool # enable signature verification
|
|
|
|
sign*: bool # enable message signing
|
2019-12-06 02:16:18 +00:00
|
|
|
cleanupLock: AsyncLock
|
2019-12-17 05:24:03 +00:00
|
|
|
validators*: Table[string, HashSet[ValidatorHandler]]
|
2020-04-30 13:22:31 +00:00
|
|
|
observers: ref seq[PubSubObserver] # ref as in smart_ptr
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
proc sendSubs*(p: PubSub,
|
|
|
|
peer: PubSubPeer,
|
|
|
|
topics: seq[string],
|
2019-12-17 05:24:03 +00:00
|
|
|
subscribe: bool) {.async.} =
|
2019-12-06 02:16:18 +00:00
|
|
|
## send subscriptions to remote peer
|
|
|
|
trace "sending subscriptions", peer = peer.id,
|
|
|
|
subscribe = subscribe,
|
|
|
|
topicIDs = topics
|
|
|
|
|
|
|
|
var msg: RPCMsg
|
|
|
|
for t in topics:
|
2019-12-10 20:50:35 +00:00
|
|
|
trace "sending topic", peer = peer.id,
|
|
|
|
subscribe = subscribe,
|
2019-12-06 02:16:18 +00:00
|
|
|
topicName = t
|
|
|
|
msg.subscriptions.add(SubOpts(topic: t, subscribe: subscribe))
|
|
|
|
|
|
|
|
await peer.send(@[msg])
|
|
|
|
|
2019-12-17 05:24:03 +00:00
|
|
|
method subscribeTopic*(p: PubSub,
|
|
|
|
topic: string,
|
|
|
|
subscribe: bool,
|
2020-05-27 18:33:49 +00:00
|
|
|
peerId: string) {.base, async.} =
|
2020-06-07 07:15:21 +00:00
|
|
|
if subscribe:
|
|
|
|
libp2p_pubsub_peers_per_topic.inc(labelValues = [topic])
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_peers_per_topic.dec(labelValues = [topic])
|
2019-12-17 05:24:03 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
method rpcHandler*(p: PubSub,
|
|
|
|
peer: PubSubPeer,
|
2019-12-17 05:24:03 +00:00
|
|
|
rpcMsgs: seq[RPCMsg]) {.async, base.} =
|
2019-12-06 02:16:18 +00:00
|
|
|
## handle rpc messages
|
2020-03-23 06:03:36 +00:00
|
|
|
trace "processing RPC message", peer = peer.id, msgs = rpcMsgs.len
|
2020-04-30 13:22:31 +00:00
|
|
|
|
2019-12-17 05:24:03 +00:00
|
|
|
for m in rpcMsgs: # for all RPC messages
|
2020-03-23 06:03:36 +00:00
|
|
|
trace "processing messages", msg = m.shortLog
|
2019-12-17 05:24:03 +00:00
|
|
|
if m.subscriptions.len > 0: # if there are any subscriptions
|
|
|
|
for s in m.subscriptions: # subscribe/unsubscribe the peer for each topic
|
2020-05-27 18:33:49 +00:00
|
|
|
trace "about to subscribe to topic", topicId = s.topic
|
|
|
|
await p.subscribeTopic(s.topic, s.subscribe, peer.id)
|
2019-12-17 05:24:03 +00:00
|
|
|
|
|
|
|
method handleDisconnect*(p: PubSub, peer: PubSubPeer) {.async, base.} =
|
2019-12-06 02:16:18 +00:00
|
|
|
## handle peer disconnects
|
|
|
|
if peer.id in p.peers:
|
|
|
|
p.peers.del(peer.id)
|
2020-06-07 07:15:21 +00:00
|
|
|
# metrics
|
|
|
|
libp2p_pubsub_peers.dec()
|
2019-12-06 02:16:18 +00:00
|
|
|
|
|
|
|
proc cleanUpHelper(p: PubSub, peer: PubSubPeer) {.async.} =
|
|
|
|
await p.cleanupLock.acquire()
|
|
|
|
if peer.refs == 0:
|
|
|
|
await p.handleDisconnect(peer)
|
2019-12-10 20:50:35 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
peer.refs.dec() # decrement refcount
|
|
|
|
p.cleanupLock.release()
|
|
|
|
|
2020-01-07 08:04:02 +00:00
|
|
|
proc getPeer(p: PubSub,
|
|
|
|
peerInfo: PeerInfo,
|
|
|
|
proto: string): PubSubPeer =
|
2019-12-06 02:16:18 +00:00
|
|
|
if peerInfo.id in p.peers:
|
|
|
|
result = p.peers[peerInfo.id]
|
|
|
|
return
|
|
|
|
|
|
|
|
# create new pubsub peer
|
|
|
|
let peer = newPubSubPeer(peerInfo, proto)
|
|
|
|
trace "created new pubsub peer", peerId = peer.id
|
2020-06-07 07:15:21 +00:00
|
|
|
# metrics
|
|
|
|
libp2p_pubsub_peers.inc()
|
2019-12-06 02:16:18 +00:00
|
|
|
|
|
|
|
p.peers[peer.id] = peer
|
|
|
|
peer.refs.inc # increment reference cound
|
2020-04-30 13:22:31 +00:00
|
|
|
peer.observers = p.observers
|
2019-12-06 02:16:18 +00:00
|
|
|
result = peer
|
|
|
|
|
2020-05-27 18:33:49 +00:00
|
|
|
proc internalCleanup(p: PubSub, conn: Connection) {.async.} =
|
2020-05-21 17:33:48 +00:00
|
|
|
# handle connection close
|
|
|
|
if conn.closed:
|
|
|
|
return
|
|
|
|
|
|
|
|
var peer = p.getPeer(conn.peerInfo, p.codec)
|
|
|
|
await conn.closeEvent.wait()
|
2020-05-23 16:50:29 +00:00
|
|
|
trace "pubsub conn closed, cleaning up peer", peer = conn.peerInfo.id
|
2020-05-21 17:33:48 +00:00
|
|
|
await p.cleanUpHelper(peer)
|
|
|
|
|
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-05-21 15:01:36 +00:00
|
|
|
try:
|
|
|
|
if isNil(conn.peerInfo):
|
|
|
|
trace "no valid PeerId for peer"
|
|
|
|
await conn.close()
|
|
|
|
return
|
|
|
|
|
|
|
|
proc handler(peer: PubSubPeer, msgs: seq[RPCMsg]) {.async.} =
|
|
|
|
# call pubsub rpc handler
|
|
|
|
await p.rpcHandler(peer, msgs)
|
|
|
|
|
|
|
|
let peer = p.getPeer(conn.peerInfo, proto)
|
|
|
|
let topics = toSeq(p.topics.keys)
|
|
|
|
if topics.len > 0:
|
|
|
|
await p.sendSubs(peer, topics, true)
|
|
|
|
|
|
|
|
peer.handler = handler
|
|
|
|
await peer.handle(conn) # spawn peer read loop
|
|
|
|
trace "pubsub peer handler ended, cleaning up"
|
2020-05-26 23:11:44 +00:00
|
|
|
await p.internalCleanup(conn)
|
2020-05-21 15:01:36 +00:00
|
|
|
except CatchableError as exc:
|
|
|
|
trace "exception ocurred in pubsub handle", exc = exc.msg
|
2020-04-07 15:49:43 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
method subscribeToPeer*(p: PubSub,
|
2019-12-17 05:24:03 +00:00
|
|
|
conn: Connection) {.base, async.} =
|
2019-12-10 20:50:35 +00:00
|
|
|
var peer = p.getPeer(conn.peerInfo, p.codec)
|
|
|
|
trace "setting connection for peer", peerId = conn.peerInfo.id
|
2019-12-06 02:16:18 +00:00
|
|
|
if not peer.isConnected:
|
|
|
|
peer.conn = conn
|
|
|
|
|
2020-05-27 18:33:49 +00:00
|
|
|
asyncCheck p.internalCleanup(conn)
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2019-09-24 16:16:39 +00:00
|
|
|
method unsubscribe*(p: PubSub,
|
2019-12-17 05:24:03 +00:00
|
|
|
topics: seq[TopicPair]) {.base, async.} =
|
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:
|
|
|
|
for i, h in p.topics[t.topic].handler:
|
|
|
|
if h == t.handler:
|
|
|
|
p.topics[t.topic].handler.del(i)
|
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
method unsubscribe*(p: PubSub,
|
|
|
|
topic: string,
|
2019-12-17 05:24:03 +00:00
|
|
|
handler: TopicHandler): Future[void] {.base.} =
|
2020-06-07 07:15:21 +00:00
|
|
|
# metrics
|
|
|
|
libp2p_pubsub_topics.dec()
|
|
|
|
|
2019-09-24 16:16:39 +00:00
|
|
|
## unsubscribe from a ``topic`` string
|
2020-06-07 07:15:21 +00:00
|
|
|
p.unsubscribe(@[(topic, handler)])
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2019-09-24 16:16:39 +00:00
|
|
|
method subscribe*(p: PubSub,
|
|
|
|
topic: string,
|
2019-12-17 05:24:03 +00:00
|
|
|
handler: TopicHandler) {.base, async.} =
|
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
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
for peer in p.peers.values:
|
|
|
|
await p.sendSubs(peer, @[topic], true)
|
|
|
|
|
2020-06-07 07:15:21 +00:00
|
|
|
# metrics
|
|
|
|
libp2p_pubsub_topics.inc()
|
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
method publish*(p: PubSub,
|
|
|
|
topic: string,
|
2019-12-17 05:24:03 +00:00
|
|
|
data: seq[byte]) {.base, async.} =
|
2020-05-27 18:33:49 +00:00
|
|
|
# TODO: Should throw indicating success/failure
|
2019-09-10 02:15:52 +00:00
|
|
|
## publish to a ``topic``
|
2019-10-03 22:22:49 +00:00
|
|
|
if p.triggerSelf and topic in p.topics:
|
|
|
|
for h in p.topics[topic].handler:
|
2019-12-23 18:45:12 +00:00
|
|
|
trace "triggering handler", topicID = topic
|
2020-05-15 03:56:56 +00:00
|
|
|
try:
|
|
|
|
await h(topic, data)
|
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
# TODO these exceptions are ignored since it's likely that if writes are
|
|
|
|
# are failing, the underlying connection is already closed - this needs
|
|
|
|
# more cleanup though
|
|
|
|
debug "Could not write to pubsub connection", msg = exc.msg
|
2019-10-03 22:22:49 +00:00
|
|
|
|
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])
|
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)
|
|
|
|
|
|
|
|
method validate*(p: PubSub, message: Message): Future[bool] {.async, base.} =
|
|
|
|
var pending: seq[Future[bool]]
|
|
|
|
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-04-11 04:08:25 +00:00
|
|
|
let futs = await allFinished(pending)
|
|
|
|
result = futs.allIt(not it.failed and it.read())
|
2020-06-07 07:15:21 +00:00
|
|
|
if result:
|
|
|
|
libp2p_pubsub_validation_success.inc()
|
|
|
|
else:
|
|
|
|
libp2p_pubsub_validation_failure.inc()
|
2019-12-17 05:24:03 +00:00
|
|
|
|
2020-05-06 09:26:08 +00:00
|
|
|
proc newPubSub*(P: typedesc[PubSub],
|
2019-12-06 02:16:18 +00:00
|
|
|
peerInfo: PeerInfo,
|
2020-05-06 09:26:08 +00:00
|
|
|
triggerSelf: bool = false,
|
|
|
|
verifySignature: bool = true,
|
|
|
|
sign: bool = true): P =
|
|
|
|
result = P(peerInfo: peerInfo,
|
|
|
|
triggerSelf: triggerSelf,
|
|
|
|
verifySignature: verifySignature,
|
|
|
|
sign: sign,
|
|
|
|
cleanupLock: newAsyncLock())
|
2019-10-03 22:22:49 +00:00
|
|
|
result.initPubSub()
|
2020-04-30 13:22:31 +00:00
|
|
|
|
|
|
|
proc addObserver*(p: PubSub; observer: PubSubObserver) = p.observers[] &= observer
|
|
|
|
|
|
|
|
proc removeObserver*(p: PubSub; observer: PubSubObserver) =
|
|
|
|
let idx = p.observers[].find(observer)
|
|
|
|
if idx != -1:
|
|
|
|
p.observers[].del(idx)
|