Skip to content

RoutedHost: NewStream ensures we have the means to connect to the peer #208

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

Merged
merged 2 commits into from
Jul 23, 2017
Merged
Changes from all 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
33 changes: 25 additions & 8 deletions p2p/host/routed/routed.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,25 +59,34 @@ 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)
if len(addrs) < 1 {

// no addrs? find some with the routing system.
pi2, err := rh.route.FindPeer(ctx, pi.ID)
var err error
addrs, err = rh.findPeerAddrs(ctx, pi.ID)
if err != nil {
return err // couldnt find any :(
}
if pi2.ID != pi.ID {
err = fmt.Errorf("routing failure: provided addrs for different peer")
logRoutingErrDifferentPeers(ctx, pi.ID, pi2.ID, err)
return err
}
addrs = pi2.Addrs
}

// 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)
}

func (rh *RoutedHost) findPeerAddrs(ctx context.Context, id peer.ID) ([]ma.Multiaddr, error) {
pi, err := rh.route.FindPeer(ctx, id)
if err != nil {
return nil, err // couldnt find any :(
}

if pi.ID != id {
err = fmt.Errorf("routing failure: provided addrs for different peer")
logRoutingErrDifferentPeers(ctx, id, pi.ID, err)
return nil, err
}

return pi.Addrs, nil
}

func logRoutingErrDifferentPeers(ctx context.Context, wanted, got peer.ID, err error) {
lm := make(lgbl.DeferredMap)
lm["error"] = err
Expand Down Expand Up @@ -119,6 +128,14 @@ func (rh *RoutedHost) RemoveStreamHandler(pid protocol.ID) {
}

func (rh *RoutedHost) NewStream(ctx context.Context, p peer.ID, pids ...protocol.ID) (inet.Stream, error) {
// Ensure we have a connection, with peer addresses resolved by the routing system (#207)
// It is not sufficient to let the underlying host connect, it will most likely not have
// any addresses for the peer without any prior connections.
err := rh.Connect(ctx, pstore.PeerInfo{ID: p})
if err != nil {
return nil, err
}

return rh.host.NewStream(ctx, p, pids...)
}
func (rh *RoutedHost) Close() error {
Expand Down