2019-08-27 21:46:12 +00:00
|
|
|
## Nim-LibP2P
|
2019-09-24 17:48:23 +00:00
|
|
|
## Copyright (c) 2019 Status Research & Development GmbH
|
2019-08-27 21:46:12 +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.
|
|
|
|
|
2020-02-21 01:14:39 +00:00
|
|
|
import tables, sequtils, options, strformat, sets
|
2020-06-11 14:45:59 +00:00
|
|
|
import chronos, chronicles, metrics
|
2020-06-19 17:29:43 +00:00
|
|
|
import stream/connection,
|
|
|
|
stream/chronosstream,
|
2019-09-11 19:03:30 +00:00
|
|
|
transports/transport,
|
|
|
|
multistream,
|
2020-06-17 04:14:02 +00:00
|
|
|
multiaddress,
|
2019-09-06 07:13:47 +00:00
|
|
|
protocols/protocol,
|
2019-09-14 13:55:52 +00:00
|
|
|
protocols/secure/secure,
|
|
|
|
protocols/secure/plaintext, # for plain text
|
2019-09-11 19:03:30 +00:00
|
|
|
peerinfo,
|
|
|
|
protocols/identify,
|
|
|
|
protocols/pubsub/pubsub,
|
2019-09-06 07:13:47 +00:00
|
|
|
muxers/muxer,
|
2020-04-11 04:08:25 +00:00
|
|
|
errors,
|
2019-09-09 17:33:32 +00:00
|
|
|
peer
|
2019-08-28 19:12:15 +00:00
|
|
|
|
2019-09-12 02:10:38 +00:00
|
|
|
logScope:
|
2020-06-10 08:48:01 +00:00
|
|
|
topics = "switch"
|
2019-09-12 02:10:38 +00:00
|
|
|
|
2019-12-04 04:44:54 +00:00
|
|
|
#TODO: General note - use a finite state machine to manage the different
|
2019-12-08 21:06:58 +00:00
|
|
|
# steps of connections establishing and upgrading. This makes everything
|
|
|
|
# more robust and less prone to ordering attacks - i.e. muxing can come if
|
|
|
|
# and only if the channel has been secured (i.e. if a secure manager has been
|
2019-12-04 04:44:54 +00:00
|
|
|
# previously provided)
|
|
|
|
|
2020-06-16 20:43:45 +00:00
|
|
|
declareGauge(libp2p_peers, "total connected peers")
|
2020-06-11 14:45:59 +00:00
|
|
|
declareCounter(libp2p_dialed_peers, "dialed peers")
|
|
|
|
declareCounter(libp2p_failed_dials, "failed dials")
|
|
|
|
declareCounter(libp2p_failed_upgrade, "peers failed upgrade")
|
|
|
|
|
2019-08-28 19:12:15 +00:00
|
|
|
type
|
2019-09-11 19:03:30 +00:00
|
|
|
NoPubSubException = object of CatchableError
|
|
|
|
|
2020-06-23 05:23:00 +00:00
|
|
|
Maintainer = object
|
|
|
|
loopFut: Future[void]
|
|
|
|
sleepFut: Future[void]
|
|
|
|
|
2019-08-28 19:12:15 +00:00
|
|
|
Switch* = ref object of RootObj
|
2019-08-30 05:17:07 +00:00
|
|
|
peerInfo*: PeerInfo
|
2019-09-13 18:41:48 +00:00
|
|
|
connections*: Table[string, Connection]
|
|
|
|
muxed*: Table[string, Muxer]
|
2019-08-30 05:17:07 +00:00
|
|
|
transports*: seq[Transport]
|
|
|
|
protocols*: seq[LPProtocol]
|
2019-09-04 22:00:39 +00:00
|
|
|
muxers*: Table[string, MuxerProvider]
|
2020-02-04 16:16:21 +00:00
|
|
|
ms*: MultistreamSelect
|
2019-09-04 01:50:17 +00:00
|
|
|
identity*: Identify
|
2019-09-06 07:13:47 +00:00
|
|
|
streamHandler*: StreamHandler
|
2020-06-01 17:49:25 +00:00
|
|
|
secureManagers*: seq[Secure]
|
2019-09-11 19:03:30 +00:00
|
|
|
pubSub*: Option[PubSub]
|
2020-02-21 01:14:39 +00:00
|
|
|
dialedPubSubPeers: HashSet[string]
|
2020-06-23 05:23:00 +00:00
|
|
|
running: bool
|
|
|
|
maintainFuts: Table[string, Maintainer]
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2020-05-23 17:12:28 +00:00
|
|
|
proc newNoPubSubException(): ref CatchableError {.inline.} =
|
2019-09-11 19:03:30 +00:00
|
|
|
result = newException(NoPubSubException, "no pubsub provided!")
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc secure(s: Switch, conn: Connection): Future[Connection] {.async, gcsafe.} =
|
2020-06-01 17:49:25 +00:00
|
|
|
if s.secureManagers.len <= 0:
|
2019-09-09 23:17:45 +00:00
|
|
|
raise newException(CatchableError, "No secure managers registered!")
|
|
|
|
|
2020-06-01 17:49:25 +00:00
|
|
|
let manager = await s.ms.select(conn, s.secureManagers.mapIt(it.codec))
|
2020-06-22 21:38:48 +00:00
|
|
|
if manager.len == 0:
|
2019-09-06 07:13:47 +00:00
|
|
|
raise newException(CatchableError, "Unable to negotiate a secure channel!")
|
2019-09-09 23:17:45 +00:00
|
|
|
|
2020-06-20 10:56:55 +00:00
|
|
|
trace "securing connection", codec=manager
|
|
|
|
let secureProtocol = s.secureManagers.filterIt(it.codec == manager)
|
|
|
|
# ms.select should deal with the correctness of this
|
|
|
|
# let's avoid duplicating checks but detect if it fails to do it properly
|
2020-06-21 09:14:19 +00:00
|
|
|
doAssert(secureProtocol.len > 0)
|
2020-06-20 10:56:55 +00:00
|
|
|
result = await secureProtocol[0].secure(conn, true)
|
2019-08-31 17:58:49 +00:00
|
|
|
|
2019-09-28 19:54:32 +00:00
|
|
|
proc identify(s: Switch, conn: Connection): Future[PeerInfo] {.async, gcsafe.} =
|
2019-09-04 01:50:17 +00:00
|
|
|
## identify the connection
|
2019-09-28 19:54:32 +00:00
|
|
|
|
2019-12-10 20:50:35 +00:00
|
|
|
if not isNil(conn.peerInfo):
|
|
|
|
result = conn.peerInfo
|
2019-12-07 16:36:39 +00:00
|
|
|
|
2019-09-06 07:13:47 +00:00
|
|
|
try:
|
|
|
|
if (await s.ms.select(conn, s.identity.codec)):
|
|
|
|
let info = await s.identity.identify(conn, conn.peerInfo)
|
|
|
|
|
2019-12-10 20:50:35 +00:00
|
|
|
if info.pubKey.isNone and isNil(result):
|
|
|
|
raise newException(CatchableError,
|
|
|
|
"no public key provided and no existing peer identity found")
|
|
|
|
|
2019-09-28 19:54:32 +00:00
|
|
|
if info.pubKey.isSome:
|
2019-12-07 16:36:39 +00:00
|
|
|
result = PeerInfo.init(info.pubKey.get())
|
2019-12-04 04:44:54 +00:00
|
|
|
trace "identify: identified remote peer", peer = result.id
|
|
|
|
|
2019-09-28 19:54:32 +00:00
|
|
|
if info.addrs.len > 0:
|
|
|
|
result.addrs = info.addrs
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-06-09 18:42:52 +00:00
|
|
|
if info.agentVersion.isSome:
|
|
|
|
result.agentVersion = info.agentVersion.get()
|
|
|
|
|
|
|
|
if info.protoVersion.isSome:
|
|
|
|
result.protoVersion = info.protoVersion.get()
|
|
|
|
|
2019-09-28 19:54:32 +00:00
|
|
|
if info.protos.len > 0:
|
|
|
|
result.protocols = info.protos
|
2020-06-11 14:45:59 +00:00
|
|
|
|
2020-06-19 17:29:43 +00:00
|
|
|
trace "identify", info = shortLog(result)
|
2019-09-06 07:13:47 +00:00
|
|
|
except IdentityInvalidMsgError as exc:
|
2019-09-23 21:51:28 +00:00
|
|
|
error "identify: invalid message", msg = exc.msg
|
2019-09-06 07:13:47 +00:00
|
|
|
except IdentityNoMatchError as exc:
|
2019-09-23 21:51:28 +00:00
|
|
|
error "identify: peer's public keys don't match ", msg = exc.msg
|
2019-09-06 07:13:47 +00:00
|
|
|
|
2019-09-08 07:43:33 +00:00
|
|
|
proc mux(s: Switch, conn: Connection): Future[void] {.async, gcsafe.} =
|
2019-09-04 01:50:17 +00:00
|
|
|
## mux incoming connection
|
2019-09-28 19:54:32 +00:00
|
|
|
|
2020-06-21 09:14:19 +00:00
|
|
|
trace "muxing connection", peer = $conn
|
2019-09-04 22:00:39 +00:00
|
|
|
let muxers = toSeq(s.muxers.keys)
|
2019-09-13 20:04:46 +00:00
|
|
|
if muxers.len == 0:
|
2019-09-23 21:51:28 +00:00
|
|
|
warn "no muxers registered, skipping upgrade flow"
|
2019-09-13 20:04:46 +00:00
|
|
|
return
|
|
|
|
|
2019-09-04 22:00:39 +00:00
|
|
|
let muxerName = await s.ms.select(conn, muxers)
|
2019-09-06 07:13:47 +00:00
|
|
|
if muxerName.len == 0 or muxerName == "na":
|
2020-06-21 09:14:19 +00:00
|
|
|
debug "no muxer available, early exit", peer = $conn
|
2019-09-04 22:00:39 +00:00
|
|
|
return
|
|
|
|
|
2019-09-14 15:55:58 +00:00
|
|
|
# create new muxer for connection
|
2019-09-04 22:00:39 +00:00
|
|
|
let muxer = s.muxers[muxerName].newMuxer(conn)
|
2020-06-20 10:56:55 +00:00
|
|
|
|
2020-06-21 09:14:19 +00:00
|
|
|
trace "found a muxer", name=muxerName, peer = $conn
|
2020-06-20 10:56:55 +00:00
|
|
|
|
2019-09-04 22:00:39 +00:00
|
|
|
# install stream handler
|
2019-09-06 07:13:47 +00:00
|
|
|
muxer.streamHandler = s.streamHandler
|
2019-09-04 22:00:39 +00:00
|
|
|
|
2019-09-14 15:55:58 +00:00
|
|
|
# new stream for identify
|
2019-12-04 04:44:54 +00:00
|
|
|
var stream = await muxer.newStream()
|
2020-06-08 23:42:27 +00:00
|
|
|
# call muxer handler, this should
|
|
|
|
# not end until muxer ends
|
2019-09-08 07:43:33 +00:00
|
|
|
let handlerFut = muxer.handle()
|
|
|
|
|
|
|
|
# add muxer handler cleanup proc
|
2019-12-08 21:06:58 +00:00
|
|
|
handlerFut.addCallback do (udata: pointer = nil):
|
|
|
|
trace "muxer handler completed for peer",
|
2019-12-10 20:50:35 +00:00
|
|
|
peer = conn.peerInfo.id
|
2019-09-14 15:55:58 +00:00
|
|
|
|
2020-06-08 23:42:27 +00:00
|
|
|
try:
|
|
|
|
# do identify first, so that we have a
|
|
|
|
# PeerInfo in case we didn't before
|
|
|
|
conn.peerInfo = await s.identify(stream)
|
|
|
|
finally:
|
|
|
|
await stream.close() # close identify stream
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2019-09-05 15:19:39 +00:00
|
|
|
# store it in muxed connections if we have a peer for it
|
2019-12-10 20:50:35 +00:00
|
|
|
if not isNil(conn.peerInfo):
|
|
|
|
trace "adding muxer for peer", peer = conn.peerInfo.id
|
|
|
|
s.muxed[conn.peerInfo.id] = muxer
|
2019-09-04 22:00:39 +00:00
|
|
|
|
2019-09-28 19:54:32 +00:00
|
|
|
proc cleanupConn(s: Switch, conn: Connection) {.async, gcsafe.} =
|
2020-05-23 17:12:28 +00:00
|
|
|
try:
|
|
|
|
if not isNil(conn.peerInfo):
|
|
|
|
let id = conn.peerInfo.id
|
|
|
|
trace "cleaning up connection for peer", peerId = id
|
|
|
|
if id in s.muxed:
|
|
|
|
await s.muxed[id].close()
|
|
|
|
s.muxed.del(id)
|
|
|
|
|
|
|
|
if id in s.connections:
|
|
|
|
s.connections.del(id)
|
2020-06-19 17:29:43 +00:00
|
|
|
|
2020-06-02 17:32:42 +00:00
|
|
|
await conn.close()
|
2020-05-23 17:12:28 +00:00
|
|
|
|
|
|
|
s.dialedPubSubPeers.excl(id)
|
|
|
|
|
2020-06-16 20:43:45 +00:00
|
|
|
libp2p_peers.dec()
|
2020-05-23 17:12:28 +00:00
|
|
|
# TODO: Investigate cleanupConn() always called twice for one peer.
|
|
|
|
if not(conn.peerInfo.isClosed()):
|
|
|
|
conn.peerInfo.close()
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "exception cleaning up connection", exc = exc.msg
|
2020-02-11 17:53:39 +00:00
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc disconnect*(s: Switch, peer: PeerInfo) {.async, gcsafe.} =
|
|
|
|
let conn = s.connections.getOrDefault(peer.id)
|
2019-12-10 20:50:35 +00:00
|
|
|
if not isNil(conn):
|
2020-06-19 17:29:43 +00:00
|
|
|
trace "disconnecting peer", peer = $peer
|
2019-12-08 21:06:58 +00:00
|
|
|
await s.cleanupConn(conn)
|
|
|
|
|
2019-12-10 20:50:35 +00:00
|
|
|
proc getMuxedStream(s: Switch, peerInfo: PeerInfo): Future[Connection] {.async, gcsafe.} =
|
2019-09-28 19:54:32 +00:00
|
|
|
# if there is a muxer for the connection
|
|
|
|
# use it instead to create a muxed stream
|
2019-12-04 04:44:54 +00:00
|
|
|
if peerInfo.id in s.muxed:
|
|
|
|
trace "connection is muxed, setting up a stream"
|
|
|
|
let muxer = s.muxed[peerInfo.id]
|
2019-09-28 19:54:32 +00:00
|
|
|
let conn = await muxer.newStream()
|
2019-12-10 20:50:35 +00:00
|
|
|
result = conn
|
2019-09-28 19:54:32 +00:00
|
|
|
|
2019-09-12 12:02:25 +00:00
|
|
|
proc upgradeOutgoing(s: Switch, conn: Connection): Future[Connection] {.async, gcsafe.} =
|
2020-05-23 17:12:28 +00:00
|
|
|
trace "handling connection", conn = $conn
|
|
|
|
result = conn
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-05-23 17:12:28 +00:00
|
|
|
# don't mux/secure twise
|
|
|
|
if conn.peerInfo.id in s.muxed:
|
|
|
|
return
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-05-23 17:12:28 +00:00
|
|
|
result = await s.secure(result) # secure the connection
|
|
|
|
if isNil(result):
|
|
|
|
return
|
2019-12-13 15:25:07 +00:00
|
|
|
|
2020-05-23 17:12:28 +00:00
|
|
|
await s.mux(result) # mux it if possible
|
|
|
|
s.connections[conn.peerInfo.id] = result
|
2019-09-04 22:00:39 +00:00
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc upgradeIncoming(s: Switch, conn: Connection) {.async, gcsafe.} =
|
Noise (#90)
* Start ChaCha20Poly1305 integration (BearSSL)
* Add Curve25519 (BearSSL) required operations for noise
* Fix curve mulgen iterate/derive
* Fix misleading header
* Add chachapoly proper test
* Curve25519 integration tests (failing, something is wrong)
* Add few converters, finish c25519 integration tests
* Remove implicit converters
* removed internal globals
* Start noise implementation
* Fix public() using proper bear mulgen
* Noise protocol WIP
* Noise progress
* Add a quick nim version of HKDF
* Converted hkdf to iterator, useful for noise
* Noise protocol implementation progress
* Noise progress
* XX handshake almost there
* noise progress
* Noise, testing handshake with test vectors
* Noise handshake progress, still wrong somewhere!
* Noise handshake success!
* Full verified noise XX handshake completed
* Fix and rewrite test to be similar to switch one
* Start with connection upgrade
* Switch chachapoly to CT implementations
* Improve HKDF implementation
* Use a type insted of tuple for HandshakeResult
* Remove unnecessary Let
* More cosmetic fixes
* Properly check randomBytes result
* Fix chachapoly signature
* Noise full circle (altho dispatcher is nil cursed)
* Allow nil aads in chachapoly routines
* Noise implementation up to running full test
* Use bearssl HKDF as well
* Directly use bearssl rng for curve25519 keys
* Add a (disabled/no CI) noise interop test server
* WIP on fixing interop issues
* More fixes in noise implementation for interop
* bump chronos requirement (nimble)
* Add a chachapoly test for very small size payloads
* Noise, more tracing
* Add 2 properly working noise tests
* Fix payload packing, following the spec properly (and not go version but
rather rust)
* Sanity, replace discard with asyncCheck
* Small fixes and optimization
* Use stew endian2 rather then system endian module
* Update nimble deps (chronos)
* Minor cosmetic/code sanity fixes
* Noise, handle Nonce max
* Noise tests, make sure to close secured conns
* More polish, improve code readability too
* More polish and testing again which test fails
* Further polishing
* Restore noise tests
* Remove useless Future[void]
* Remove useless CipherState initializer
* add a proper read wait future in second noise test
* Remove noise generic secure implementation for now
* Few fixes to run eth2 sim
* Add more debug info in noise traces
* Merge size + payload write in sendEncryptedMessage
* Revert secure interface, add outgoing property directly in newNoise
* remove sendEncrypted and receiveEncrypted
* Use openarray in chachapoly and curve25519 helpers
2020-03-17 12:30:01 +00:00
|
|
|
trace "upgrading incoming connection", conn = $conn
|
2019-09-28 19:54:32 +00:00
|
|
|
let ms = newMultistream()
|
2019-09-04 01:50:17 +00:00
|
|
|
|
2019-09-28 19:54:32 +00:00
|
|
|
# secure incoming connections
|
|
|
|
proc securedHandler (conn: Connection,
|
|
|
|
proto: string)
|
|
|
|
{.async, gcsafe, closure.} =
|
2020-05-15 03:56:56 +00:00
|
|
|
try:
|
|
|
|
trace "Securing connection"
|
2020-06-01 17:49:25 +00:00
|
|
|
let secure = s.secureManagers.filterIt(it.codec == proto)[0]
|
2020-05-15 03:56:56 +00:00
|
|
|
let sconn = await secure.secure(conn, false)
|
|
|
|
if sconn.isNil:
|
|
|
|
return
|
|
|
|
|
2019-09-28 19:54:32 +00:00
|
|
|
# add the muxer
|
|
|
|
for muxer in s.muxers.values:
|
|
|
|
ms.addHandler(muxer.codec, muxer)
|
|
|
|
|
2020-05-15 03:56:56 +00:00
|
|
|
# handle subsequent requests
|
2020-05-23 17:12:28 +00:00
|
|
|
try:
|
|
|
|
await ms.handle(sconn)
|
|
|
|
finally:
|
|
|
|
await sconn.close()
|
|
|
|
|
2020-05-15 03:56:56 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "ending secured handler", err = exc.msg
|
2019-09-28 19:54:32 +00:00
|
|
|
|
2020-05-15 03:56:56 +00:00
|
|
|
try:
|
2020-05-23 17:12:28 +00:00
|
|
|
try:
|
|
|
|
if (await ms.select(conn)): # just handshake
|
|
|
|
# add the secure handlers
|
2020-06-01 17:49:25 +00:00
|
|
|
for k in s.secureManagers:
|
|
|
|
ms.addHandler(k.codec, securedHandler)
|
2020-05-23 17:12:28 +00:00
|
|
|
|
|
|
|
# handle secured connections
|
|
|
|
await ms.handle(conn)
|
|
|
|
finally:
|
|
|
|
await conn.close()
|
2020-05-15 03:56:56 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
2020-06-02 23:53:38 +00:00
|
|
|
trace "error in multistream", err = exc.msg
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2020-05-23 17:12:28 +00:00
|
|
|
proc subscribeToPeer*(s: Switch, peerInfo: PeerInfo) {.async, gcsafe.}
|
2020-02-21 01:14:39 +00:00
|
|
|
|
2020-02-25 22:13:05 +00:00
|
|
|
proc internalConnect(s: Switch,
|
|
|
|
peer: PeerInfo): Future[Connection] {.async.} =
|
2019-12-04 04:44:54 +00:00
|
|
|
let id = peer.id
|
2019-12-08 21:06:58 +00:00
|
|
|
trace "Dialing peer", peer = id
|
2019-12-23 18:44:51 +00:00
|
|
|
var conn = s.connections.getOrDefault(id)
|
|
|
|
if conn.isNil or conn.closed:
|
2019-12-08 21:06:58 +00:00
|
|
|
for t in s.transports: # for each transport
|
|
|
|
for a in peer.addrs: # for each address
|
2019-12-23 18:44:51 +00:00
|
|
|
if t.handles(a): # check if it can dial it
|
2019-12-08 21:06:58 +00:00
|
|
|
trace "Dialing address", address = $a
|
2020-06-11 14:45:59 +00:00
|
|
|
try:
|
|
|
|
conn = await t.dial(a)
|
|
|
|
libp2p_dialed_peers.inc()
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "dialing failed", exc = exc.msg
|
|
|
|
libp2p_failed_dials.inc()
|
|
|
|
continue
|
|
|
|
|
2019-12-04 04:44:54 +00:00
|
|
|
# make sure to assign the peer to the connection
|
2019-12-23 18:44:51 +00:00
|
|
|
conn.peerInfo = peer
|
2020-06-11 14:45:59 +00:00
|
|
|
|
2019-12-23 18:44:51 +00:00
|
|
|
conn = await s.upgradeOutgoing(conn)
|
|
|
|
if isNil(conn):
|
2020-06-11 14:45:59 +00:00
|
|
|
libp2p_failed_upgrade.inc()
|
2019-12-13 15:25:07 +00:00
|
|
|
continue
|
|
|
|
|
2019-12-23 18:44:51 +00:00
|
|
|
conn.closeEvent.wait()
|
2020-05-23 17:12:28 +00:00
|
|
|
.addCallback do(udata: pointer):
|
|
|
|
asyncCheck s.cleanupConn(conn)
|
|
|
|
|
2020-06-16 20:43:45 +00:00
|
|
|
libp2p_peers.inc()
|
2019-12-09 17:17:29 +00:00
|
|
|
break
|
2019-12-08 21:06:58 +00:00
|
|
|
else:
|
|
|
|
trace "Reusing existing connection"
|
|
|
|
|
2020-03-29 14:28:48 +00:00
|
|
|
if not isNil(conn):
|
|
|
|
await s.subscribeToPeer(peer)
|
|
|
|
|
2020-02-25 22:13:05 +00:00
|
|
|
result = conn
|
|
|
|
|
|
|
|
proc connect*(s: Switch, peer: PeerInfo) {.async.} =
|
2020-02-25 23:21:12 +00:00
|
|
|
var conn = await s.internalConnect(peer)
|
2020-02-25 22:13:05 +00:00
|
|
|
if isNil(conn):
|
|
|
|
raise newException(CatchableError, "Unable to connect to peer")
|
|
|
|
|
|
|
|
proc dial*(s: Switch,
|
|
|
|
peer: PeerInfo,
|
|
|
|
proto: string):
|
|
|
|
Future[Connection] {.async.} =
|
|
|
|
var conn = await s.internalConnect(peer)
|
2019-12-23 18:44:51 +00:00
|
|
|
if isNil(conn):
|
|
|
|
raise newException(CatchableError, "Unable to establish outgoing link")
|
2019-12-10 20:50:35 +00:00
|
|
|
|
2020-02-25 22:13:05 +00:00
|
|
|
if conn.closed:
|
|
|
|
raise newException(CatchableError, "Connection dead on arrival")
|
2019-12-08 21:06:58 +00:00
|
|
|
|
2020-02-25 23:20:57 +00:00
|
|
|
result = conn
|
2020-02-25 22:13:05 +00:00
|
|
|
let stream = await s.getMuxedStream(peer)
|
|
|
|
if not isNil(stream):
|
|
|
|
trace "Connection is muxed, return muxed stream"
|
|
|
|
result = stream
|
|
|
|
trace "Attempting to select remote", proto = proto
|
2019-12-08 21:06:58 +00:00
|
|
|
|
2020-02-25 22:13:05 +00:00
|
|
|
if not await s.ms.select(result, proto):
|
2020-06-06 00:17:05 +00:00
|
|
|
raise newException(CatchableError, "Unable to select sub-protocol " & proto)
|
2020-02-21 01:14:39 +00:00
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc mount*[T: LPProtocol](s: Switch, proto: T) {.gcsafe.} =
|
2019-08-31 17:58:49 +00:00
|
|
|
if isNil(proto.handler):
|
2019-12-04 04:44:54 +00:00
|
|
|
raise newException(CatchableError,
|
2019-08-31 17:58:49 +00:00
|
|
|
"Protocol has to define a handle method or proc")
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2019-09-06 07:13:47 +00:00
|
|
|
if proto.codec.len == 0:
|
2019-12-04 04:44:54 +00:00
|
|
|
raise newException(CatchableError,
|
2019-08-31 18:52:56 +00:00
|
|
|
"Protocol has to define a codec string")
|
|
|
|
|
2019-08-31 17:58:49 +00:00
|
|
|
s.ms.addHandler(proto.codec, proto)
|
2019-08-28 02:30:53 +00:00
|
|
|
|
2020-05-05 15:55:02 +00:00
|
|
|
proc start*(s: Switch): Future[seq[Future[void]]] {.async, gcsafe.} =
|
2020-06-09 18:42:52 +00:00
|
|
|
trace "starting switch for peer", peerInfo = shortLog(s.peerInfo)
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2019-08-31 18:52:56 +00:00
|
|
|
proc handle(conn: Connection): Future[void] {.async, closure, gcsafe.} =
|
2019-09-04 22:00:39 +00:00
|
|
|
try:
|
2020-05-23 17:12:28 +00:00
|
|
|
try:
|
2020-06-16 20:43:45 +00:00
|
|
|
libp2p_peers.inc()
|
2020-05-23 17:12:28 +00:00
|
|
|
await s.upgradeIncoming(conn) # perform upgrade on incoming connection
|
|
|
|
finally:
|
|
|
|
await s.cleanupConn(conn)
|
2020-05-15 03:56:56 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
2019-12-04 04:44:54 +00:00
|
|
|
except CatchableError as exc:
|
2020-03-27 14:25:52 +00:00
|
|
|
trace "Exception occurred in Switch.start", exc = exc.msg
|
2020-02-25 22:13:05 +00:00
|
|
|
|
2019-09-12 00:15:04 +00:00
|
|
|
var startFuts: seq[Future[void]]
|
2019-08-28 02:30:53 +00:00
|
|
|
for t in s.transports: # for each transport
|
2019-09-28 19:54:32 +00:00
|
|
|
for i, a in s.peerInfo.addrs:
|
2019-08-28 02:30:53 +00:00
|
|
|
if t.handles(a): # check if it handles the multiaddr
|
2020-05-05 15:55:02 +00:00
|
|
|
var server = await t.listen(a, handle)
|
2019-09-28 19:54:32 +00:00
|
|
|
s.peerInfo.addrs[i] = t.ma # update peer's address
|
2019-09-12 00:15:04 +00:00
|
|
|
startFuts.add(server)
|
2019-12-08 21:06:58 +00:00
|
|
|
|
2019-12-06 02:16:18 +00:00
|
|
|
if s.pubSub.isSome:
|
|
|
|
await s.pubSub.get().start()
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2019-09-12 00:15:04 +00:00
|
|
|
result = startFuts # listen for incoming connections
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2019-12-08 21:06:58 +00:00
|
|
|
proc stop*(s: Switch) {.async.} =
|
2020-05-27 20:46:25 +00:00
|
|
|
try:
|
|
|
|
trace "stopping switch"
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2020-06-23 05:23:00 +00:00
|
|
|
s.running = false
|
|
|
|
|
|
|
|
# Stop explicit peering system (gossip 1.1 related, but useful even with other pubsubs)
|
|
|
|
# Cancel their sleep as it likely is running for 5 mins
|
|
|
|
# running is false so they should exit after that
|
|
|
|
# and so we just wait/ensure all has finished
|
|
|
|
# Maintain has tryAndWarn so we should not be priting any error here
|
|
|
|
# nevertheless use checkFutures!
|
|
|
|
# Notice.. this is ugly but we have no clean way to express a Chain of operations/futures
|
|
|
|
# and simply post a cancelation/stop from the root of the chain...
|
|
|
|
let
|
|
|
|
maintainers = toSeq(s.maintainFuts.values)
|
|
|
|
sleepFuts = maintainers.mapIt(it.sleepFut)
|
|
|
|
loopFuts = maintainers.mapIt(it.loopFut)
|
|
|
|
for f in sleepFuts: f.cancel()
|
|
|
|
checkFutures(await allFinished(sleepFuts))
|
|
|
|
checkFutures(await allFinished(loopFuts))
|
|
|
|
|
2020-05-27 20:46:25 +00:00
|
|
|
# we want to report errors but we do not want to fail
|
|
|
|
# or crash here, cos we need to clean possibly MANY items
|
|
|
|
# and any following conn/transport won't be cleaned up
|
|
|
|
if s.pubSub.isSome:
|
|
|
|
await s.pubSub.get().stop()
|
2020-04-11 04:08:25 +00:00
|
|
|
|
2020-05-27 20:46:25 +00:00
|
|
|
for conn in toSeq(s.connections.values):
|
|
|
|
try:
|
|
|
|
await s.cleanupConn(conn)
|
|
|
|
except CatchableError as exc:
|
|
|
|
warn "error cleaning up connections"
|
2019-12-06 02:16:18 +00:00
|
|
|
|
2020-05-27 20:46:25 +00:00
|
|
|
for t in s.transports:
|
|
|
|
try:
|
|
|
|
await t.close()
|
|
|
|
except CatchableError as exc:
|
|
|
|
warn "error cleaning up transports"
|
2019-09-06 07:13:47 +00:00
|
|
|
|
2020-05-27 20:46:25 +00:00
|
|
|
trace "switch stopped"
|
|
|
|
except CatchableError as exc:
|
|
|
|
warn "error stopping switch", exc = exc.msg
|
2020-04-21 01:24:42 +00:00
|
|
|
|
2020-06-23 05:23:00 +00:00
|
|
|
proc maintainPeer(s: Switch, peerInfo: PeerInfo) {.async.} =
|
|
|
|
while s.running:
|
|
|
|
tryAndWarn "explicit peer maintain":
|
|
|
|
var conn = s.connections.getOrDefault(peerInfo.id)
|
|
|
|
if conn.isNil or conn.closed:
|
|
|
|
# attempt redial in this case
|
|
|
|
discard
|
|
|
|
|
|
|
|
await sleepAsync(5.minutes) # spec recommended
|
|
|
|
|
2020-05-23 17:12:28 +00:00
|
|
|
proc subscribeToPeer*(s: Switch, peerInfo: PeerInfo) {.async, gcsafe.} =
|
2020-06-18 02:12:32 +00:00
|
|
|
trace "about to subscribe to pubsub peer", peer = peerInfo.shortLog()
|
2019-09-12 02:10:38 +00:00
|
|
|
## Subscribe to pub sub peer
|
2020-06-18 02:12:32 +00:00
|
|
|
if s.pubSub.isSome and (peerInfo.id notin s.dialedPubSubPeers):
|
|
|
|
let conn = await s.getMuxedStream(peerInfo)
|
2020-06-19 17:29:25 +00:00
|
|
|
if isNil(conn):
|
|
|
|
trace "unable to subscribe to peer", peer = peerInfo.shortLog
|
|
|
|
return
|
2020-06-18 02:12:32 +00:00
|
|
|
|
2020-06-19 17:29:25 +00:00
|
|
|
s.dialedPubSubPeers.incl(peerInfo.id)
|
|
|
|
try:
|
2020-06-18 02:12:32 +00:00
|
|
|
if (await s.ms.select(conn, s.pubSub.get().codec)):
|
|
|
|
await s.pubSub.get().subscribeToPeer(conn)
|
|
|
|
else:
|
|
|
|
await conn.close()
|
2020-02-21 01:14:39 +00:00
|
|
|
except CatchableError as exc:
|
2020-06-18 02:12:32 +00:00
|
|
|
trace "exception in subscribe to peer", peer = peerInfo.shortLog, exc = exc.msg
|
|
|
|
await conn.close()
|
2020-03-29 14:28:48 +00:00
|
|
|
finally:
|
2020-02-21 01:14:39 +00:00
|
|
|
s.dialedPubSubPeers.excl(peerInfo.id)
|
2020-06-23 05:23:00 +00:00
|
|
|
|
|
|
|
if peerInfo.maintain:
|
|
|
|
s.maintainFuts[peerInfo.id].loopFut = maintainPeer(s, peerInfo)
|
|
|
|
s.maintainFuts[peerInfo.id].sleepFut = newFuture[void]() # stub until real one happens
|
2019-09-11 19:03:30 +00:00
|
|
|
|
2020-03-04 19:45:14 +00:00
|
|
|
proc subscribe*(s: Switch, topic: string,
|
|
|
|
handler: TopicHandler): Future[void] =
|
2019-09-12 02:10:38 +00:00
|
|
|
## subscribe to a pubsub topic
|
2019-09-11 19:03:30 +00:00
|
|
|
if s.pubSub.isNone:
|
2020-03-04 19:45:14 +00:00
|
|
|
var retFuture = newFuture[void]("Switch.subscribe")
|
|
|
|
retFuture.fail(newNoPubSubException())
|
|
|
|
return retFuture
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2019-09-11 19:03:30 +00:00
|
|
|
result = s.pubSub.get().subscribe(topic, handler)
|
|
|
|
|
2020-03-04 19:45:14 +00:00
|
|
|
proc unsubscribe*(s: Switch, topics: seq[TopicPair]): Future[void] =
|
2019-09-12 02:10:38 +00:00
|
|
|
## unsubscribe from topics
|
2019-09-11 19:03:30 +00:00
|
|
|
if s.pubSub.isNone:
|
2020-03-04 19:45:14 +00:00
|
|
|
var retFuture = newFuture[void]("Switch.unsubscribe")
|
|
|
|
retFuture.fail(newNoPubSubException())
|
|
|
|
return retFuture
|
2019-12-04 04:44:54 +00:00
|
|
|
|
2019-09-11 19:03:30 +00:00
|
|
|
result = s.pubSub.get().unsubscribe(topics)
|
|
|
|
|
2020-03-04 19:45:14 +00:00
|
|
|
proc publish*(s: Switch, topic: string, data: seq[byte]): Future[void] =
|
2019-09-12 02:10:38 +00:00
|
|
|
# pubslish to pubsub topic
|
2019-09-11 19:03:30 +00:00
|
|
|
if s.pubSub.isNone:
|
2020-03-04 19:45:14 +00:00
|
|
|
var retFuture = newFuture[void]("Switch.publish")
|
|
|
|
retFuture.fail(newNoPubSubException())
|
|
|
|
return retFuture
|
2019-09-11 19:03:30 +00:00
|
|
|
|
|
|
|
result = s.pubSub.get().publish(topic, data)
|
|
|
|
|
2019-12-17 05:24:03 +00:00
|
|
|
proc addValidator*(s: Switch,
|
|
|
|
topics: varargs[string],
|
|
|
|
hook: ValidatorHandler) =
|
|
|
|
# add validator
|
|
|
|
if s.pubSub.isNone:
|
|
|
|
raise newNoPubSubException()
|
|
|
|
|
|
|
|
s.pubSub.get().addValidator(topics, hook)
|
|
|
|
|
|
|
|
proc removeValidator*(s: Switch,
|
|
|
|
topics: varargs[string],
|
|
|
|
hook: ValidatorHandler) =
|
|
|
|
# pubslish to pubsub topic
|
|
|
|
if s.pubSub.isNone:
|
|
|
|
raise newNoPubSubException()
|
|
|
|
|
|
|
|
s.pubSub.get().removeValidator(topics, hook)
|
|
|
|
|
2019-09-06 07:13:47 +00:00
|
|
|
proc newSwitch*(peerInfo: PeerInfo,
|
|
|
|
transports: seq[Transport],
|
|
|
|
identity: Identify,
|
2019-09-09 17:33:32 +00:00
|
|
|
muxers: Table[string, MuxerProvider],
|
2020-06-01 06:41:32 +00:00
|
|
|
secureManagers: openarray[Secure] = [],
|
2019-09-11 19:03:30 +00:00
|
|
|
pubSub: Option[PubSub] = none(PubSub)): Switch =
|
2019-09-06 07:13:47 +00:00
|
|
|
new result
|
|
|
|
result.peerInfo = peerInfo
|
|
|
|
result.ms = newMultistream()
|
|
|
|
result.transports = transports
|
2019-09-13 18:41:48 +00:00
|
|
|
result.connections = initTable[string, Connection]()
|
|
|
|
result.muxed = initTable[string, Muxer]()
|
2019-09-06 07:13:47 +00:00
|
|
|
result.identity = identity
|
|
|
|
result.muxers = muxers
|
2020-06-01 17:49:25 +00:00
|
|
|
result.secureManagers = @secureManagers
|
2020-02-21 01:14:39 +00:00
|
|
|
result.dialedPubSubPeers = initHashSet[string]()
|
2019-09-06 07:13:47 +00:00
|
|
|
|
|
|
|
let s = result # can't capture result
|
2019-12-08 21:06:58 +00:00
|
|
|
result.streamHandler = proc(stream: Connection) {.async, gcsafe.} =
|
2020-05-23 19:25:53 +00:00
|
|
|
try:
|
2020-06-09 18:42:52 +00:00
|
|
|
trace "handling connection for", peerInfo = $stream
|
2020-05-23 19:25:53 +00:00
|
|
|
try:
|
|
|
|
await s.ms.handle(stream) # handle incoming connection
|
|
|
|
finally:
|
|
|
|
if not(stream.closed):
|
|
|
|
await stream.close()
|
|
|
|
except CatchableError as exc:
|
2020-06-02 17:32:42 +00:00
|
|
|
trace "exception in stream handler", exc = exc.msg
|
2019-09-06 07:13:47 +00:00
|
|
|
|
|
|
|
result.mount(identity)
|
|
|
|
for key, val in muxers:
|
|
|
|
val.streamHandler = result.streamHandler
|
2019-09-12 02:10:38 +00:00
|
|
|
val.muxerHandler = proc(muxer: Muxer) {.async, gcsafe.} =
|
2020-05-23 17:12:28 +00:00
|
|
|
var stream: Connection
|
|
|
|
try:
|
|
|
|
trace "got new muxer"
|
|
|
|
stream = await muxer.newStream()
|
2020-06-02 17:32:42 +00:00
|
|
|
# once we got a muxed connection, attempt to
|
|
|
|
# identify it
|
2020-05-23 17:12:28 +00:00
|
|
|
muxer.connection.peerInfo = await s.identify(stream)
|
|
|
|
|
|
|
|
# store muxer for connection
|
|
|
|
s.muxed[muxer.connection.peerInfo.id] = muxer
|
|
|
|
|
|
|
|
# store muxed connection
|
|
|
|
s.connections[muxer.connection.peerInfo.id] = muxer.connection
|
|
|
|
|
2020-06-02 17:32:42 +00:00
|
|
|
muxer.connection.closeEvent.wait()
|
|
|
|
.addCallback do(udata: pointer):
|
|
|
|
asyncCheck s.cleanupConn(muxer.connection)
|
|
|
|
|
2020-05-23 17:12:28 +00:00
|
|
|
# try establishing a pubsub connection
|
|
|
|
await s.subscribeToPeer(muxer.connection.peerInfo)
|
|
|
|
except CatchableError as exc:
|
2020-06-11 14:45:59 +00:00
|
|
|
libp2p_failed_upgrade.inc()
|
2020-05-23 17:12:28 +00:00
|
|
|
trace "exception in muxer handler", exc = exc.msg
|
|
|
|
finally:
|
|
|
|
if not(isNil(stream)):
|
|
|
|
await stream.close()
|
2020-05-21 17:33:48 +00:00
|
|
|
|
2020-06-01 17:49:25 +00:00
|
|
|
if result.secureManagers.len <= 0:
|
2019-09-09 17:33:32 +00:00
|
|
|
# use plain text if no secure managers are provided
|
2020-02-12 14:43:42 +00:00
|
|
|
warn "no secure managers, falling back to plain text", codec = PlainTextCodec
|
2020-06-01 17:49:25 +00:00
|
|
|
result.secureManagers &= Secure(newPlainText())
|
2019-09-11 19:03:30 +00:00
|
|
|
|
|
|
|
if pubSub.isSome:
|
|
|
|
result.pubSub = pubSub
|
|
|
|
result.mount(pubSub.get())
|