Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 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
25 changes: 25 additions & 0 deletions libp2p/multiaddress.nim
Original file line number Diff line number Diff line change
Expand Up @@ -587,10 +587,28 @@ proc getPart(ma: MultiAddress, index: int): MaResult[MultiAddress] =
inc(offset)
ok(res)

proc getParts[U, V](ma: MultiAddress, slice: HSlice[U, V]): MaResult[MultiAddress] =
when slice.a is BackwardsIndex or slice.b is BackwardsIndex:
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)
var res: MultiAddress
for i in indexStart..indexEnd:
? res.append(? ma[i])
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 Expand Up @@ -627,6 +645,13 @@ iterator items*(ma: MultiAddress): MaResult[MultiAddress] =
res.data.finish()
yield ok(MaResult[MultiAddress], res)

proc len*(ma: MultiAddress): MaResult[int] =
var counter: int
for part in ma:
if part.isErr: return err(part.error)
counter.inc()
ok(counter)

proc contains*(ma: MultiAddress, codec: MultiCodec): MaResult[bool] {.inline.} =
## Returns ``true``, if address with MultiCodec ``codec`` present in
## MultiAddress ``ma``.
Expand Down
Loading