2022-07-01 18:19:57 +00:00
|
|
|
# Nim-LibP2P
|
2023-01-20 14:47:40 +00:00
|
|
|
# Copyright (c) 2023 Status Research & Development GmbH
|
2022-07-01 18:19:57 +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-09-10 02:15:52 +00:00
|
|
|
|
2023-06-07 11:12:49 +00:00
|
|
|
{.push raises: [].}
|
2021-05-21 16:27:01 +00:00
|
|
|
|
2023-04-03 08:56:20 +00:00
|
|
|
import std/[sequtils, strutils, tables, hashes, options, sets, deques]
|
2022-09-22 19:55:59 +00:00
|
|
|
import stew/results
|
2020-06-11 18:09:34 +00:00
|
|
|
import chronos, chronicles, nimcrypto/sha2, metrics
|
2023-09-22 14:45:08 +00:00
|
|
|
import chronos/ratelimit
|
2019-12-10 20:50:35 +00:00
|
|
|
import rpc/[messages, message, protobuf],
|
2020-07-01 06:25:09 +00:00
|
|
|
../../peerid,
|
2019-09-24 16:16:39 +00:00
|
|
|
../../peerinfo,
|
2020-06-19 17:29:43 +00:00
|
|
|
../../stream/connection,
|
2019-09-12 05:46:08 +00:00
|
|
|
../../crypto/crypto,
|
2020-03-23 06:03:36 +00:00
|
|
|
../../protobuf/minprotobuf,
|
|
|
|
../../utility
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2023-07-28 08:58:05 +00:00
|
|
|
export peerid, connection, deques
|
2020-09-24 16:43:20 +00:00
|
|
|
|
2019-09-10 02:15:52 +00:00
|
|
|
logScope:
|
2020-12-01 17:34:27 +00:00
|
|
|
topics = "libp2p pubsubpeer"
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2020-08-04 23:27:59 +00:00
|
|
|
when defined(libp2p_expensive_metrics):
|
|
|
|
declareCounter(libp2p_pubsub_sent_messages, "number of messages sent", labels = ["id", "topic"])
|
|
|
|
declareCounter(libp2p_pubsub_skipped_received_messages, "number of received skipped messages", labels = ["id"])
|
|
|
|
declareCounter(libp2p_pubsub_skipped_sent_messages, "number of sent skipped messages", labels = ["id"])
|
2020-06-12 02:20:58 +00:00
|
|
|
|
2019-09-10 02:15:52 +00:00
|
|
|
type
|
2023-09-22 14:45:08 +00:00
|
|
|
PeerRateLimitError* = object of CatchableError
|
|
|
|
|
2020-04-30 13:22:31 +00:00
|
|
|
PubSubObserver* = ref object
|
2023-06-07 11:12:49 +00:00
|
|
|
onRecv*: proc(peer: PubSubPeer; msgs: var RPCMsg) {.gcsafe, raises: [].}
|
|
|
|
onSend*: proc(peer: PubSubPeer; msgs: var RPCMsg) {.gcsafe, raises: [].}
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2020-09-22 07:05:53 +00:00
|
|
|
PubSubPeerEventKind* {.pure.} = enum
|
|
|
|
Connected
|
|
|
|
Disconnected
|
|
|
|
|
2022-07-27 17:14:05 +00:00
|
|
|
PubSubPeerEvent* = object
|
2020-09-22 07:05:53 +00:00
|
|
|
kind*: PubSubPeerEventKind
|
|
|
|
|
2023-06-07 11:12:49 +00:00
|
|
|
GetConn* = proc(): Future[Connection] {.gcsafe, raises: [].}
|
|
|
|
DropConn* = proc(peer: PubSubPeer) {.gcsafe, raises: [].} # have to pass peer as it's unknown during init
|
|
|
|
OnEvent* = proc(peer: PubSubPeer, event: PubSubPeerEvent) {.gcsafe, raises: [].}
|
2020-09-01 07:33:03 +00:00
|
|
|
|
2020-04-30 13:22:31 +00:00
|
|
|
PubSubPeer* = ref object of RootObj
|
2020-09-01 07:33:03 +00:00
|
|
|
getConn*: GetConn # callback to establish a new send connection
|
2020-09-22 07:05:53 +00:00
|
|
|
onEvent*: OnEvent # Connectivity updates for peer
|
2020-08-12 00:05:49 +00:00
|
|
|
codec*: string # the protocol that this peer joined from
|
2020-09-22 07:05:53 +00:00
|
|
|
sendConn*: Connection # cached send connection
|
2023-01-10 12:33:14 +00:00
|
|
|
connectedFut: Future[void]
|
2021-02-27 14:49:56 +00:00
|
|
|
address*: Option[MultiAddress]
|
2021-12-16 10:05:20 +00:00
|
|
|
peerId*: PeerId
|
2020-04-30 13:22:31 +00:00
|
|
|
handler*: RPCHandler
|
|
|
|
observers*: ref seq[PubSubObserver] # ref as in smart_ptr
|
|
|
|
|
2020-09-21 09:16:29 +00:00
|
|
|
score*: float64
|
2023-04-03 08:56:20 +00:00
|
|
|
sentIHaves*: Deque[HashSet[MessageId]]
|
2023-07-28 08:58:05 +00:00
|
|
|
heDontWants*: Deque[HashSet[MessageId]]
|
2020-09-21 09:16:29 +00:00
|
|
|
iHaveBudget*: int
|
2023-06-21 08:40:10 +00:00
|
|
|
pingBudget*: int
|
2021-10-25 10:58:38 +00:00
|
|
|
maxMessageSize: int
|
2020-09-21 09:16:29 +00:00
|
|
|
appScore*: float64 # application specific score
|
|
|
|
behaviourPenalty*: float64 # the eventual penalty score
|
2023-09-22 14:45:08 +00:00
|
|
|
overheadRateLimitOpt*: Opt[TokenBucket]
|
2021-01-15 04:48:03 +00:00
|
|
|
|
2023-09-22 14:45:08 +00:00
|
|
|
RPCHandler* = proc(peer: PubSubPeer, data: seq[byte]): Future[void]
|
2023-06-07 11:12:49 +00:00
|
|
|
{.gcsafe, raises: [].}
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2023-04-03 09:05:01 +00:00
|
|
|
when defined(libp2p_agents_metrics):
|
|
|
|
func shortAgent*(p: PubSubPeer): string =
|
|
|
|
if p.sendConn.isNil or p.sendConn.getWrapped().isNil:
|
|
|
|
"unknown"
|
|
|
|
else:
|
|
|
|
#TODO the sendConn is setup before identify,
|
|
|
|
#so we have to read the parents short agent..
|
|
|
|
p.sendConn.getWrapped().shortAgent
|
|
|
|
|
2020-09-22 07:05:53 +00:00
|
|
|
func hash*(p: PubSubPeer): Hash =
|
2021-02-26 10:19:15 +00:00
|
|
|
p.peerId.hash
|
|
|
|
|
|
|
|
func `==`*(a, b: PubSubPeer): bool =
|
|
|
|
a.peerId == b.peerId
|
2020-07-13 13:32:38 +00:00
|
|
|
|
2020-09-06 08:31:47 +00:00
|
|
|
func shortLog*(p: PubSubPeer): string =
|
|
|
|
if p.isNil: "PubSubPeer(nil)"
|
|
|
|
else: shortLog(p.peerId)
|
|
|
|
chronicles.formatIt(PubSubPeer): shortLog(it)
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-06-29 15:15:31 +00:00
|
|
|
proc connected*(p: PubSubPeer): bool =
|
2020-08-12 00:05:49 +00:00
|
|
|
not p.sendConn.isNil and not
|
|
|
|
(p.sendConn.closed or p.sendConn.atEof)
|
2020-07-08 00:33:05 +00:00
|
|
|
|
2021-04-18 08:08:33 +00:00
|
|
|
proc hasObservers*(p: PubSubPeer): bool =
|
2020-09-24 16:43:20 +00:00
|
|
|
p.observers != nil and anyIt(p.observers[], it != nil)
|
|
|
|
|
2021-02-06 00:13:04 +00:00
|
|
|
func outbound*(p: PubSubPeer): bool =
|
2021-03-02 23:23:40 +00:00
|
|
|
# gossipsub 1.1 spec requires us to know if the transport is outgoing
|
|
|
|
# in order to give priotity to connections we make
|
|
|
|
# https://github.com/libp2p/specs/blob/master/pubsub/gossipsub/gossipsub-v1.1.md#outbound-mesh-quotas
|
|
|
|
# This behaviour is presrcibed to counter sybil attacks and ensures that a coordinated inbound attack can never fully take over the mesh
|
|
|
|
if not p.sendConn.isNil and p.sendConn.transportDir == Direction.Out:
|
2021-02-06 00:13:04 +00:00
|
|
|
true
|
|
|
|
else:
|
|
|
|
false
|
|
|
|
|
2023-09-22 14:45:08 +00:00
|
|
|
proc recvObservers*(p: PubSubPeer, msg: var RPCMsg) =
|
2020-05-29 16:46:27 +00:00
|
|
|
# trigger hooks
|
|
|
|
if not(isNil(p.observers)) and p.observers[].len > 0:
|
|
|
|
for obs in p.observers[]:
|
2020-06-24 15:08:44 +00:00
|
|
|
if not(isNil(obs)): # TODO: should never be nil, but...
|
|
|
|
obs.onRecv(p, msg)
|
2020-05-29 16:46:27 +00:00
|
|
|
|
|
|
|
proc sendObservers(p: PubSubPeer, msg: var RPCMsg) =
|
|
|
|
# trigger hooks
|
|
|
|
if not(isNil(p.observers)) and p.observers[].len > 0:
|
|
|
|
for obs in p.observers[]:
|
2020-06-24 15:08:44 +00:00
|
|
|
if not(isNil(obs)): # TODO: should never be nil, but...
|
|
|
|
obs.onSend(p, msg)
|
2020-05-29 16:46:27 +00:00
|
|
|
|
2019-12-17 05:24:03 +00:00
|
|
|
proc handle*(p: PubSubPeer, conn: Connection) {.async.} =
|
2020-09-06 08:31:47 +00:00
|
|
|
debug "starting pubsub read loop",
|
|
|
|
conn, peer = p, closed = conn.closed
|
2019-09-10 02:15:52 +00:00
|
|
|
try:
|
2020-05-25 14:33:24 +00:00
|
|
|
try:
|
2020-08-03 05:20:11 +00:00
|
|
|
while not conn.atEof:
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "waiting for data", conn, peer = p, closed = conn.closed
|
|
|
|
|
2021-10-25 10:58:38 +00:00
|
|
|
var data = await conn.readLp(p.maxMessageSize)
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "read data from peer",
|
|
|
|
conn, peer = p, closed = conn.closed,
|
|
|
|
data = data.shortLog
|
2020-05-25 14:33:24 +00:00
|
|
|
|
2023-09-22 14:45:08 +00:00
|
|
|
await p.handler(p, data)
|
|
|
|
data = newSeq[byte]() # Release memory
|
|
|
|
except PeerRateLimitError as exc:
|
|
|
|
debug "Peer rate limit exceeded, exiting read while", conn, peer = p, error = exc.msg
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Exception occurred in PubSubPeer.handle",
|
|
|
|
conn, peer = p, closed = conn.closed, exc = exc.msg
|
2020-05-25 14:33:24 +00:00
|
|
|
finally:
|
|
|
|
await conn.close()
|
2020-09-04 16:30:45 +00:00
|
|
|
except CancelledError:
|
|
|
|
# This is top-level procedure which will work as separate task, so it
|
2020-11-23 21:02:23 +00:00
|
|
|
# do not need to propagate CancelledError.
|
2020-09-04 16:30:45 +00:00
|
|
|
trace "Unexpected cancellation in PubSubPeer.handle"
|
2019-12-06 02:16:18 +00:00
|
|
|
except CatchableError as exc:
|
2020-09-06 08:31:47 +00:00
|
|
|
trace "Exception occurred in PubSubPeer.handle",
|
|
|
|
conn, peer = p, closed = conn.closed, exc = exc.msg
|
2020-09-01 07:33:03 +00:00
|
|
|
finally:
|
2020-09-06 08:31:47 +00:00
|
|
|
debug "exiting pubsub read loop",
|
|
|
|
conn, peer = p, closed = conn.closed
|
2019-09-10 02:15:52 +00:00
|
|
|
|
2020-09-22 07:05:53 +00:00
|
|
|
proc connectOnce(p: PubSubPeer): Future[void] {.async.} =
|
2020-08-17 19:39:39 +00:00
|
|
|
try:
|
2023-01-10 12:33:14 +00:00
|
|
|
if p.connectedFut.finished:
|
|
|
|
p.connectedFut = newFuture[void]()
|
2023-06-14 15:23:39 +00:00
|
|
|
let newConn = await p.getConn().wait(5.seconds)
|
2020-08-17 19:39:39 +00:00
|
|
|
if newConn.isNil:
|
2021-06-02 13:39:10 +00:00
|
|
|
raise (ref LPError)(msg: "Cannot establish send connection")
|
2020-08-17 19:39:39 +00:00
|
|
|
|
2020-09-22 07:05:53 +00:00
|
|
|
# When the send channel goes up, subscriptions need to be sent to the
|
|
|
|
# remote peer - if we had multiple channels up and one goes down, all
|
|
|
|
# stop working so we make an effort to only keep a single channel alive
|
2020-09-01 07:33:03 +00:00
|
|
|
|
2020-09-22 07:05:53 +00:00
|
|
|
trace "Get new send connection", p, newConn
|
2023-03-08 11:30:19 +00:00
|
|
|
|
|
|
|
# Careful to race conditions here.
|
|
|
|
# Topic subscription relies on either connectedFut
|
|
|
|
# to be completed, or onEvent to be called later
|
2023-01-10 12:33:14 +00:00
|
|
|
p.connectedFut.complete()
|
2020-08-17 19:39:39 +00:00
|
|
|
p.sendConn = newConn
|
2022-09-22 19:55:59 +00:00
|
|
|
p.address = if p.sendConn.observedAddr.isSome: some(p.sendConn.observedAddr.get) else: none(MultiAddress)
|
2020-09-22 07:05:53 +00:00
|
|
|
|
|
|
|
if p.onEvent != nil:
|
2022-07-27 17:14:05 +00:00
|
|
|
p.onEvent(p, PubSubPeerEvent(kind: PubSubPeerEventKind.Connected))
|
2020-09-22 07:05:53 +00:00
|
|
|
|
|
|
|
await handle(p, newConn)
|
2020-08-17 19:39:39 +00:00
|
|
|
finally:
|
2020-09-22 07:05:53 +00:00
|
|
|
if p.sendConn != nil:
|
|
|
|
trace "Removing send connection", p, conn = p.sendConn
|
|
|
|
await p.sendConn.close()
|
2021-03-02 23:23:40 +00:00
|
|
|
p.sendConn = nil
|
remove send lock (#334)
* remove send lock
When mplex receives data it will block until a reader has processed the
data. Thus, when a large message is received, such as a gossipsub
subscription table, all of mplex will be blocked until all reading is
finished.
However, if at the same time a `dial` to establish a gossipsub send
connection is ongoing, that `dial` will be blocked because mplex is no
longer reading data - specifically, it might indeed be the connection
that's processing the previous data that is waiting for a send
connection.
There are other problems with the current code:
* If an exception is raised, it is not necessarily raised for the same
connection as `p.sendConn`, so resetting `p.sendConn` in the exception
handling is wrong
* `p.isConnected` is checked before taking the lock - thus, if it
returns false, a new dial will be started. If a new task enters `send`
before dial is finished, it will also determine `p.isConnected` is
false, then get stuck on the lock - when the previous task finishes and
releases the lock, the new task will _also_ dial and thus reset
`p.sendConn` causing a leak.
* prefer existing connection
simplifies flow
2020-08-17 10:38:27 +00:00
|
|
|
|
2023-06-14 15:23:39 +00:00
|
|
|
if not p.connectedFut.finished:
|
|
|
|
p.connectedFut.complete()
|
|
|
|
|
2021-03-02 23:23:40 +00:00
|
|
|
try:
|
|
|
|
if p.onEvent != nil:
|
2022-07-27 17:14:05 +00:00
|
|
|
p.onEvent(p, PubSubPeerEvent(kind: PubSubPeerEventKind.Disconnected))
|
2021-10-25 08:26:32 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
2021-03-02 23:23:40 +00:00
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Errors during diconnection events", error = exc.msg
|
2021-02-28 04:53:17 +00:00
|
|
|
|
2021-03-02 23:23:40 +00:00
|
|
|
# don't cleanup p.address else we leak some gossip stat table
|
2020-09-22 07:05:53 +00:00
|
|
|
|
|
|
|
proc connectImpl(p: PubSubPeer) {.async.} =
|
2020-09-01 07:33:03 +00:00
|
|
|
try:
|
2020-09-22 07:05:53 +00:00
|
|
|
# Keep trying to establish a connection while it's possible to do so - the
|
|
|
|
# send connection might get disconnected due to a timeout or an unrelated
|
|
|
|
# issue so we try to get a new on
|
|
|
|
while true:
|
|
|
|
await connectOnce(p)
|
2021-03-09 12:22:52 +00:00
|
|
|
except CatchableError as exc: # never cancelled
|
2020-09-22 07:05:53 +00:00
|
|
|
debug "Could not establish send connection", msg = exc.msg
|
2020-09-01 07:33:03 +00:00
|
|
|
|
|
|
|
proc connect*(p: PubSubPeer) =
|
2023-01-10 12:33:14 +00:00
|
|
|
if p.connected:
|
|
|
|
return
|
2020-07-16 10:06:57 +00:00
|
|
|
|
2023-01-10 12:33:14 +00:00
|
|
|
asyncSpawn connectImpl(p)
|
2020-09-01 07:33:03 +00:00
|
|
|
|
2023-03-08 11:30:19 +00:00
|
|
|
proc hasSendConn*(p: PubSubPeer): bool =
|
|
|
|
p.sendConn != nil
|
|
|
|
|
2020-11-23 21:02:23 +00:00
|
|
|
template sendMetrics(msg: RPCMsg): untyped =
|
|
|
|
when defined(libp2p_expensive_metrics):
|
|
|
|
for x in msg.messages:
|
2024-01-30 15:55:55 +00:00
|
|
|
for t in x.topicIds:
|
2020-11-23 21:02:23 +00:00
|
|
|
# metrics
|
|
|
|
libp2p_pubsub_sent_messages.inc(labelValues = [$p.peerId, t])
|
|
|
|
|
2024-02-19 12:47:37 +00:00
|
|
|
proc sendEncoded*(p: PubSubPeer, msg: seq[byte]) {.async.} =
|
|
|
|
doAssert(not isNil(p), "pubsubpeer nil!")
|
|
|
|
|
|
|
|
if msg.len <= 0:
|
|
|
|
debug "empty message, skipping", p, msg = shortLog(msg)
|
|
|
|
return
|
|
|
|
|
|
|
|
if msg.len > p.maxMessageSize:
|
|
|
|
info "trying to send a msg too big for pubsub", maxSize=p.maxMessageSize, msgSize=msg.len
|
|
|
|
return
|
2021-10-25 10:58:38 +00:00
|
|
|
|
2023-01-10 12:33:14 +00:00
|
|
|
if p.sendConn == nil:
|
2023-06-14 15:23:39 +00:00
|
|
|
# Wait for a send conn to be setup. `connectOnce` will
|
|
|
|
# complete this even if the sendConn setup failed
|
|
|
|
await p.connectedFut
|
2023-01-10 12:33:14 +00:00
|
|
|
|
|
|
|
var conn = p.sendConn
|
2020-09-24 16:43:20 +00:00
|
|
|
if conn == nil or conn.closed():
|
2023-06-14 15:23:39 +00:00
|
|
|
debug "No send connection", p, msg = shortLog(msg)
|
2020-09-24 16:43:20 +00:00
|
|
|
return
|
|
|
|
|
2023-01-10 12:33:14 +00:00
|
|
|
trace "sending encoded msgs to peer", conn, encoded = shortLog(msg)
|
|
|
|
|
|
|
|
try:
|
|
|
|
await conn.writeLp(msg)
|
|
|
|
trace "sent pubsub message to remote", conn
|
|
|
|
except CatchableError as exc: # never cancelled
|
|
|
|
# Because we detach the send call from the currently executing task using
|
|
|
|
# asyncSpawn, no exceptions may leak out of it
|
|
|
|
trace "Unable to send to remote", conn, msg = exc.msg
|
|
|
|
# Next time sendConn is used, it will be have its close flag set and thus
|
|
|
|
# will be recycled
|
|
|
|
|
|
|
|
await conn.close() # This will clean up the send connection
|
2021-04-18 08:08:33 +00:00
|
|
|
|
2023-10-02 09:39:28 +00:00
|
|
|
iterator splitRPCMsg(peer: PubSubPeer, rpcMsg: RPCMsg, maxSize: int, anonymize: bool): seq[byte] =
|
|
|
|
## This iterator takes an `RPCMsg` and sequentially repackages its Messages into new `RPCMsg` instances.
|
|
|
|
## Each new `RPCMsg` accumulates Messages until reaching the specified `maxSize`. If a single Message
|
|
|
|
## exceeds the `maxSize` when trying to fit into an empty `RPCMsg`, the latter is skipped as too large to send.
|
|
|
|
## Every constructed `RPCMsg` is then encoded, optionally anonymized, and yielded as a sequence of bytes.
|
|
|
|
|
|
|
|
var currentRPCMsg = rpcMsg
|
|
|
|
currentRPCMsg.messages = newSeq[Message]()
|
|
|
|
|
|
|
|
var currentSize = byteSize(currentRPCMsg)
|
|
|
|
|
|
|
|
for msg in rpcMsg.messages:
|
|
|
|
let msgSize = byteSize(msg)
|
|
|
|
|
|
|
|
# Check if adding the next message will exceed maxSize
|
|
|
|
if float(currentSize + msgSize) * 1.1 > float(maxSize): # Guessing 10% protobuf overhead
|
|
|
|
if currentRPCMsg.messages.len == 0:
|
|
|
|
trace "message too big to sent", peer, rpcMsg = shortLog(currentRPCMsg)
|
|
|
|
continue # Skip this message
|
|
|
|
|
|
|
|
trace "sending msg to peer", peer, rpcMsg = shortLog(currentRPCMsg)
|
|
|
|
yield encodeRpcMsg(currentRPCMsg, anonymize)
|
|
|
|
currentRPCMsg = RPCMsg()
|
|
|
|
currentSize = 0
|
2020-09-24 16:43:20 +00:00
|
|
|
|
2023-10-02 09:39:28 +00:00
|
|
|
currentRPCMsg.messages.add(msg)
|
|
|
|
currentSize += msgSize
|
|
|
|
|
|
|
|
# Check if there is a non-empty currentRPCMsg left to be added
|
|
|
|
if currentSize > 0 and currentRPCMsg.messages.len > 0:
|
|
|
|
trace "sending msg to peer", peer, rpcMsg = shortLog(currentRPCMsg)
|
|
|
|
yield encodeRpcMsg(currentRPCMsg, anonymize)
|
|
|
|
else:
|
|
|
|
trace "message too big to sent", peer, rpcMsg = shortLog(currentRPCMsg)
|
|
|
|
|
2024-02-19 12:47:37 +00:00
|
|
|
proc send*(p: PubSubPeer, msg: RPCMsg, anonymize: bool) {.raises: [].} =
|
2020-09-25 16:39:34 +00:00
|
|
|
# When sending messages, we take care to re-encode them with the right
|
|
|
|
# anonymization flag to ensure that we're not penalized for sending invalid
|
|
|
|
# or malicious data on the wire - in particular, re-encoding protects against
|
|
|
|
# some forms of valid but redundantly encoded protobufs with unknown or
|
|
|
|
# duplicated fields
|
2020-09-24 16:43:20 +00:00
|
|
|
let encoded = if p.hasObservers():
|
2020-11-23 21:02:23 +00:00
|
|
|
var mm = msg
|
2020-09-24 16:43:20 +00:00
|
|
|
# trigger send hooks
|
|
|
|
p.sendObservers(mm)
|
2020-11-23 21:02:23 +00:00
|
|
|
sendMetrics(mm)
|
2020-09-25 16:39:34 +00:00
|
|
|
encodeRpcMsg(mm, anonymize)
|
2020-09-24 16:43:20 +00:00
|
|
|
else:
|
|
|
|
# If there are no send hooks, we redundantly re-encode the message to
|
|
|
|
# protobuf for every peer - this could easily be improved!
|
2020-11-23 21:02:23 +00:00
|
|
|
sendMetrics(msg)
|
2020-09-25 16:39:34 +00:00
|
|
|
encodeRpcMsg(msg, anonymize)
|
2020-09-24 16:43:20 +00:00
|
|
|
|
2023-10-02 09:39:28 +00:00
|
|
|
if encoded.len > p.maxMessageSize and msg.messages.len > 1:
|
|
|
|
for encodedSplitMsg in splitRPCMsg(p, msg, p.maxMessageSize, anonymize):
|
2024-02-19 12:47:37 +00:00
|
|
|
asyncSpawn p.sendEncoded(encodedSplitMsg)
|
2023-10-02 09:39:28 +00:00
|
|
|
else:
|
|
|
|
# If the message size is within limits, send it as is
|
|
|
|
trace "sending msg to peer", peer = p, rpcMsg = shortLog(msg)
|
2024-02-19 12:47:37 +00:00
|
|
|
asyncSpawn p.sendEncoded(encoded)
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2023-04-03 08:56:20 +00:00
|
|
|
proc canAskIWant*(p: PubSubPeer, msgId: MessageId): bool =
|
|
|
|
for sentIHave in p.sentIHaves.mitems():
|
|
|
|
if msgId in sentIHave:
|
|
|
|
sentIHave.excl(msgId)
|
|
|
|
return true
|
|
|
|
return false
|
|
|
|
|
2021-06-07 07:32:08 +00:00
|
|
|
proc new*(
|
|
|
|
T: typedesc[PubSubPeer],
|
2021-12-16 10:05:20 +00:00
|
|
|
peerId: PeerId,
|
2021-06-07 07:32:08 +00:00
|
|
|
getConn: GetConn,
|
|
|
|
onEvent: OnEvent,
|
2021-10-25 10:58:38 +00:00
|
|
|
codec: string,
|
2023-09-22 14:45:08 +00:00
|
|
|
maxMessageSize: int,
|
|
|
|
overheadRateLimitOpt: Opt[TokenBucket] = Opt.none(TokenBucket)): T =
|
2021-06-07 07:32:08 +00:00
|
|
|
|
2023-04-03 08:56:20 +00:00
|
|
|
result = T(
|
2020-09-22 07:05:53 +00:00
|
|
|
getConn: getConn,
|
|
|
|
onEvent: onEvent,
|
|
|
|
codec: codec,
|
|
|
|
peerId: peerId,
|
2023-01-10 12:33:14 +00:00
|
|
|
connectedFut: newFuture[void](),
|
2023-09-22 14:45:08 +00:00
|
|
|
maxMessageSize: maxMessageSize,
|
2024-02-19 12:47:37 +00:00
|
|
|
overheadRateLimitOpt: overheadRateLimitOpt
|
2020-09-22 07:05:53 +00:00
|
|
|
)
|
2023-04-03 08:56:20 +00:00
|
|
|
result.sentIHaves.addFirst(default(HashSet[MessageId]))
|
2023-07-28 08:58:05 +00:00
|
|
|
result.heDontWants.addFirst(default(HashSet[MessageId]))
|
2024-02-19 12:47:37 +00:00
|
|
|
|
|
|
|
proc getAgent*(peer: PubSubPeer): string =
|
|
|
|
return
|
|
|
|
when defined(libp2p_agents_metrics):
|
|
|
|
if peer.shortAgent.len > 0:
|
|
|
|
peer.shortAgent
|
|
|
|
else:
|
|
|
|
"unknown"
|
|
|
|
else:
|
|
|
|
"unknown"
|