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 8 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
40 changes: 40 additions & 0 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 Down Expand Up @@ -185,6 +186,45 @@ proc negotiateStream(

return conn

method canDial*(
self: Dialer,
peerId: PeerId,
addrs: seq[MultiAddress],
protos: seq[string]): 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, protos
for address in addrs: # for each address
let
hostname = address.getHostname()
resolvedAddresses =
if isNil(self.nameResolver): @[address]
else: await self.nameResolver.resolveMAddress(address)

for a in resolvedAddresses: # for each resolved address
for transport in self.transports: # for each transport
if transport.handles(a): # check if it can dial it
trace "Dialing address", address = $a, peerId, hostname
try:
let dialed = await transport.dial(hostname, address)
defer: await dialed.close()
# make sure to assign the peer to the connection
dialed.peerId = peerId
# also keep track of the connection's bottom unsafe transport direction
# required by gossipsub scoring
dialed.transportDir = Direction.Out
let sconn = await transport.upgrader.secure(dialed)
await sconn.close()
return sconn.observedAddr
except CancelledError as exc:
raise exc
except CatchableError as exc:
continue # Try the next address
raise newException(DialFailedError, "Dial failed")

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