go-libp2p-kad-dht/lookup.go

135 lines
3.3 KiB
Go
Raw Normal View History

package dht
import (
2016-09-30 10:24:03 -07:00
"context"
"fmt"
"strings"
2019-06-14 15:55:36 -07:00
"time"
2016-09-30 10:24:03 -07:00
2019-05-26 23:33:15 +01:00
"github.com/libp2p/go-libp2p-core/peer"
"github.com/ipfs/go-cid"
logging "github.com/ipfs/go-log"
pb "github.com/libp2p/go-libp2p-kad-dht/pb"
2016-09-02 20:21:23 +01:00
kb "github.com/libp2p/go-libp2p-kbucket"
notif "github.com/libp2p/go-libp2p-routing/notifications"
2019-12-17 17:25:11 -05:00
"github.com/multiformats/go-base32"
"github.com/multiformats/go-multihash"
)
func tryFormatLoggableKey(k string) (string, error) {
if len(k) == 0 {
return "", fmt.Errorf("loggableKey is empty")
}
var proto, cstr string
if k[0] == '/' {
// it's a path (probably)
protoEnd := strings.IndexByte(k[1:], '/')
if protoEnd < 0 {
return k, fmt.Errorf("loggableKey starts with '/' but is not a path: %x", k)
}
proto = k[1 : protoEnd+1]
cstr = k[protoEnd+2:]
} else {
proto = "provider"
cstr = k
}
2019-12-17 17:25:11 -05:00
var encStr string
c, err := cid.Cast([]byte(cstr))
2019-12-17 17:25:11 -05:00
if err == nil {
encStr = c.String()
} else {
encStr = base32.RawStdEncoding.EncodeToString([]byte(cstr))
}
2019-12-17 17:25:11 -05:00
return fmt.Sprintf("/%s/%s", proto, encStr), nil
}
func loggableKey(k string) logging.LoggableMap {
newKey, err := tryFormatLoggableKey(k)
2017-07-27 16:49:44 +02:00
if err != nil {
2019-02-01 17:46:46 +11:00
logger.Debug(err)
2017-07-27 16:49:44 +02:00
} else {
k = newKey
}
return logging.LoggableMap{
"key": k,
}
}
2019-12-17 17:25:11 -05:00
func multihashLoggableKey(mh multihash.Multihash) logging.LoggableMap {
return logging.LoggableMap{
"multihash": base32.RawStdEncoding.EncodeToString(mh),
}
}
// Kademlia 'node lookup' operation. Returns a channel of the K closest peers
// to the given key
func (dht *IpfsDHT) GetClosestPeers(ctx context.Context, key string) (<-chan peer.ID, error) {
2019-02-01 17:46:46 +11:00
e := logger.EventBegin(ctx, "getClosestPeers", loggableKey(key))
tablepeers := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
if len(tablepeers) == 0 {
return nil, kb.ErrLookupFailure
}
out := make(chan peer.ID, dht.bucketSize)
// since the query doesnt actually pass our context down
// we have to hack this here. whyrusleeping isnt a huge fan of goprocess
parent := ctx
query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
// For DHT query command
notif.PublishQueryEvent(parent, &notif.QueryEvent{
Type: notif.SendingQuery,
ID: p,
})
2018-02-19 19:25:44 -05:00
pmes, err := dht.findPeerSingle(ctx, p, peer.ID(key))
if err != nil {
2019-02-01 17:46:46 +11:00
logger.Debugf("error getting closer peers: %s", err)
return nil, err
}
2018-02-19 19:25:44 -05:00
peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())
// For DHT query command
notif.PublishQueryEvent(parent, &notif.QueryEvent{
Type: notif.PeerResponse,
ID: p,
2018-02-19 19:25:44 -05:00
Responses: peers,
})
2018-02-19 19:25:44 -05:00
return &dhtQueryResult{closerPeers: peers}, nil
})
go func() {
defer close(out)
defer e.Done()
2019-06-14 15:55:36 -07:00
timedCtx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
// run it!
2019-06-14 15:55:36 -07:00
res, err := query.Run(timedCtx, tablepeers)
if err != nil {
2019-02-01 17:46:46 +11:00
logger.Debugf("closestPeers query run error: %s", err)
}
if res != nil && res.queriedSet != nil {
2019-12-17 01:25:57 +08:00
// refresh the cpl for this key as the query was successful
dht.routingTable.ResetCplRefreshedAtForID(kb.ConvertKey(key), time.Now())
sorted := kb.SortClosestPeers(res.queriedSet.Peers(), kb.ConvertKey(key))
l := len(sorted)
if l > dht.bucketSize {
sorted = sorted[:dht.bucketSize]
}
for _, p := range sorted {
out <- p
}
}
}()
return out, nil
}