lookup.go 1.54 KB
Newer Older
1 2 3
package dht

import (
Jeromy's avatar
Jeromy committed
4
	"context"
Steven Allen's avatar
Steven Allen committed
5
	"fmt"
Michael Avila's avatar
Michael Avila committed
6
	"time"
Jeromy's avatar
Jeromy committed
7

8
	"github.com/libp2p/go-libp2p-core/peer"
9
	"github.com/libp2p/go-libp2p-core/routing"
10

George Antoniadis's avatar
George Antoniadis committed
11
	kb "github.com/libp2p/go-libp2p-kbucket"
12 13
)

Alan Shaw's avatar
Alan Shaw committed
14 15
// GetClosestPeers is a Kademlia 'node lookup' operation. Returns a channel of
// the K closest peers to the given key.
16 17 18
//
// If the context is canceled, this function will return the context error along
// with the closest K peers it has found so far.
19
func (dht *IpfsDHT) GetClosestPeers(ctx context.Context, key string) ([]peer.ID, error) {
Steven Allen's avatar
Steven Allen committed
20 21 22
	if key == "" {
		return nil, fmt.Errorf("can't lookup empty key")
	}
23
	//TODO: I can break the interface! return []peer.ID
Aarsh Shah's avatar
Aarsh Shah committed
24
	lookupRes, err := dht.runLookupWithFollowup(ctx, key,
Adin Schmahmann's avatar
Adin Schmahmann committed
25 26 27 28 29 30 31
		func(ctx context.Context, p peer.ID) ([]*peer.AddrInfo, error) {
			// For DHT query command
			routing.PublishQueryEvent(ctx, &routing.QueryEvent{
				Type: routing.SendingQuery,
				ID:   p,
			})

32
			peers, err := dht.protoMessenger.GetClosestPeers(ctx, p, peer.ID(key))
Adin Schmahmann's avatar
Adin Schmahmann committed
33 34 35 36
			if err != nil {
				logger.Debugf("error getting closer peers: %s", err)
				return nil, err
			}
37

Adin Schmahmann's avatar
Adin Schmahmann committed
38 39 40 41 42 43
			// For DHT query command
			routing.PublishQueryEvent(ctx, &routing.QueryEvent{
				Type:      routing.PeerResponse,
				ID:        p,
				Responses: peers,
			})
44

Adin Schmahmann's avatar
Adin Schmahmann committed
45 46
			return peers, err
		},
Adin Schmahmann's avatar
Adin Schmahmann committed
47
		func() bool { return false },
Adin Schmahmann's avatar
Adin Schmahmann committed
48
	)
Jeromy's avatar
Jeromy committed
49

50 51 52 53
	if err != nil {
		return nil, err
	}

Adin Schmahmann's avatar
Adin Schmahmann committed
54
	if ctx.Err() == nil && lookupRes.completed {
Adin Schmahmann's avatar
Adin Schmahmann committed
55
		// refresh the cpl for this key as the query was successful
Adin Schmahmann's avatar
Adin Schmahmann committed
56
		dht.routingTable.ResetCplRefreshedAtForID(kb.ConvertKey(key), time.Now())
Adin Schmahmann's avatar
Adin Schmahmann committed
57
	}
58

59
	return lookupRes.peers, ctx.Err()
60
}