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.
|
2021-03-18 15:20:36 +00:00
|
|
|
|
2023-05-18 08:24:17 +00:00
|
|
|
import std/tables
|
2021-03-18 15:20:36 +00:00
|
|
|
|
2022-09-22 19:55:59 +00:00
|
|
|
import stew/results
|
2021-03-18 15:20:36 +00:00
|
|
|
import pkg/[chronos,
|
|
|
|
chronicles,
|
|
|
|
metrics]
|
|
|
|
|
|
|
|
import dial,
|
|
|
|
peerid,
|
|
|
|
peerinfo,
|
2023-03-08 11:30:19 +00:00
|
|
|
peerstore,
|
2022-09-26 09:03:24 +00:00
|
|
|
multicodec,
|
2023-03-08 11:30:19 +00:00
|
|
|
muxers/muxer,
|
2021-03-18 15:20:36 +00:00
|
|
|
multistream,
|
|
|
|
connmanager,
|
|
|
|
stream/connection,
|
2021-05-24 17:55:33 +00:00
|
|
|
transports/transport,
|
2021-11-08 12:02:03 +00:00
|
|
|
nameresolving/nameresolver,
|
2022-08-23 15:49:07 +00:00
|
|
|
upgrademngrs/upgrade,
|
2021-05-24 17:55:33 +00:00
|
|
|
errors
|
2021-03-18 15:20:36 +00:00
|
|
|
|
2022-09-22 19:55:59 +00:00
|
|
|
export dial, errors, results
|
2021-03-18 15:20:36 +00:00
|
|
|
|
|
|
|
logScope:
|
|
|
|
topics = "libp2p dialer"
|
|
|
|
|
|
|
|
declareCounter(libp2p_total_dial_attempts, "total attempted dials")
|
|
|
|
declareCounter(libp2p_successful_dials, "dialed successful peers")
|
|
|
|
declareCounter(libp2p_failed_dials, "failed dials")
|
|
|
|
|
|
|
|
type
|
2021-05-24 17:55:33 +00:00
|
|
|
DialFailedError* = object of LPError
|
2021-03-18 15:20:36 +00:00
|
|
|
|
|
|
|
Dialer* = ref object of Dial
|
2021-09-08 09:07:46 +00:00
|
|
|
localPeerId*: PeerId
|
2021-03-18 15:20:36 +00:00
|
|
|
connManager: ConnManager
|
2021-12-16 10:05:20 +00:00
|
|
|
dialLock: Table[PeerId, AsyncLock]
|
2021-03-18 15:20:36 +00:00
|
|
|
transports: seq[Transport]
|
2023-03-08 11:30:19 +00:00
|
|
|
peerStore: PeerStore
|
2021-11-08 12:02:03 +00:00
|
|
|
nameResolver: NameResolver
|
2021-03-18 15:20:36 +00:00
|
|
|
|
2022-09-26 09:03:24 +00:00
|
|
|
proc dialAndUpgrade(
|
|
|
|
self: Dialer,
|
|
|
|
peerId: Opt[PeerId],
|
|
|
|
hostname: string,
|
2023-04-14 14:23:19 +00:00
|
|
|
address: MultiAddress,
|
2023-11-29 16:38:47 +00:00
|
|
|
dir = Direction.Out):
|
2023-03-08 11:30:19 +00:00
|
|
|
Future[Muxer] {.async.} =
|
2022-09-26 09:03:24 +00:00
|
|
|
|
|
|
|
for transport in self.transports: # for each transport
|
|
|
|
if transport.handles(address): # check if it can dial it
|
2023-06-28 15:00:33 +00:00
|
|
|
trace "Dialing address", address, peerId = peerId.get(default(PeerId)), hostname
|
2022-09-26 09:03:24 +00:00
|
|
|
let dialed =
|
|
|
|
try:
|
|
|
|
libp2p_total_dial_attempts.inc()
|
2023-01-31 11:46:10 +00:00
|
|
|
await transport.dial(hostname, address, peerId)
|
2022-09-26 09:03:24 +00:00
|
|
|
except CancelledError as exc:
|
2023-06-28 15:00:33 +00:00
|
|
|
debug "Dialing canceled", err = exc.msg, peerId = peerId.get(default(PeerId))
|
2022-09-26 09:03:24 +00:00
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
2023-06-28 15:00:33 +00:00
|
|
|
debug "Dialing failed", err = exc.msg, peerId = peerId.get(default(PeerId))
|
2022-09-26 09:03:24 +00:00
|
|
|
libp2p_failed_dials.inc()
|
|
|
|
return nil # Try the next address
|
|
|
|
|
|
|
|
libp2p_successful_dials.inc()
|
|
|
|
|
2023-03-08 11:30:19 +00:00
|
|
|
let mux =
|
2022-09-26 09:03:24 +00:00
|
|
|
try:
|
2023-11-29 16:38:47 +00:00
|
|
|
# This is for the very specific case of a simultaneous dial during DCUtR. In this case, both sides will have
|
|
|
|
# an Outbound direction at the transport level. Therefore we update the DCUtR initiator transport direction to Inbound.
|
|
|
|
# The if below is more general and might handle other use cases in the future.
|
|
|
|
if dialed.dir != dir:
|
|
|
|
dialed.dir = dir
|
|
|
|
await transport.upgrade(dialed, peerId)
|
2024-05-14 05:10:34 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
await dialed.close()
|
|
|
|
raise exc
|
2022-09-26 09:03:24 +00:00
|
|
|
except CatchableError as exc:
|
|
|
|
# If we failed to establish the connection through one transport,
|
|
|
|
# we won't succeeded through another - no use in trying again
|
|
|
|
await dialed.close()
|
2024-03-18 10:38:23 +00:00
|
|
|
debug "Connection upgrade failed", err = exc.msg, peerId = peerId.get(default(PeerId))
|
2024-05-14 05:10:34 +00:00
|
|
|
if dialed.dir == Direction.Out:
|
|
|
|
libp2p_failed_upgrades_outgoing.inc()
|
|
|
|
else:
|
|
|
|
libp2p_failed_upgrades_incoming.inc()
|
2022-09-26 09:03:24 +00:00
|
|
|
|
|
|
|
# Try other address
|
|
|
|
return nil
|
|
|
|
|
2023-11-29 16:38:47 +00:00
|
|
|
doAssert not isNil(mux), "connection died after upgrade " & $dialed.dir
|
2023-03-08 11:30:19 +00:00
|
|
|
debug "Dial successful", peerId = mux.connection.peerId
|
|
|
|
return mux
|
2022-09-26 09:03:24 +00:00
|
|
|
return nil
|
|
|
|
|
|
|
|
proc expandDnsAddr(
|
|
|
|
self: Dialer,
|
|
|
|
peerId: Opt[PeerId],
|
|
|
|
address: MultiAddress): Future[seq[(MultiAddress, Opt[PeerId])]] {.async.} =
|
|
|
|
|
|
|
|
if not DNSADDR.matchPartial(address): return @[(address, peerId)]
|
|
|
|
if isNil(self.nameResolver):
|
|
|
|
info "Can't resolve DNSADDR without NameResolver", ma=address
|
|
|
|
return @[]
|
|
|
|
|
|
|
|
let
|
|
|
|
toResolve =
|
|
|
|
if peerId.isSome:
|
|
|
|
address & MultiAddress.init(multiCodec("p2p"), peerId.tryGet()).tryGet()
|
|
|
|
else:
|
|
|
|
address
|
|
|
|
resolved = await self.nameResolver.resolveDnsAddr(toResolve)
|
|
|
|
|
|
|
|
for resolvedAddress in resolved:
|
|
|
|
let lastPart = resolvedAddress[^1].tryGet()
|
|
|
|
if lastPart.protoCode == Result[MultiCodec, string].ok(multiCodec("p2p")):
|
|
|
|
let
|
|
|
|
peerIdBytes = lastPart.protoArgument().tryGet()
|
|
|
|
addrPeerId = PeerId.init(peerIdBytes).tryGet()
|
|
|
|
result.add((resolvedAddress[0..^2].tryGet(), Opt.some(addrPeerId)))
|
|
|
|
else:
|
|
|
|
result.add((resolvedAddress, peerId))
|
|
|
|
|
2021-03-18 15:20:36 +00:00
|
|
|
proc dialAndUpgrade(
|
|
|
|
self: Dialer,
|
2022-09-05 12:31:14 +00:00
|
|
|
peerId: Opt[PeerId],
|
2023-04-14 14:23:19 +00:00
|
|
|
addrs: seq[MultiAddress],
|
2023-11-29 16:38:47 +00:00
|
|
|
dir = Direction.Out):
|
2023-03-08 11:30:19 +00:00
|
|
|
Future[Muxer] {.async.} =
|
2022-09-26 09:03:24 +00:00
|
|
|
|
2023-06-28 15:00:33 +00:00
|
|
|
debug "Dialing peer", peerId = peerId.get(default(PeerId))
|
2021-03-18 15:20:36 +00:00
|
|
|
|
2022-09-26 09:03:24 +00:00
|
|
|
for rawAddress in addrs:
|
|
|
|
# resolve potential dnsaddr
|
|
|
|
let addresses = await self.expandDnsAddr(peerId, rawAddress)
|
|
|
|
|
|
|
|
for (expandedAddress, addrPeerId) in addresses:
|
|
|
|
# DNS resolution
|
|
|
|
let
|
|
|
|
hostname = expandedAddress.getHostname()
|
|
|
|
resolvedAddresses =
|
|
|
|
if isNil(self.nameResolver): @[expandedAddress]
|
|
|
|
else: await self.nameResolver.resolveMAddress(expandedAddress)
|
|
|
|
|
|
|
|
for resolvedAddress in resolvedAddresses:
|
2023-11-29 16:38:47 +00:00
|
|
|
result = await self.dialAndUpgrade(addrPeerId, hostname, resolvedAddress, dir)
|
2022-09-26 09:03:24 +00:00
|
|
|
if not isNil(result):
|
|
|
|
return result
|
2021-03-18 15:20:36 +00:00
|
|
|
|
2023-06-28 14:44:58 +00:00
|
|
|
proc tryReusingConnection(self: Dialer, peerId: PeerId): Opt[Muxer] =
|
2023-03-08 11:30:19 +00:00
|
|
|
let muxer = self.connManager.selectMuxer(peerId)
|
|
|
|
if muxer == nil:
|
|
|
|
return Opt.none(Muxer)
|
2023-01-25 10:19:03 +00:00
|
|
|
|
2023-03-08 11:30:19 +00:00
|
|
|
trace "Reusing existing connection", muxer, direction = $muxer.connection.dir
|
|
|
|
return Opt.some(muxer)
|
2023-01-25 10:19:03 +00:00
|
|
|
|
2021-03-18 15:20:36 +00:00
|
|
|
proc internalConnect(
|
|
|
|
self: Dialer,
|
2022-09-05 12:31:14 +00:00
|
|
|
peerId: Opt[PeerId],
|
2022-02-24 16:31:47 +00:00
|
|
|
addrs: seq[MultiAddress],
|
2023-01-25 10:19:03 +00:00
|
|
|
forceDial: bool,
|
2023-04-14 14:23:19 +00:00
|
|
|
reuseConnection = true,
|
2023-11-29 16:38:47 +00:00
|
|
|
dir = Direction.Out):
|
2023-03-08 11:30:19 +00:00
|
|
|
Future[Muxer] {.async.} =
|
2022-09-05 12:31:14 +00:00
|
|
|
if Opt.some(self.localPeerId) == peerId:
|
2021-03-18 15:20:36 +00:00
|
|
|
raise newException(CatchableError, "can't dial self!")
|
|
|
|
|
|
|
|
# Ensure there's only one in-flight attempt per peer
|
2022-09-05 12:31:14 +00:00
|
|
|
let lock = self.dialLock.mgetOrPut(peerId.get(default(PeerId)), newAsyncLock())
|
2021-03-18 15:20:36 +00:00
|
|
|
try:
|
|
|
|
await lock.acquire()
|
|
|
|
|
2023-06-28 14:44:58 +00:00
|
|
|
if reuseConnection:
|
|
|
|
peerId.withValue(peerId):
|
|
|
|
self.tryReusingConnection(peerId).withValue(mux):
|
|
|
|
return mux
|
2021-03-18 15:20:36 +00:00
|
|
|
|
2023-01-05 14:02:52 +00:00
|
|
|
let slot = self.connManager.getOutgoingSlot(forceDial)
|
2023-03-08 11:30:19 +00:00
|
|
|
let muxed =
|
2022-08-03 14:48:19 +00:00
|
|
|
try:
|
2023-11-29 16:38:47 +00:00
|
|
|
await self.dialAndUpgrade(peerId, addrs, dir)
|
2022-08-03 14:48:19 +00:00
|
|
|
except CatchableError as exc:
|
|
|
|
slot.release()
|
|
|
|
raise exc
|
2023-03-08 11:30:19 +00:00
|
|
|
slot.trackMuxer(muxed)
|
|
|
|
if isNil(muxed): # None of the addresses connected
|
2021-03-18 15:20:36 +00:00
|
|
|
raise newException(DialFailedError, "Unable to establish outgoing link")
|
|
|
|
|
2023-03-08 11:30:19 +00:00
|
|
|
try:
|
|
|
|
self.connManager.storeMuxer(muxed)
|
|
|
|
await self.peerStore.identify(muxed)
|
|
|
|
except CatchableError as exc:
|
|
|
|
trace "Failed to finish outgoung upgrade", err=exc.msg
|
|
|
|
await muxed.close()
|
|
|
|
raise exc
|
|
|
|
|
|
|
|
return muxed
|
2021-03-18 15:20:36 +00:00
|
|
|
finally:
|
|
|
|
if lock.locked():
|
|
|
|
lock.release()
|
|
|
|
|
|
|
|
method connect*(
|
|
|
|
self: Dialer,
|
2021-12-16 10:05:20 +00:00
|
|
|
peerId: PeerId,
|
2022-02-24 16:31:47 +00:00
|
|
|
addrs: seq[MultiAddress],
|
2023-01-25 10:19:03 +00:00
|
|
|
forceDial = false,
|
2023-04-14 14:23:19 +00:00
|
|
|
reuseConnection = true,
|
2023-11-29 16:38:47 +00:00
|
|
|
dir = Direction.Out) {.async.} =
|
2021-03-18 15:20:36 +00:00
|
|
|
## connect remote peer without negotiating
|
|
|
|
## a protocol
|
|
|
|
##
|
|
|
|
|
2023-01-25 10:19:03 +00:00
|
|
|
if self.connManager.connCount(peerId) > 0 and reuseConnection:
|
2021-03-18 15:20:36 +00:00
|
|
|
return
|
|
|
|
|
2023-11-29 16:38:47 +00:00
|
|
|
discard await self.internalConnect(Opt.some(peerId), addrs, forceDial, reuseConnection, dir)
|
2022-09-05 12:31:14 +00:00
|
|
|
|
|
|
|
method connect*(
|
|
|
|
self: Dialer,
|
2022-12-08 16:11:55 +00:00
|
|
|
address: MultiAddress,
|
|
|
|
allowUnknownPeerId = false): Future[PeerId] {.async.} =
|
2022-09-05 12:31:14 +00:00
|
|
|
## Connects to a peer and retrieve its PeerId
|
|
|
|
|
2023-06-28 14:44:58 +00:00
|
|
|
parseFullAddress(address).toOpt().withValue(fullAddress):
|
2022-12-08 16:11:55 +00:00
|
|
|
return (await self.internalConnect(
|
2023-06-28 14:44:58 +00:00
|
|
|
Opt.some(fullAddress[0]),
|
|
|
|
@[fullAddress[1]],
|
2023-03-08 11:30:19 +00:00
|
|
|
false)).connection.peerId
|
2021-03-18 15:20:36 +00:00
|
|
|
|
2023-06-28 14:44:58 +00:00
|
|
|
if allowUnknownPeerId == false:
|
|
|
|
raise newException(DialFailedError, "Address without PeerID and unknown peer id disabled!")
|
|
|
|
|
|
|
|
return (await self.internalConnect(
|
|
|
|
Opt.none(PeerId),
|
|
|
|
@[address],
|
|
|
|
false)).connection.peerId
|
|
|
|
|
2021-03-18 15:20:36 +00:00
|
|
|
proc negotiateStream(
|
|
|
|
self: Dialer,
|
|
|
|
conn: Connection,
|
|
|
|
protos: seq[string]): Future[Connection] {.async.} =
|
|
|
|
trace "Negotiating stream", conn, protos
|
2023-03-08 11:30:19 +00:00
|
|
|
let selected = await MultistreamSelect.select(conn, protos)
|
2021-03-18 15:20:36 +00:00
|
|
|
if not protos.contains(selected):
|
|
|
|
await conn.closeWithEOF()
|
|
|
|
raise newException(DialFailedError, "Unable to select sub-protocol " & $protos)
|
|
|
|
|
|
|
|
return conn
|
|
|
|
|
2022-08-23 15:49:07 +00:00
|
|
|
method tryDial*(
|
|
|
|
self: Dialer,
|
|
|
|
peerId: PeerId,
|
2022-09-22 19:55:59 +00:00
|
|
|
addrs: seq[MultiAddress]): Future[Opt[MultiAddress]] {.async.} =
|
2022-09-02 18:40:14 +00:00
|
|
|
## Create a protocol stream in order to check
|
2022-08-23 15:49:07 +00:00
|
|
|
## if a connection is possible.
|
|
|
|
## Doesn't use the Connection Manager to save it.
|
|
|
|
##
|
|
|
|
|
|
|
|
trace "Check if it can dial", peerId, addrs
|
|
|
|
try:
|
2023-03-08 11:30:19 +00:00
|
|
|
let mux = await self.dialAndUpgrade(Opt.some(peerId), addrs)
|
|
|
|
if mux.isNil():
|
2022-08-23 15:49:07 +00:00
|
|
|
raise newException(DialFailedError, "No valid multiaddress")
|
2023-03-08 11:30:19 +00:00
|
|
|
await mux.close()
|
|
|
|
return mux.connection.observedAddr
|
2022-08-23 15:49:07 +00:00
|
|
|
except CancelledError as exc:
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
|
|
|
raise newException(DialFailedError, exc.msg)
|
|
|
|
|
2021-03-18 15:20:36 +00:00
|
|
|
method dial*(
|
|
|
|
self: Dialer,
|
2021-12-16 10:05:20 +00:00
|
|
|
peerId: PeerId,
|
2021-03-18 15:20:36 +00:00
|
|
|
protos: seq[string]): Future[Connection] {.async.} =
|
|
|
|
## create a protocol stream over an
|
|
|
|
## existing connection
|
|
|
|
##
|
|
|
|
|
|
|
|
trace "Dialing (existing)", peerId, protos
|
|
|
|
let stream = await self.connManager.getStream(peerId)
|
|
|
|
if stream.isNil:
|
|
|
|
raise newException(DialFailedError, "Couldn't get muxed stream")
|
|
|
|
|
|
|
|
return await self.negotiateStream(stream, protos)
|
|
|
|
|
|
|
|
method dial*(
|
|
|
|
self: Dialer,
|
2021-12-16 10:05:20 +00:00
|
|
|
peerId: PeerId,
|
2021-03-18 15:20:36 +00:00
|
|
|
addrs: seq[MultiAddress],
|
2022-02-24 16:31:47 +00:00
|
|
|
protos: seq[string],
|
|
|
|
forceDial = false): Future[Connection] {.async.} =
|
2021-03-18 15:20:36 +00:00
|
|
|
## create a protocol stream and establish
|
|
|
|
## a connection if one doesn't exist already
|
|
|
|
##
|
|
|
|
|
|
|
|
var
|
2023-03-08 11:30:19 +00:00
|
|
|
conn: Muxer
|
2021-03-18 15:20:36 +00:00
|
|
|
stream: Connection
|
|
|
|
|
|
|
|
proc cleanup() {.async.} =
|
|
|
|
if not(isNil(stream)):
|
|
|
|
await stream.closeWithEOF()
|
|
|
|
|
|
|
|
if not(isNil(conn)):
|
|
|
|
await conn.close()
|
|
|
|
|
|
|
|
try:
|
|
|
|
trace "Dialing (new)", peerId, protos
|
2022-09-05 12:31:14 +00:00
|
|
|
conn = await self.internalConnect(Opt.some(peerId), addrs, forceDial)
|
2021-03-18 15:20:36 +00:00
|
|
|
trace "Opening stream", conn
|
|
|
|
stream = await self.connManager.getStream(conn)
|
|
|
|
|
|
|
|
if isNil(stream):
|
|
|
|
raise newException(DialFailedError,
|
|
|
|
"Couldn't get muxed stream")
|
|
|
|
|
|
|
|
return await self.negotiateStream(stream, protos)
|
|
|
|
except CancelledError as exc:
|
|
|
|
trace "Dial canceled", conn
|
|
|
|
await cleanup()
|
|
|
|
raise exc
|
|
|
|
except CatchableError as exc:
|
2023-06-28 15:00:33 +00:00
|
|
|
debug "Error dialing", conn, err = exc.msg
|
2021-03-18 15:20:36 +00:00
|
|
|
await cleanup()
|
|
|
|
raise exc
|
|
|
|
|
2022-05-18 08:19:37 +00:00
|
|
|
method addTransport*(self: Dialer, t: Transport) =
|
|
|
|
self.transports &= t
|
|
|
|
|
2021-03-18 15:20:36 +00:00
|
|
|
proc new*(
|
|
|
|
T: type Dialer,
|
2021-09-08 09:07:46 +00:00
|
|
|
localPeerId: PeerId,
|
2021-03-18 15:20:36 +00:00
|
|
|
connManager: ConnManager,
|
2023-03-08 11:30:19 +00:00
|
|
|
peerStore: PeerStore,
|
2021-03-18 15:20:36 +00:00
|
|
|
transports: seq[Transport],
|
2021-11-08 12:02:03 +00:00
|
|
|
nameResolver: NameResolver = nil): Dialer =
|
2021-03-18 15:20:36 +00:00
|
|
|
|
2021-09-08 09:07:46 +00:00
|
|
|
T(localPeerId: localPeerId,
|
2021-03-18 15:20:36 +00:00
|
|
|
connManager: connManager,
|
|
|
|
transports: transports,
|
2023-03-08 11:30:19 +00:00
|
|
|
peerStore: peerStore,
|
2021-11-08 12:02:03 +00:00
|
|
|
nameResolver: nameResolver)
|