2022-12-16 11:32:00 +00:00
|
|
|
# Nim-LibP2P
|
2023-01-20 14:47:40 +00:00
|
|
|
# Copyright (c) 2023 Status Research & Development GmbH
|
2022-12-16 11:32:00 +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.
|
|
|
|
|
2023-06-07 11:12:49 +00:00
|
|
|
{.push raises: [].}
|
2022-12-16 11:32:00 +00:00
|
|
|
|
|
|
|
import std/[options, deques, sequtils]
|
|
|
|
import chronos, metrics
|
2023-01-06 10:14:38 +00:00
|
|
|
import ../../../switch
|
2023-03-24 15:42:49 +00:00
|
|
|
import ../../../wire
|
2023-01-06 10:14:38 +00:00
|
|
|
import client
|
2023-04-18 10:50:21 +00:00
|
|
|
from core import NetworkReachability, AutonatUnreachableError
|
2023-01-06 10:14:38 +00:00
|
|
|
import ../../../utils/heartbeat
|
|
|
|
import ../../../crypto/crypto
|
|
|
|
|
2023-04-18 10:50:21 +00:00
|
|
|
export options, core.NetworkReachability
|
|
|
|
|
2023-01-06 10:14:38 +00:00
|
|
|
logScope:
|
|
|
|
topics = "libp2p autonatservice"
|
2022-12-16 11:32:00 +00:00
|
|
|
|
|
|
|
declarePublicGauge(libp2p_autonat_reachability_confidence, "autonat reachability confidence", labels = ["reachability"])
|
|
|
|
|
|
|
|
type
|
|
|
|
AutonatService* = ref object of Service
|
|
|
|
newConnectedPeerHandler: PeerEventHandler
|
2023-03-24 15:42:49 +00:00
|
|
|
addressMapper: AddressMapper
|
2022-12-16 11:32:00 +00:00
|
|
|
scheduleHandle: Future[void]
|
2023-04-18 10:50:21 +00:00
|
|
|
networkReachability*: NetworkReachability
|
2022-12-16 11:32:00 +00:00
|
|
|
confidence: Option[float]
|
|
|
|
answers: Deque[NetworkReachability]
|
2023-01-06 10:14:38 +00:00
|
|
|
autonatClient: AutonatClient
|
2022-12-16 11:32:00 +00:00
|
|
|
statusAndConfidenceHandler: StatusAndConfidenceHandler
|
|
|
|
rng: ref HmacDrbgContext
|
|
|
|
scheduleInterval: Option[Duration]
|
|
|
|
askNewConnectedPeers: bool
|
|
|
|
numPeersToAsk: int
|
|
|
|
maxQueueSize: int
|
|
|
|
minConfidence: float
|
|
|
|
dialTimeout: Duration
|
2023-03-24 15:42:49 +00:00
|
|
|
enableAddressMapper: bool
|
2022-12-16 11:32:00 +00:00
|
|
|
|
2023-06-07 11:12:49 +00:00
|
|
|
StatusAndConfidenceHandler* = proc (networkReachability: NetworkReachability, confidence: Option[float]): Future[void] {.gcsafe, raises: [].}
|
2022-12-16 11:32:00 +00:00
|
|
|
|
|
|
|
proc new*(
|
|
|
|
T: typedesc[AutonatService],
|
2023-01-06 10:14:38 +00:00
|
|
|
autonatClient: AutonatClient,
|
2022-12-16 11:32:00 +00:00
|
|
|
rng: ref HmacDrbgContext,
|
|
|
|
scheduleInterval: Option[Duration] = none(Duration),
|
|
|
|
askNewConnectedPeers = true,
|
|
|
|
numPeersToAsk: int = 5,
|
|
|
|
maxQueueSize: int = 10,
|
|
|
|
minConfidence: float = 0.3,
|
2023-03-24 15:42:49 +00:00
|
|
|
dialTimeout = 30.seconds,
|
|
|
|
enableAddressMapper = true): T =
|
2022-12-16 11:32:00 +00:00
|
|
|
return T(
|
|
|
|
scheduleInterval: scheduleInterval,
|
|
|
|
networkReachability: Unknown,
|
|
|
|
confidence: none(float),
|
|
|
|
answers: initDeque[NetworkReachability](),
|
2023-01-06 10:14:38 +00:00
|
|
|
autonatClient: autonatClient,
|
2022-12-16 11:32:00 +00:00
|
|
|
rng: rng,
|
|
|
|
askNewConnectedPeers: askNewConnectedPeers,
|
|
|
|
numPeersToAsk: numPeersToAsk,
|
|
|
|
maxQueueSize: maxQueueSize,
|
|
|
|
minConfidence: minConfidence,
|
2023-03-24 15:42:49 +00:00
|
|
|
dialTimeout: dialTimeout,
|
|
|
|
enableAddressMapper: enableAddressMapper)
|
2022-12-16 11:32:00 +00:00
|
|
|
|
|
|
|
proc callHandler(self: AutonatService) {.async.} =
|
|
|
|
if not isNil(self.statusAndConfidenceHandler):
|
|
|
|
await self.statusAndConfidenceHandler(self.networkReachability, self.confidence)
|
|
|
|
|
2023-01-24 16:04:42 +00:00
|
|
|
proc hasEnoughIncomingSlots(switch: Switch): bool =
|
|
|
|
# we leave some margin instead of comparing to 0 as a peer could connect to us while we are asking for the dial back
|
|
|
|
return switch.connManager.slotsAvailable(In) >= 2
|
|
|
|
|
2023-02-21 16:49:41 +00:00
|
|
|
proc doesPeerHaveIncomingConn(switch: Switch, peerId: PeerId): bool =
|
2023-03-08 11:30:19 +00:00
|
|
|
return switch.connManager.selectMuxer(peerId, In) != nil
|
2023-02-21 16:49:41 +00:00
|
|
|
|
2022-12-16 11:32:00 +00:00
|
|
|
proc handleAnswer(self: AutonatService, ans: NetworkReachability) {.async.} =
|
|
|
|
|
2022-12-23 15:49:25 +00:00
|
|
|
if ans == Unknown:
|
|
|
|
return
|
|
|
|
|
2022-12-16 11:32:00 +00:00
|
|
|
if self.answers.len == self.maxQueueSize:
|
|
|
|
self.answers.popFirst()
|
|
|
|
self.answers.addLast(ans)
|
|
|
|
|
|
|
|
self.networkReachability = Unknown
|
|
|
|
self.confidence = none(float)
|
|
|
|
const reachabilityPriority = [Reachable, NotReachable]
|
|
|
|
for reachability in reachabilityPriority:
|
|
|
|
let confidence = self.answers.countIt(it == reachability) / self.maxQueueSize
|
|
|
|
libp2p_autonat_reachability_confidence.set(value = confidence, labelValues = [$reachability])
|
|
|
|
if self.confidence.isNone and confidence >= self.minConfidence:
|
|
|
|
self.networkReachability = reachability
|
|
|
|
self.confidence = some(confidence)
|
|
|
|
|
2023-02-07 17:51:17 +00:00
|
|
|
debug "Current status", currentStats = $self.networkReachability, confidence = $self.confidence, answers = self.answers
|
2022-12-16 11:32:00 +00:00
|
|
|
|
2023-01-06 10:14:38 +00:00
|
|
|
proc askPeer(self: AutonatService, switch: Switch, peerId: PeerId): Future[NetworkReachability] {.async.} =
|
2023-01-24 16:04:42 +00:00
|
|
|
logScope:
|
|
|
|
peerId = $peerId
|
2023-02-21 16:49:41 +00:00
|
|
|
|
|
|
|
if doesPeerHaveIncomingConn(switch, peerId):
|
|
|
|
return Unknown
|
|
|
|
|
2023-01-24 16:04:42 +00:00
|
|
|
if not hasEnoughIncomingSlots(switch):
|
2023-02-07 17:51:17 +00:00
|
|
|
debug "No incoming slots available, not asking peer", incomingSlotsAvailable=switch.connManager.slotsAvailable(In)
|
2023-01-24 16:04:42 +00:00
|
|
|
return Unknown
|
|
|
|
|
2023-02-07 17:51:17 +00:00
|
|
|
trace "Asking peer for reachability"
|
2022-12-16 11:32:00 +00:00
|
|
|
let ans =
|
|
|
|
try:
|
2023-01-06 10:14:38 +00:00
|
|
|
discard await self.autonatClient.dialMe(switch, peerId).wait(self.dialTimeout)
|
2023-02-07 17:51:17 +00:00
|
|
|
debug "dialMe answer is reachable"
|
2022-12-16 11:32:00 +00:00
|
|
|
Reachable
|
2023-02-07 17:51:17 +00:00
|
|
|
except AutonatUnreachableError as error:
|
|
|
|
debug "dialMe answer is not reachable", msg = error.msg
|
2022-12-16 11:32:00 +00:00
|
|
|
NotReachable
|
2023-02-07 17:51:17 +00:00
|
|
|
except AsyncTimeoutError as error:
|
|
|
|
debug "dialMe timed out", msg = error.msg
|
2022-12-16 11:32:00 +00:00
|
|
|
Unknown
|
2023-02-07 17:51:17 +00:00
|
|
|
except CatchableError as error:
|
|
|
|
debug "dialMe unexpected error", msg = error.msg
|
2022-12-16 11:32:00 +00:00
|
|
|
Unknown
|
|
|
|
await self.handleAnswer(ans)
|
|
|
|
if not isNil(self.statusAndConfidenceHandler):
|
|
|
|
await self.statusAndConfidenceHandler(self.networkReachability, self.confidence)
|
2023-03-24 15:42:49 +00:00
|
|
|
await switch.peerInfo.update()
|
2022-12-16 11:32:00 +00:00
|
|
|
return ans
|
|
|
|
|
|
|
|
proc askConnectedPeers(self: AutonatService, switch: Switch) {.async.} =
|
2023-02-07 17:51:17 +00:00
|
|
|
trace "Asking peers for reachability"
|
2022-12-16 11:32:00 +00:00
|
|
|
var peers = switch.connectedPeers(Direction.Out)
|
|
|
|
self.rng.shuffle(peers)
|
|
|
|
var answersFromPeers = 0
|
|
|
|
for peer in peers:
|
|
|
|
if answersFromPeers >= self.numPeersToAsk:
|
|
|
|
break
|
2023-01-24 16:04:42 +00:00
|
|
|
if not hasEnoughIncomingSlots(switch):
|
|
|
|
debug "No incoming slots available, not asking peers", incomingSlotsAvailable=switch.connManager.slotsAvailable(In)
|
|
|
|
break
|
|
|
|
if (await askPeer(self, switch, peer)) != Unknown:
|
2022-12-16 11:32:00 +00:00
|
|
|
answersFromPeers.inc()
|
|
|
|
|
|
|
|
proc schedule(service: AutonatService, switch: Switch, interval: Duration) {.async.} =
|
2023-02-07 17:51:17 +00:00
|
|
|
heartbeat "Scheduling AutonatService run", interval:
|
2022-12-16 11:32:00 +00:00
|
|
|
await service.run(switch)
|
|
|
|
|
2023-03-24 15:42:49 +00:00
|
|
|
proc addressMapper(
|
|
|
|
self: AutonatService,
|
|
|
|
peerStore: PeerStore,
|
|
|
|
listenAddrs: seq[MultiAddress]): Future[seq[MultiAddress]] {.gcsafe, async.} =
|
|
|
|
|
|
|
|
if self.networkReachability != NetworkReachability.Reachable:
|
|
|
|
return listenAddrs
|
|
|
|
|
|
|
|
var addrs = newSeq[MultiAddress]()
|
|
|
|
for listenAddr in listenAddrs:
|
|
|
|
var processedMA = listenAddr
|
|
|
|
try:
|
|
|
|
let hostIP = initTAddress(listenAddr).get()
|
|
|
|
if not hostIP.isGlobal() and self.networkReachability == NetworkReachability.Reachable:
|
|
|
|
processedMA = peerStore.guessDialableAddr(listenAddr) # handle manual port forwarding
|
|
|
|
except CatchableError as exc:
|
|
|
|
debug "Error while handling address mapper", msg = exc.msg
|
|
|
|
addrs.add(processedMA)
|
|
|
|
return addrs
|
|
|
|
|
2022-12-16 11:32:00 +00:00
|
|
|
method setup*(self: AutonatService, switch: Switch): Future[bool] {.async.} =
|
2023-03-24 15:42:49 +00:00
|
|
|
self.addressMapper = proc (listenAddrs: seq[MultiAddress]): Future[seq[MultiAddress]] {.gcsafe, async.} =
|
|
|
|
return await addressMapper(self, switch.peerStore, listenAddrs)
|
|
|
|
|
2023-02-07 17:51:17 +00:00
|
|
|
info "Setting up AutonatService"
|
2022-12-16 11:32:00 +00:00
|
|
|
let hasBeenSetup = await procCall Service(self).setup(switch)
|
|
|
|
if hasBeenSetup:
|
|
|
|
if self.askNewConnectedPeers:
|
|
|
|
self.newConnectedPeerHandler = proc (peerId: PeerId, event: PeerEvent): Future[void] {.async.} =
|
|
|
|
discard askPeer(self, switch, peerId)
|
|
|
|
switch.connManager.addPeerEventHandler(self.newConnectedPeerHandler, PeerEventKind.Joined)
|
|
|
|
if self.scheduleInterval.isSome():
|
|
|
|
self.scheduleHandle = schedule(self, switch, self.scheduleInterval.get())
|
2023-03-24 15:42:49 +00:00
|
|
|
if self.enableAddressMapper:
|
|
|
|
switch.peerInfo.addressMappers.add(self.addressMapper)
|
2022-12-16 11:32:00 +00:00
|
|
|
return hasBeenSetup
|
|
|
|
|
|
|
|
method run*(self: AutonatService, switch: Switch) {.async, public.} =
|
2023-02-07 17:51:17 +00:00
|
|
|
trace "Running AutonatService"
|
2022-12-16 11:32:00 +00:00
|
|
|
await askConnectedPeers(self, switch)
|
|
|
|
await self.callHandler()
|
|
|
|
|
|
|
|
method stop*(self: AutonatService, switch: Switch): Future[bool] {.async, public.} =
|
2023-02-07 17:51:17 +00:00
|
|
|
info "Stopping AutonatService"
|
2022-12-16 11:32:00 +00:00
|
|
|
let hasBeenStopped = await procCall Service(self).stop(switch)
|
|
|
|
if hasBeenStopped:
|
|
|
|
if not isNil(self.scheduleHandle):
|
|
|
|
self.scheduleHandle.cancel()
|
|
|
|
self.scheduleHandle = nil
|
|
|
|
if not isNil(self.newConnectedPeerHandler):
|
|
|
|
switch.connManager.removePeerEventHandler(self.newConnectedPeerHandler, PeerEventKind.Joined)
|
2023-03-24 15:42:49 +00:00
|
|
|
if self.enableAddressMapper:
|
|
|
|
switch.peerInfo.addressMappers.keepItIf(it != self.addressMapper)
|
|
|
|
await switch.peerInfo.update()
|
2022-12-16 11:32:00 +00:00
|
|
|
return hasBeenStopped
|
|
|
|
|
|
|
|
proc statusAndConfidenceHandler*(self: AutonatService, statusAndConfidenceHandler: StatusAndConfidenceHandler) =
|
|
|
|
self.statusAndConfidenceHandler = statusAndConfidenceHandler
|