Skip to content

Commit

Permalink
Routed host searches for new addrs issue libp2p#351
Browse files Browse the repository at this point in the history
If there were addresses available for a given peer,
and they did not work, an err would be returned.
This doesn't make sense as there should be an attempt
to find new addresses through the router before determining
that a connection cannot be made.

Now the router is searched if a connection with the current
addresses cannot be made. If the router had already been
searched(This happens if no addresses were present in the peerinfo)
then we do not search repeat the search as it doesn't to
search the router twice within such a short timespan.
  • Loading branch information
jmintb committed Jun 24, 2018
1 parent 1198616 commit 3f77c5d
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion p2p/host/routed/routed.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,11 @@ func (rh *RoutedHost) Connect(ctx context.Context, pi pstore.PeerInfo) error {

// Check if we have some addresses in our recent memory.
addrs := rh.Peerstore().Addrs(pi.ID)
hasSearched := false // Used to determine if we have used to router to search for addresses.

if len(addrs) < 1 {
// no addrs? find some with the routing system.
hasSearched = true
var err error
addrs, err = rh.findPeerAddrs(ctx, pi.ID)
if err != nil {
Expand All @@ -69,7 +72,48 @@ func (rh *RoutedHost) Connect(ctx context.Context, pi pstore.PeerInfo) error {

// if we're here, we got some addrs. let's use our wrapped host to connect.
pi.Addrs = addrs
return rh.host.Connect(ctx, pi)
connErr := rh.host.Connect(ctx, pi)

// If we could not connect with the addresses that we already had, we use
// the router to search for new addresses. Unless we have already searched for
// new addresses, then there is no reason to search again.
if connErr != nil && hasSearched {
return connErr
} else if connErr != nil {
newAddrs, findErr := rh.findPeerAddrs(ctx, pi.ID)

if findErr != nil {
return findErr // We could not find any addresses.
}

// If we have found new addresses we attempt to connect.
if hasNewAddr(pi.Addrs, newAddrs) {
pi.Addrs = addrs
return rh.host.Connect(ctx, pi)
}
}

return nil
}

func hasNewAddr(oldAddrs, newAddrs []ma.Multiaddr) bool {
for _, addr := range newAddrs {
if !hasAddr(addr, oldAddrs) {
return true
}
}

return false
}

func hasAddr(addr ma.Multiaddr, addrs []ma.Multiaddr) bool {
for _, addr2 := range addrs {
if addr2 == addr {
return true
}
}

return false
}

func (rh *RoutedHost) findPeerAddrs(ctx context.Context, id peer.ID) ([]ma.Multiaddr, error) {
Expand Down

0 comments on commit 3f77c5d

Please sign in to comment.