routing.go 14.8 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package dht

import (
4
	"bytes"
Jeromy's avatar
Jeromy committed
5
	"context"
6
	"fmt"
7
	"runtime"
Jeromy's avatar
Jeromy committed
8
	"sync"
Jeromy's avatar
Jeromy committed
9
	"time"
10

11
	proto "github.com/gogo/protobuf/proto"
12
	cid "github.com/ipfs/go-cid"
13
	u "github.com/ipfs/go-ipfs-util"
Jeromy's avatar
Jeromy committed
14
	logging "github.com/ipfs/go-log"
George Antoniadis's avatar
George Antoniadis committed
15 16
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
	kb "github.com/libp2p/go-libp2p-kbucket"
17 18 19 20
	inet "github.com/libp2p/go-libp2p-net"
	peer "github.com/libp2p/go-libp2p-peer"
	pset "github.com/libp2p/go-libp2p-peer/peerset"
	pstore "github.com/libp2p/go-libp2p-peerstore"
George Antoniadis's avatar
George Antoniadis committed
21 22 23
	record "github.com/libp2p/go-libp2p-record"
	routing "github.com/libp2p/go-libp2p-routing"
	notif "github.com/libp2p/go-libp2p-routing/notifications"
Steven Allen's avatar
Steven Allen committed
24
	ropts "github.com/libp2p/go-libp2p-routing/options"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25 26
)

27 28 29 30 31 32
// asyncQueryBuffer is the size of buffered channels in async queries. This
// buffer allows multiple queries to execute simultaneously, return their
// results and continue querying closer peers. Note that different query
// results will wait for the channel to drain.
var asyncQueryBuffer = 10

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33 34 35 36 37
// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

// PutValue adds value corresponding to given Key.
38
// This is the top level "Store" operation of the DHT
Steven Allen's avatar
Steven Allen committed
39
func (dht *IpfsDHT) PutValue(ctx context.Context, key string, value []byte, opts ...ropts.Option) (err error) {
40 41 42 43 44 45 46 47
	eip := log.EventBegin(ctx, "PutValue")
	defer func() {
		eip.Append(loggableKey(key))
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48
	log.Debugf("PutValue %s", key)
Jeromy's avatar
Jeromy committed
49

50
	rec := record.MakePutRecord(key, value)
51
	rec.TimeReceived = proto.String(u.FormatRFC3339(time.Now()))
Jeromy's avatar
Jeromy committed
52
	err = dht.putLocal(key, rec)
53 54 55 56
	if err != nil {
		return err
	}

57
	pchan, err := dht.GetClosestPeers(ctx, key)
58 59 60
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61

62 63 64 65
	wg := sync.WaitGroup{}
	for p := range pchan {
		wg.Add(1)
		go func(p peer.ID) {
Jeromy's avatar
Jeromy committed
66 67
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()
68
			defer wg.Done()
Jeromy's avatar
Jeromy committed
69 70 71 72 73
			notif.PublishQueryEvent(ctx, &notif.QueryEvent{
				Type: notif.Value,
				ID:   p,
			})

Jeromy's avatar
Jeromy committed
74
			err := dht.putValueToPeer(ctx, p, key, rec)
75
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76
				log.Debugf("failed putting value to peer: %s", err)
77 78 79 80 81
			}
		}(p)
	}
	wg.Wait()
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82 83
}

Steven Allen's avatar
Steven Allen committed
84 85 86 87 88 89
// RecvdVal stores a value and the peer from which we got the value.
type RecvdVal struct {
	Val  []byte
	From peer.ID
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90
// GetValue searches for the value corresponding to given Key.
Steven Allen's avatar
Steven Allen committed
91
func (dht *IpfsDHT) GetValue(ctx context.Context, key string, opts ...ropts.Option) (_ []byte, err error) {
92 93 94 95 96 97 98 99
	eip := log.EventBegin(ctx, "GetValue")
	defer func() {
		eip.Append(loggableKey(key))
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Jeromy's avatar
Jeromy committed
100 101 102
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()

Steven Allen's avatar
Steven Allen committed
103 104 105 106 107 108 109 110 111 112 113
	var cfg ropts.Options
	if err := cfg.Apply(opts...); err != nil {
		return nil, err
	}

	responsesNeeded := 0
	if !cfg.Offline {
		responsesNeeded = getQuorum(&cfg)
	}

	vals, err := dht.GetValues(ctx, key, responsesNeeded)
114 115 116 117
	if err != nil {
		return nil, err
	}

Steven Allen's avatar
Steven Allen committed
118
	recs := make([][]byte, 0, len(vals))
119
	for _, v := range vals {
120 121 122
		if v.Val != nil {
			recs = append(recs, v.Val)
		}
123
	}
124 125 126
	if len(recs) == 0 {
		return nil, routing.ErrNotFound
	}
127

128
	i, err := dht.Validator.Select(key, recs)
129 130 131 132 133 134 135 136 137 138 139
	if err != nil {
		return nil, err
	}

	best := recs[i]
	log.Debugf("GetValue %v %v", key, best)
	if best == nil {
		log.Errorf("GetValue yielded correct record with nil value.")
		return nil, routing.ErrNotFound
	}

140
	fixupRec := record.MakePutRecord(key, best)
141 142 143
	for _, v := range vals {
		// if someone sent us a different 'less-valid' record, lets correct them
		if !bytes.Equal(v.Val, best) {
Steven Allen's avatar
Steven Allen committed
144
			go func(v RecvdVal) {
145 146 147 148 149 150 151
				if v.From == dht.self {
					err := dht.putLocal(key, fixupRec)
					if err != nil {
						log.Error("Error correcting local dht entry:", err)
					}
					return
				}
Jeromy's avatar
Jeromy committed
152 153
				ctx, cancel := context.WithTimeout(dht.Context(), time.Second*30)
				defer cancel()
154 155 156 157 158 159 160 161 162 163 164
				err := dht.putValueToPeer(ctx, v.From, key, fixupRec)
				if err != nil {
					log.Error("Error correcting DHT entry: ", err)
				}
			}(v)
		}
	}

	return best, nil
}

Steven Allen's avatar
Steven Allen committed
165 166
// GetValues gets nvals values corresponding to the given key.
func (dht *IpfsDHT) GetValues(ctx context.Context, key string, nvals int) (_ []RecvdVal, err error) {
167 168 169 170 171 172 173 174
	eip := log.EventBegin(ctx, "GetValues")
	defer func() {
		eip.Append(loggableKey(key))
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Steven Allen's avatar
Steven Allen committed
175
	vals := make([]RecvdVal, 0, nvals)
176 177
	var valslock sync.Mutex

178
	// If we have it local, don't bother doing an RPC!
179
	lrec, err := dht.getLocal(key)
180 181 182 183 184
	if err != nil {
		// something is wrong with the datastore.
		return nil, err
	}
	if lrec != nil {
185
		// TODO: this is tricky, we don't always want to trust our own value
186
		// what if the authoritative source updated it?
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187
		log.Debug("have it locally")
Steven Allen's avatar
Steven Allen committed
188
		vals = append(vals, RecvdVal{
189 190 191 192 193 194 195 196 197
			Val:  lrec.GetValue(),
			From: dht.self,
		})

		if nvals <= 1 {
			return vals, nil
		}
	} else if nvals == 0 {
		return nil, err
Jeromy's avatar
Jeromy committed
198 199
	}

200
	// get closest peers in the routing table
Jeromy's avatar
Jeromy committed
201
	rtp := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
202
	log.Debugf("peers in rt: %d %s", len(rtp), rtp)
203
	if len(rtp) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
204
		log.Warning("No peers from routing table!")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205
		return nil, kb.ErrLookupFailure
206 207
	}

208
	// setup the Query
Jeromy's avatar
Jeromy committed
209
	parent := ctx
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
210
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
211
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
Jeromy's avatar
Jeromy committed
212 213 214 215
			Type: notif.SendingQuery,
			ID:   p,
		})

216
		rec, peers, err := dht.getValueOrPeers(ctx, p, key)
217 218 219 220 221 222 223 224 225
		switch err {
		case routing.ErrNotFound:
			// in this case, they responded with nothing,
			// still send a notification so listeners can know the
			// request has completed 'successfully'
			notif.PublishQueryEvent(parent, &notif.QueryEvent{
				Type: notif.PeerResponse,
				ID:   p,
			})
226
			return nil, err
227 228 229 230 231
		default:
			return nil, err

		case nil, errInvalidRecord:
			// in either of these cases, we want to keep going
232
		}
233

234 235
		res := &dhtQueryResult{closerPeers: peers}

236
		if rec.GetValue() != nil || err == errInvalidRecord {
Steven Allen's avatar
Steven Allen committed
237
			rv := RecvdVal{
238 239 240 241 242 243
				Val:  rec.GetValue(),
				From: p,
			}
			valslock.Lock()
			vals = append(vals, rv)

244
			// If we have collected enough records, we're done
245 246 247 248
			if len(vals) >= nvals {
				res.success = true
			}
			valslock.Unlock()
249 250
		}

Jeromy's avatar
Jeromy committed
251
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
Jeromy's avatar
Jeromy committed
252 253
			Type:      notif.PeerResponse,
			ID:        p,
Jeromy's avatar
Jeromy committed
254
			Responses: peers,
Jeromy's avatar
Jeromy committed
255 256
		})

257 258
		return res, nil
	})
259

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
260
	// run it!
261 262 263 264 265
	_, err = query.Run(ctx, rtp)
	if len(vals) == 0 {
		if err != nil {
			return nil, err
		}
266 267
	}

268
	return vals, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
269 270
}

271 272 273
// Provider abstraction for indirect stores.
// Some DHTs store values directly, while an indirect store stores pointers to
// locations of the value, similarly to Coral and Mainline DHT.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
274

275
// Provide makes this node announce that it can provide a value for the given key
276 277 278 279 280 281 282 283
func (dht *IpfsDHT) Provide(ctx context.Context, key *cid.Cid, brdcst bool) (err error) {
	eip := log.EventBegin(ctx, "Provide", key, logging.LoggableMap{"broadcast": brdcst})
	defer func() {
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
284 285

	// add self locally
286
	dht.providers.AddProvider(ctx, key, dht.self)
Jeromy's avatar
Jeromy committed
287 288 289
	if !brdcst {
		return nil
	}
290

291
	peers, err := dht.GetClosestPeers(ctx, key.KeyString())
292 293
	if err != nil {
		return err
294 295
	}

296 297 298 299 300
	mes, err := dht.makeProvRecord(key)
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
301
	wg := sync.WaitGroup{}
302
	for p := range peers {
Jeromy's avatar
Jeromy committed
303 304 305
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
306
			log.Debugf("putProvider(%s, %s)", key, p)
307
			err := dht.sendMessage(ctx, p, mes)
Jeromy's avatar
Jeromy committed
308
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
309
				log.Debug(err)
Jeromy's avatar
Jeromy committed
310 311
			}
		}(p)
312
	}
Jeromy's avatar
Jeromy committed
313
	wg.Wait()
314
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
315
}
316
func (dht *IpfsDHT) makeProvRecord(skey *cid.Cid) (*pb.Message, error) {
317 318 319 320 321 322 323 324 325 326 327
	pi := pstore.PeerInfo{
		ID:    dht.self,
		Addrs: dht.host.Addrs(),
	}

	// // only share WAN-friendly addresses ??
	// pi.Addrs = addrutil.WANShareableAddrs(pi.Addrs)
	if len(pi.Addrs) < 1 {
		return nil, fmt.Errorf("no known addresses for self. cannot put provider.")
	}

328
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, skey.KeyString(), 0)
329 330 331
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]pstore.PeerInfo{pi})
	return pmes, nil
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
332

Brian Tiger Chow's avatar
Brian Tiger Chow committed
333
// FindProviders searches until the context expires.
334
func (dht *IpfsDHT) FindProviders(ctx context.Context, c *cid.Cid) ([]pstore.PeerInfo, error) {
Jeromy's avatar
Jeromy committed
335
	var providers []pstore.PeerInfo
336
	for p := range dht.FindProvidersAsync(ctx, c, KValue) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
337 338 339 340 341
		providers = append(providers, p)
	}
	return providers, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
342 343 344
// FindProvidersAsync is the same thing as FindProviders, but returns a channel.
// Peers will be returned on the channel as soon as they are found, even before
// the search query completes.
345 346
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key *cid.Cid, count int) <-chan pstore.PeerInfo {
	log.Event(ctx, "findProviders", key)
Jeromy's avatar
Jeromy committed
347
	peerOut := make(chan pstore.PeerInfo, count)
Jeromy's avatar
Jeromy committed
348 349 350 351
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

352 353
func (dht *IpfsDHT) findProvidersAsyncRoutine(ctx context.Context, key *cid.Cid, count int, peerOut chan pstore.PeerInfo) {
	defer log.EventBegin(ctx, "findProvidersAsync", key).Done()
Jeromy's avatar
Jeromy committed
354 355
	defer close(peerOut)

Jeromy's avatar
Jeromy committed
356
	ps := pset.NewLimited(count)
Jeromy's avatar
Jeromy committed
357 358
	provs := dht.providers.GetProviders(ctx, key)
	for _, p := range provs {
359
		// NOTE: Assuming that this list of peers is unique
Jeromy's avatar
Jeromy committed
360
		if ps.TryAdd(p) {
Jeromy's avatar
Jeromy committed
361
			pi := dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
362
			select {
Jeromy's avatar
Jeromy committed
363
			case peerOut <- pi:
Jeromy's avatar
Jeromy committed
364 365 366
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
367
		}
Jeromy's avatar
Jeromy committed
368

369
		// If we have enough peers locally, don't bother with remote RPC
Jeromy's avatar
Jeromy committed
370
		// TODO: is this a DOS vector?
Jeromy's avatar
Jeromy committed
371
		if ps.Size() >= count {
Jeromy's avatar
Jeromy committed
372 373 374 375 376
			return
		}
	}

	// setup the Query
Jeromy's avatar
Jeromy committed
377
	parent := ctx
378
	query := dht.newQuery(key.KeyString(), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
379
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
380 381 382
			Type: notif.SendingQuery,
			ID:   p,
		})
383
		pmes, err := dht.findProvidersSingle(ctx, p, key)
Jeromy's avatar
Jeromy committed
384 385 386 387
		if err != nil {
			return nil, err
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
388
		log.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
389
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
390
		log.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
391 392 393

		// Add unique providers from request, up to 'count'
		for _, prov := range provs {
394 395 396
			if prov.ID != dht.self {
				dht.peerstore.AddAddrs(prov.ID, prov.Addrs, pstore.TempAddrTTL)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
397
			log.Debugf("got provider: %s", prov)
398
			if ps.TryAdd(prov.ID) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
399
				log.Debugf("using provider: %s", prov)
Jeromy's avatar
Jeromy committed
400
				select {
Jeromy's avatar
Jeromy committed
401
				case peerOut <- *prov:
Jeromy's avatar
Jeromy committed
402
				case <-ctx.Done():
403
					log.Debug("context timed out sending more providers")
Jeromy's avatar
Jeromy committed
404 405
					return nil, ctx.Err()
				}
406
			}
Jeromy's avatar
Jeromy committed
407
			if ps.Size() >= count {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
408
				log.Debugf("got enough providers (%d/%d)", ps.Size(), count)
Jeromy's avatar
Jeromy committed
409
				return &dhtQueryResult{success: true}, nil
410 411 412
			}
		}

Jeromy's avatar
Jeromy committed
413 414
		// Give closer peers back to the query to be queried
		closer := pmes.GetCloserPeers()
415
		clpeers := pb.PBPeersToPeerInfos(closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
416
		log.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
417

Jeromy's avatar
Jeromy committed
418
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
419 420
			Type:      notif.PeerResponse,
			ID:        p,
Jeromy's avatar
Jeromy committed
421
			Responses: clpeers,
422
		})
Jeromy's avatar
Jeromy committed
423 424 425
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

Jeromy's avatar
Jeromy committed
426
	peers := dht.routingTable.NearestPeers(kb.ConvertKey(key.KeyString()), AlphaValue)
Jeromy's avatar
Jeromy committed
427 428
	_, err := query.Run(ctx, peers)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
429
		log.Debugf("Query error: %s", err)
430 431 432 433 434 435 436 437 438 439
		// Special handling for issue: https://github.com/ipfs/go-ipfs/issues/3032
		if fmt.Sprint(err) == "<nil>" {
			log.Error("reproduced bug 3032:")
			log.Errorf("Errors type information: %#v", err)
			log.Errorf("go version: %s", runtime.Version())
			log.Error("please report this information to: https://github.com/ipfs/go-ipfs/issues/3032")

			// replace problematic error with something that won't crash the daemon
			err = fmt.Errorf("<nil>")
		}
440 441 442 443
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type:  notif.QueryError,
			Extra: err.Error(),
		})
Jeromy's avatar
Jeromy committed
444
	}
445 446
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
447
// FindPeer searches for a peer with given ID.
448 449 450 451 452 453 454 455
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (_ pstore.PeerInfo, err error) {
	eip := log.EventBegin(ctx, "FindPeer", id)
	defer func() {
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
456

457
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
458
	if pi := dht.FindLocal(id); pi.ID != "" {
459
		return pi, nil
460 461
	}

Jeromy's avatar
Jeromy committed
462
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
463
	if len(peers) == 0 {
Jeromy's avatar
Jeromy committed
464
		return pstore.PeerInfo{}, kb.ErrLookupFailure
465
	}
466

Jeromy's avatar
Jeromy committed
467
	// Sanity...
468
	for _, p := range peers {
469
		if p == id {
470
			log.Debug("found target peer in list of closest peers...")
471
			return dht.peerstore.PeerInfo(p), nil
472
		}
473
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
474

Jeromy's avatar
Jeromy committed
475
	// setup the Query
Jeromy's avatar
Jeromy committed
476
	parent := ctx
477
	query := dht.newQuery(string(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
478
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
479 480 481
			Type: notif.SendingQuery,
			ID:   p,
		})
Jeromy's avatar
Jeromy committed
482

483
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
484
		if err != nil {
485
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
486
		}
487

Jeromy's avatar
Jeromy committed
488
		closer := pmes.GetCloserPeers()
489
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
490

491
		// see if we got the peer here
492 493
		for _, npi := range clpeerInfos {
			if npi.ID == id {
Jeromy's avatar
Jeromy committed
494
				return &dhtQueryResult{
495
					peer:    npi,
Jeromy's avatar
Jeromy committed
496 497 498
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
499 500
		}

Jeromy's avatar
Jeromy committed
501
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
502
			Type:      notif.PeerResponse,
503
			ID:        p,
Jeromy's avatar
Jeromy committed
504
			Responses: clpeerInfos,
505 506
		})

507
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
508
	})
509

Jeromy's avatar
Jeromy committed
510
	// run it!
511
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
512
	if err != nil {
Jeromy's avatar
Jeromy committed
513
		return pstore.PeerInfo{}, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
514 515
	}

516
	log.Debugf("FindPeer %v %v", id, result.success)
517
	if result.peer.ID == "" {
Jeromy's avatar
Jeromy committed
518
		return pstore.PeerInfo{}, routing.ErrNotFound
519
	}
Jeromy's avatar
Jeromy committed
520

Jeromy's avatar
Jeromy committed
521
	return *result.peer, nil
522 523
}

524
// FindPeersConnectedToPeer searches for peers directly connected to a given peer.
Jeromy's avatar
Jeromy committed
525
func (dht *IpfsDHT) FindPeersConnectedToPeer(ctx context.Context, id peer.ID) (<-chan *pstore.PeerInfo, error) {
526

Jeromy's avatar
Jeromy committed
527
	peerchan := make(chan *pstore.PeerInfo, asyncQueryBuffer)
Jeromy's avatar
Jeromy committed
528
	peersSeen := make(map[peer.ID]struct{})
529
	var peersSeenMx sync.Mutex
530

Jeromy's avatar
Jeromy committed
531
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
532
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
533
		return nil, kb.ErrLookupFailure
534 535 536
	}

	// setup the Query
537
	query := dht.newQuery(string(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
538

539
		pmes, err := dht.findPeerSingle(ctx, p, id)
540 541 542 543
		if err != nil {
			return nil, err
		}

Jeromy's avatar
Jeromy committed
544
		var clpeers []*pstore.PeerInfo
545 546
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
547
			pi := pb.PBPeerToPeerInfo(pbp)
548

549
			// skip peers already seen
550
			peersSeenMx.Lock()
551
			if _, found := peersSeen[pi.ID]; found {
552
				peersSeenMx.Unlock()
553 554
				continue
			}
555
			peersSeen[pi.ID] = struct{}{}
556
			peersSeenMx.Unlock()
557 558 559 560 561 562

			// if peer is connected, send it to our client.
			if pb.Connectedness(*pbp.Connection) == inet.Connected {
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
563
				case peerchan <- pi:
564 565 566 567
				}
			}

			// if peer is the peer we're looking for, don't bother querying it.
568
			// TODO maybe query it?
569
			if pb.Connectedness(*pbp.Connection) != inet.Connected {
570
				clpeers = append(clpeers, pi)
571 572 573 574 575 576 577 578 579
			}
		}

		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

	// run it! run it asynchronously to gen peers as results are found.
	// this does no error checking
	go func() {
580
		if _, err := query.Run(ctx, peers); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
581
			log.Debug(err)
582 583 584 585 586 587 588 589
		}

		// close the peerchan channel when done.
		close(peerchan)
	}()

	return peerchan, nil
}