Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 23 additions & 7 deletions codex/codex.nim
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,10 @@ import ./contracts
import ./systemclock
import ./contracts/clock
import ./contracts/deployment
import ./utils/addrutils
import ./namespaces
import ./codextypes
import ./logutils
import ./nat
import ./nat/reachabilitymanager

logScope:
topics = "codex node"
Expand All @@ -57,6 +56,7 @@ type
repoStore: RepoStore
maintenance: BlockMaintainer
taskpool: Taskpool
reachabilityManager: ReachabilityManager

CodexPrivateKey* = libp2p.PrivateKey # alias
EthWallet = ethers.Wallet
Expand Down Expand Up @@ -166,12 +166,18 @@ proc start*(s: CodexServer) {.async.} =

await s.codexNode.switch.start()

let (announceAddrs, discoveryAddrs) = nattedAddress(
s.config.nat, s.codexNode.switch.peerInfo.addrs, s.config.discoveryPort
)
s.reachabilityManager.getAnnounceRecords = some proc(): ?seq[MultiAddress] =
s.codexNode.switch.peerInfo.addrs.some
s.reachabilityManager.getDiscoveryRecords = some proc(): ?seq[MultiAddress] =
if dhtRecord =? s.codexNode.discovery.dhtRecord:
return dhtRecord.data.addresses.mapIt(it.address).some

s.reachabilityManager.updateAnnounceRecords = some proc(records: seq[MultiAddress]) =
s.codexNode.discovery.updateAnnounceRecord(records)
s.reachabilityManager.updateDiscoveryRecords = some proc(records: seq[MultiAddress]) =
s.codexNode.discovery.updateDhtRecord(records)

s.codexNode.discovery.updateAnnounceRecord(announceAddrs)
s.codexNode.discovery.updateDhtRecord(discoveryAddrs)
await s.reachabilityManager.start(s.codexNode.switch, s.config.bootstrapNodes)

await s.bootstrapInteractions()
await s.codexNode.start()
Expand All @@ -183,6 +189,7 @@ proc stop*(s: CodexServer) {.async.} =
let res = await noCancel allFinishedFailed[void](
@[
s.restServer.stop(),
s.reachabilityManager.stop(),
s.codexNode.switch.stop(),
s.codexNode.stop(),
s.repoStore.stop(),
Expand All @@ -201,6 +208,9 @@ proc new*(
T: type CodexServer, config: CodexConf, privateKey: CodexPrivateKey
): CodexServer =
## create CodexServer including setting up datastore, repostore, etc

let reachabilityManager = ReachabilityManager.new(config.forcePortMapping)

let switch = SwitchBuilder
.new()
.withPrivateKey(privateKey)
Expand All @@ -212,6 +222,11 @@ proc new*(
.withAgentVersion(config.agentString)
.withSignedPeerRecord(true)
.withTcpTransport({ServerFlags.ReuseAddr})
# Adds AutoNAT server support - ability to respond to other peers ask about their reachability status
.withAutonat()

# Adds AutoNAT client support - to discover the node's rechability
.withServices(@[reachabilityManager.getAutonatService()])
.build()

var
Expand Down Expand Up @@ -338,4 +353,5 @@ proc new*(
repoStore: repoStore,
maintenance: maintenance,
taskpool: taskpool,
reachabilityManager: reachabilityManager,
)
49 changes: 18 additions & 31 deletions codex/conf.nim
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,13 @@ import ./logutils
import ./stores
import ./units
import ./utils
import ./nat
import ./utils/natutils
import ./nat/port_mapping

from ./contracts/config import DefaultRequestCacheSize, DefaultMaxPriorityFeePerGas
from ./validationconfig import MaxSlots, ValidationGroups

export units, net, codextypes, logutils, completeCmdArg, parseCmdArg, NatConfig
export ValidationGroups, MaxSlots
export units, net, codextypes, logutils, completeCmdArg, parseCmdArg
export ValidationGroups, MaxSlots, PortMappingStrategy

export
DefaultQuotaBytes, DefaultBlockTtl, DefaultBlockInterval, DefaultNumBlocksPerInterval,
Expand Down Expand Up @@ -151,14 +150,14 @@ type
name: "listen-addrs"
.}: seq[MultiAddress]

nat* {.
forcePortMapping* {.
desc:
"Specify method to use for determining public address. " &
"Must be one of: any, none, upnp, pmp, extip:<IP>",
defaultValue: defaultNatConfig(),
"Overide automatic detection to specific upnp mode. " &
"Must be one of: any, none, upnp, pmp",
defaultValue: PortMappingStrategy.Any,
defaultValueDesc: "any",
name: "nat"
.}: NatConfig
name: "force-port-mapping"
.}: PortMappingStrategy

discoveryPort* {.
desc: "Discovery (UDP) port",
Expand Down Expand Up @@ -464,9 +463,6 @@ logutils.formatIt(LogFormat.json, EthAddress):
func defaultAddress*(conf: CodexConf): IpAddress =
result = static parseIpAddress("127.0.0.1")

func defaultNatConfig*(): NatConfig =
result = NatConfig(hasExtIp: false, nat: NatStrategy.NatAny)

func persistence*(self: CodexConf): bool =
self.cmd == StartUpCmd.persistence

Expand Down Expand Up @@ -538,29 +534,20 @@ proc parseCmdArg*(T: type SignedPeerRecord, uri: string): T =
quit QuitFailure
res

func parseCmdArg*(T: type NatConfig, p: string): T {.raises: [ValueError].} =
func parseCmdArg*(T: type PortMappingStrategy, p: string): T {.raises: [ValueError].} =
case p.toLowerAscii
of "any":
NatConfig(hasExtIp: false, nat: NatStrategy.NatAny)
PortMappingStrategy.Any
of "none":
NatConfig(hasExtIp: false, nat: NatStrategy.NatNone)
PortMappingStrategy.None
of "upnp":
NatConfig(hasExtIp: false, nat: NatStrategy.NatUpnp)
PortMappingStrategy.Upnp
of "pmp":
NatConfig(hasExtIp: false, nat: NatStrategy.NatPmp)
PortMappingStrategy.Pmp
else:
if p.startsWith("extip:"):
try:
let ip = parseIpAddress(p[6 ..^ 1])
NatConfig(hasExtIp: true, extIp: ip)
except ValueError:
let error = "Not a valid IP address: " & p[6 ..^ 1]
raise newException(ValueError, error)
else:
let error = "Not a valid NAT option: " & p
raise newException(ValueError, error)
raise newException(ValueError, "Not a valid NAT option: " & p)

proc completeCmdArg*(T: type NatConfig, val: string): seq[string] =
proc completeCmdArg*(T: type PortMappingStrategy, val: string): seq[string] =
return @[]

proc parseCmdArg*(T: type EthAddress, address: string): T =
Expand Down Expand Up @@ -642,11 +629,11 @@ proc readValue*(
val = dur

proc readValue*(
r: var TomlReader, val: var NatConfig
r: var TomlReader, val: var PortMappingStrategy
) {.raises: [SerializationError].} =
val =
try:
parseCmdArg(NatConfig, r.readValue(string))
parseCmdArg(PortMappingStrategy, r.readValue(string))
except CatchableError as err:
raise newException(SerializationError, err.msg)

Expand Down
Loading
Loading