Compare commits

...

6 Commits

Author SHA1 Message Date
Tanguy
3874c57395 Merge remote-tracking branch 'origin/unstable' into autoupnp 2022-11-08 17:23:59 +01:00
Tanguy
5eca4e2131 Nat auto mapper 2022-09-15 16:40:51 +02:00
Tanguy
4946ee5fa9 Merge remote-tracking branch 'origin/unstable' into publicaddressmapping 2022-09-15 13:48:03 +02:00
Tanguy
ebe342c766 fix CI 2022-09-12 16:16:47 +02:00
Tanguy
901f55c680 Allow public address mapping 2022-09-12 14:09:59 +02:00
Tanguy
7e4b69bfb2 Fix compilation on devel 2022-09-12 14:09:04 +02:00
5 changed files with 101 additions and 12 deletions

View File

@@ -6,6 +6,7 @@ faststreams;https://github.com/status-im/nim-faststreams@#6112432b3a81d9db116cd5
httputils;https://github.com/status-im/nim-http-utils@#e88e231dfcef4585fe3b2fbd9b664dbd28a88040
json_serialization;https://github.com/status-im/nim-json-serialization@#e5b18fb710c3d0167ec79f3b892f5a7a1bc6d1a4
metrics;https://github.com/status-im/nim-metrics@#0a6477268e850d7bc98347b3875301524871765f
nat_mapper;https://github.com/status-im/nim-nat-mapper@#31c7e280c65c8e0816d82978e710464399f6cd6c
nimcrypto;https://github.com/cheatfate/nimcrypto@#24e006df85927f64916e60511620583b11403178
secp256k1;https://github.com/status-im/nim-secp256k1@#c7f1a37d9b0f17292649bfed8bf6cef83cf4221f
serialization;https://github.com/status-im/nim-serialization@#60a5bd8ac0461dfadd3069fd9c01a7734f205995
@@ -13,4 +14,4 @@ stew;https://github.com/status-im/nim-stew@#23da07c9b59c0ba3d4efa7e4e6e2c4121ae5
testutils;https://github.com/status-im/nim-testutils@#dfc4c1b39f9ded9baf6365014de2b4bfb4dafc34
unittest2;https://github.com/status-im/nim-unittest2@#da8398c45cafd5bd7772da1fc96e3924a18d3823
websock;https://github.com/status-im/nim-websock@#acbe30e9ca1e51dcbbfe4c552ee6f16c7eede538
zlib;https://github.com/status-im/nim-zlib@#6a6670afba6b97b29b920340e2641978c05ab4d8
zlib;https://github.com/status-im/nim-zlib@#6a6670afba6b97b29b920340e2641978c05ab4d8

View File

@@ -5,9 +5,10 @@ import
strformat, strutils,
stew/byteutils,
chronos,
libp2p
libp2p,
libp2p/protocols/connectivity/nat_auto_mapper
const DefaultAddr = "/ip4/127.0.0.1/tcp/0"
const DefaultAddr = "/ip4/0.0.0.0/tcp/0"
const Help = """
Commands: /[?|help|connect|disconnect|exit]
@@ -178,11 +179,14 @@ proc main() {.async.} =
.withNoise() # Use Noise as secure manager
.build()
let chat = Chat(
switch: switch,
stdinReader: stdinReader)
let
chat = Chat(
switch: switch,
stdinReader: stdinReader)
natAutoMapper = NatAutoMapper.new(switch.peerInfo)
switch.mount(ChatProto.new(chat))
switch.mount(natAutoMapper)
await switch.start()

View File

@@ -13,6 +13,7 @@ requires "nim >= 1.2.0",
"bearssl >= 0.1.4",
"chronicles >= 0.10.2",
"chronos >= 3.0.6",
"https://github.com/status-im/nim-nat-mapper",
"metrics",
"secp256k1",
"stew#head",

View File

@@ -0,0 +1,86 @@
# Nim-LibP2P
# Copyright (c) 2022 Status Research & Development GmbH
# 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.
import std/[sequtils, strutils, tables]
import pkg/[
chronos, chronicles, nat_mapper
]
import ../protocol,
../../peerinfo,
../../multiaddress,
../../wire,
../../multicodec
when (NimMajor, NimMinor) < (1, 4):
{.push raises: [Defect].}
else:
{.push raises: [].}
logScope:
topics = "libp2p nat_auto_mapper"
type
NatAutoMapper* = ref object of LPProtocol
mappingManager*: MappingManager
peerInfo*: PeerInfo
proc toPortMappings(mas: seq[MultiAddress]): Table[MultiAddress, PortMapping] =
for ma in mas:
let ta = initTAddress(ma)
if ta.isErr: continue
try:
if ta.get().address() != IPv4_any(): continue
except ValueError: continue
var mapping = PortMapping(port: ta.get.port.int)
if (multiCodec("udp") in ma) == MaResult[bool].ok(true):
mapping.protocol = NatProtocolType.Udp
result[ma] = mapping
elif (multiCodec("tcp") in ma) == MaResult[bool].ok(true):
mapping.protocol = NatProtocolType.Tcp
result[ma] = mapping
proc mapAddress(p: NatAutoMapper, addrs: seq[MultiAddress]): Future[seq[MultiAddress]] {.async.} =
debug "Mapping addresses", addrs
try:
let mappings = addrs.toPortMappings()
if mappings.len == 0:
return addrs
var resAddrs = addrs.filterIt(it notin mappings)
debug "Creating mappings", count=mappings.len
await p.mappingManager.setMappings(toSeq(mappings.values))
let
publicIp = await p.mappingManager.publicIp()
publicIpMa =
MultiAddress.init(multiCodec("ip4"), publicIp.address_v4).tryGet()
for ma, _ in mappings:
resAddrs &= publicIpMa & ma[1..^1].tryGet()
return resAddrs
except CatchableError as exc:
info "Failed to map addresses", err = exc.msg, addrs
return addrs
method stop*(p: NatAutoMapper) {.async.} =
await procCall LPProtocol(p).stop()
if not isNil(p.mappingManager):
await p.mappingManager.stop()
proc new*(T: type[NatAutoMapper], peerInfo: PeerInfo): T =
let res = T(mappingManager: MappingManager.new(), peerInfo: peerInfo)
#TODO consider a LPProtocol "early start" instead
peerInfo.addressMappers &=
proc(listenAddrs: seq[MultiAddress]): Future[seq[MultiAddress]] {.async.} =
return await res.mapAddress(listenAddrs)
res

View File

@@ -175,19 +175,16 @@ proc mount*[T: LPProtocol](s: Switch, proto: T, matcher: Matcher = nil)
{.gcsafe, raises: [Defect, LPError], public.} =
## mount a protocol to the switch
if isNil(proto.handler):
if proto.codecs.len > 0 and isNil(proto.handler):
raise newException(LPError,
"Protocol has to define a handle method or proc")
if proto.codec.len == 0:
raise newException(LPError,
"Protocol has to define a codec string")
if s.started and not proto.started:
raise newException(LPError, "Protocol not started")
s.ms.addHandler(proto.codecs, proto, matcher)
s.peerInfo.protocols.add(proto.codec)
for codec in proto.codecs:
s.peerInfo.protocols.add(codec)
proc upgradeMonitor(conn: Connection, upgrades: AsyncSemaphore) {.async.} =
## monitor connection for upgrades