Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autonat protocol #739

Merged
merged 22 commits into from
Aug 23, 2022
Merged
Show file tree
Hide file tree
Changes from 14 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
11 changes: 10 additions & 1 deletion libp2p/builders.nim
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import
switch, peerid, peerinfo, stream/connection, multiaddress,
crypto/crypto, transports/[transport, tcptransport],
muxers/[muxer, mplex/mplex, yamux/yamux],
protocols/[identify, secure/secure, secure/noise, relay],
protocols/[identify, secure/secure, secure/noise, relay, autonat],
connmanager, upgrademngrs/muxedupgrade,
nameresolving/nameresolver,
errors, utility
Expand Down Expand Up @@ -58,6 +58,7 @@ type
agentVersion: string
nameResolver: NameResolver
peerStoreCapacity: Option[int]
autonat: bool
isCircuitRelay: bool
circuitRelayCanHop: bool

Expand Down Expand Up @@ -185,6 +186,10 @@ proc withNameResolver*(b: SwitchBuilder, nameResolver: NameResolver): SwitchBuil
b.nameResolver = nameResolver
b

proc withAutonat*(b: SwitchBuilder): SwitchBuilder =
b.autonat = true
b

proc withRelayTransport*(b: SwitchBuilder, canHop: bool): SwitchBuilder =
b.isCircuitRelay = true
b.circuitRelayCanHop = canHop
Expand Down Expand Up @@ -255,6 +260,10 @@ proc build*(b: SwitchBuilder): Switch
nameResolver = b.nameResolver,
peerStore = peerStore)

if b.autonat:
let autonat = Autonat.new(switch)
switch.mount(autonat)

if b.isCircuitRelay:
let relay = Relay.new(switch, b.circuitRelayCanHop)
switch.mount(relay)
Expand Down
6 changes: 6 additions & 0 deletions libp2p/dial.nim
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,9 @@ method addTransport*(
self: Dial,
transport: Transport) {.base.} =
doAssert(false, "Not implemented!")

method tryDial*(
self: Dial,
peerId: PeerId,
addrs: seq[MultiAddress]): Future[MultiAddress] {.async, base.} =
doAssert(false, "Not implemented!")
42 changes: 28 additions & 14 deletions libp2p/dialer.nim
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import dial,
stream/connection,
transports/transport,
nameresolving/nameresolver,
upgrademngrs/upgrade,
errors

export dial, errors
Expand All @@ -47,8 +48,7 @@ type
proc dialAndUpgrade(
self: Dialer,
peerId: PeerId,
addrs: seq[MultiAddress],
forceDial: bool):
addrs: seq[MultiAddress]):
Future[Connection] {.async.} =
debug "Dialing peer", peerId

Expand All @@ -65,17 +65,7 @@ proc dialAndUpgrade(
trace "Dialing address", address = $a, peerId, hostname
let dialed = try:
libp2p_total_dial_attempts.inc()
# await a connection slot when the total
# connection count is equal to `maxConns`
#
# Need to copy to avoid "cannot be captured" errors in Nim-1.4.x.
let
transportCopy = transport
addressCopy = a
await self.connManager.trackOutgoingConn(
() => transportCopy.dial(hostname, addressCopy),
forceDial
)
await transport.dial(hostname, a)
except TooManyConnectionsError as exc:
trace "Connection limit reached!"
raise exc
Expand Down Expand Up @@ -139,7 +129,10 @@ proc internalConnect(
trace "Reusing existing connection", conn, direction = $conn.dir
return conn

conn = await self.dialAndUpgrade(peerId, addrs, forceDial)
conn = await self.connManager.trackOutgoingConn(
() => self.dialAndUpgrade(peerId, addrs),
forceDial
)
if isNil(conn): # None of the addresses connected
raise newException(DialFailedError, "Unable to establish outgoing link")

Expand Down Expand Up @@ -185,6 +178,27 @@ proc negotiateStream(

return conn

method tryDial*(
self: Dialer,
peerId: PeerId,
addrs: seq[MultiAddress]): Future[MultiAddress] {.raises: [Defect], async.} =
## Create a protocol stream and in order to check
## if a connection is possible.
## Doesn't use the Connection Manager to save it.
##

trace "Check if it can dial", peerId, addrs
try:
let conn = await self.dialAndUpgrade(peerId, addrs)
if conn.isNil():
raise newException(DialFailedError, "No valid multiaddress")
await conn.close()
return conn.observedAddr
except CancelledError as exc:
raise exc
except CatchableError as exc:
raise newException(DialFailedError, exc.msg)

method dial*(
self: Dialer,
peerId: PeerId,
Expand Down
73 changes: 73 additions & 0 deletions libp2p/multiaddress.nim
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,28 @@ proc protoAddress*(ma: MultiAddress): MaResult[seq[byte]] =
buffer.setLen(res)
ok(buffer)

proc len*(ma: MultiAddress): MaResult[int] =
var counter: int = 0
var header: uint64
var vb = ma
var data = newSeq[byte]()

while len(vb.data) > 0:
if vb.data.readVarint(header) == -1:
return err("multiaddress: Malformed binary address!")
let proto = CodeAddresses.getOrDefault(MultiCodec(header))
if proto.kind == None:
return err("multiaddress: Unsupported protocol '" & $header & "'")
elif proto.kind == Fixed:
data.setLen(proto.size)
if vb.data.readArray(data) != proto.size:
return err("multiaddress: Decoding protocol error")
elif proto.kind in {Length, Path}:
if vb.data.readSeq(data) == -1:
return err("multiaddress: Decoding protocol error")
counter.inc()
ok(counter)

proc getPart(ma: MultiAddress, index: int): MaResult[MultiAddress] =
var header: uint64
var data = newSeq[byte]()
Expand Down Expand Up @@ -587,10 +609,61 @@ proc getPart(ma: MultiAddress, index: int): MaResult[MultiAddress] =
inc(offset)
ok(res)

proc getParts[U, V](ma: MultiAddress, slice: HSlice[U, V]): MaResult[MultiAddress] =
let maLength = ? len(ma)
template normalizeIndex(index): int =
when index is BackwardsIndex: maLength - int(index)
else: int(index)
let
indexStart = normalizeIndex(slice.a)
indexEnd = normalizeIndex(slice.b)
if indexStart notin 0..<maLength or indexEnd notin indexStart..<maLength:
return err("multiaddress: index out of bound")
var
header: uint64
data = newSeq[byte]()
offset = 0
vb = ma
res: MultiAddress
res.data = initVBuffer()
while offset <= indexEnd:
if vb.data.readVarint(header) == -1:
return err("multiaddress: Malformed binary address!")

let proto = CodeAddresses.getOrDefault(MultiCodec(header))
if proto.kind == None:
return err("multiaddress: Unsupported protocol '" & $header & "'")

elif proto.kind == Fixed:
data.setLen(proto.size)
if vb.data.readArray(data) != proto.size:
return err("multiaddress: Decoding protocol error")

if offset in indexStart..indexEnd:
res.data.writeVarint(header)
res.data.writeArray(data)
elif proto.kind in {Length, Path}:
if vb.data.readSeq(data) == -1:
return err("multiaddress: Decoding protocol error")

if offset in indexStart..indexEnd:
res.data.writeVarint(header)
res.data.writeSeq(data)
elif proto.kind == Marker:
if offset in indexStart..indexEnd:
res.data.writeVarint(header)
inc(offset)
res.data.finish()
ok(res)

proc `[]`*(ma: MultiAddress, i: int): MaResult[MultiAddress] {.inline.} =
## Returns part with index ``i`` of MultiAddress ``ma``.
ma.getPart(i)

proc `[]`*(ma: MultiAddress, slice: HSlice): MaResult[MultiAddress] {.inline.} =
## Returns parts with slice ``slice`` of MultiAddress ``ma``.
ma.getParts(slice)

iterator items*(ma: MultiAddress): MaResult[MultiAddress] =
## Iterates over all addresses inside of MultiAddress ``ma``.
var header: uint64
Expand Down
Loading