routing.go 14 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
	cid "github.com/ipfs/go-cid"
Jeromy's avatar
Jeromy committed
12
	logging "github.com/ipfs/go-log"
George Antoniadis's avatar
George Antoniadis committed
13 14
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
	kb "github.com/libp2p/go-libp2p-kbucket"
15 16 17 18
	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
19 20 21
	record "github.com/libp2p/go-libp2p-record"
	routing "github.com/libp2p/go-libp2p-routing"
	notif "github.com/libp2p/go-libp2p-routing/notifications"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
22 23
)

24 25 26 27 28 29
// 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
30 31 32 33 34
// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

// PutValue adds value corresponding to given Key.
35
// This is the top level "Store" operation of the DHT
36 37 38 39 40 41 42 43 44
func (dht *IpfsDHT) PutValue(ctx context.Context, key string, value []byte) (err error) {
	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
45
	log.Debugf("PutValue %s", key)
Jeromy's avatar
Jeromy committed
46

47
	rec := record.MakePutRecord(key, value)
Jeromy's avatar
Jeromy committed
48
	err = dht.putLocal(key, rec)
49 50 51 52
	if err != nil {
		return err
	}

53
	pchan, err := dht.GetClosestPeers(ctx, key)
54 55 56
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57

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

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

// GetValue searches for the value corresponding to given Key.
81 82 83 84 85 86 87 88 89
func (dht *IpfsDHT) GetValue(ctx context.Context, key string) (_ []byte, err error) {
	eip := log.EventBegin(ctx, "GetValue")
	defer func() {
		eip.Append(loggableKey(key))
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Jeromy's avatar
Jeromy committed
90 91 92 93
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()

	vals, err := dht.GetValues(ctx, key, 16)
94 95 96 97
	if err != nil {
		return nil, err
	}

Steven Allen's avatar
Steven Allen committed
98
	recs := make([][]byte, 0, len(vals))
99
	for _, v := range vals {
100 101 102
		if v.Val != nil {
			recs = append(recs, v.Val)
		}
103 104 105 106 107 108 109 110 111 112 113 114 115 116
	}

	i, err := dht.Selector.BestRecord(key, recs)
	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
	}

117
	fixupRec := record.MakePutRecord(key, best)
118 119 120 121
	for _, v := range vals {
		// if someone sent us a different 'less-valid' record, lets correct them
		if !bytes.Equal(v.Val, best) {
			go func(v routing.RecvdVal) {
122 123 124 125 126 127 128
				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
129 130
				ctx, cancel := context.WithTimeout(dht.Context(), time.Second*30)
				defer cancel()
131 132 133 134 135 136 137 138 139 140 141
				err := dht.putValueToPeer(ctx, v.From, key, fixupRec)
				if err != nil {
					log.Error("Error correcting DHT entry: ", err)
				}
			}(v)
		}
	}

	return best, nil
}

142 143 144 145 146 147 148 149 150
func (dht *IpfsDHT) GetValues(ctx context.Context, key string, nvals int) (_ []routing.RecvdVal, err error) {
	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
151
	vals := make([]routing.RecvdVal, 0, nvals)
152 153
	var valslock sync.Mutex

Jeromy's avatar
Jeromy committed
154
	// If we have it local, dont bother doing an RPC!
155
	lrec, err := dht.getLocal(key)
Jeromy's avatar
Jeromy committed
156
	if err == nil {
157 158
		// TODO: this is tricky, we dont always want to trust our own value
		// what if the authoritative source updated it?
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159
		log.Debug("have it locally")
160 161 162 163 164 165 166 167 168 169
		vals = append(vals, routing.RecvdVal{
			Val:  lrec.GetValue(),
			From: dht.self,
		})

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

172
	// get closest peers in the routing table
Jeromy's avatar
Jeromy committed
173
	rtp := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
174
	log.Debugf("peers in rt: %d %s", len(rtp), rtp)
175
	if len(rtp) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176
		log.Warning("No peers from routing table!")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177
		return nil, kb.ErrLookupFailure
178 179
	}

180
	// setup the Query
Jeromy's avatar
Jeromy committed
181
	parent := ctx
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
183
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
Jeromy's avatar
Jeromy committed
184 185 186 187
			Type: notif.SendingQuery,
			ID:   p,
		})

188
		rec, peers, err := dht.getValueOrPeers(ctx, p, key)
189 190 191 192 193 194 195 196 197
		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,
			})
198
			return nil, err
199 200 201 202 203
		default:
			return nil, err

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

206 207
		res := &dhtQueryResult{closerPeers: peers}

208
		if rec.GetValue() != nil || err == errInvalidRecord {
209 210 211 212 213 214 215 216 217 218 219 220
			rv := routing.RecvdVal{
				Val:  rec.GetValue(),
				From: p,
			}
			valslock.Lock()
			vals = append(vals, rv)

			// If weve collected enough records, we're done
			if len(vals) >= nvals {
				res.success = true
			}
			valslock.Unlock()
221 222
		}

Jeromy's avatar
Jeromy committed
223
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
Jeromy's avatar
Jeromy committed
224 225
			Type:      notif.PeerResponse,
			ID:        p,
Jeromy's avatar
Jeromy committed
226
			Responses: peers,
Jeromy's avatar
Jeromy committed
227 228
		})

229 230
		return res, nil
	})
231

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232
	// run it!
233 234 235 236 237
	_, err = query.Run(ctx, rtp)
	if len(vals) == 0 {
		if err != nil {
			return nil, err
		}
238 239
	}

240
	return vals, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241 242 243 244 245
}

// Value provider layer of indirection.
// This is what DSHTs (Coral and MainlineDHT) do to store large values in a DHT.

246
// Provide makes this node announce that it can provide a value for the given key
247 248 249 250 251 252 253 254
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
255 256

	// add self locally
257
	dht.providers.AddProvider(ctx, key, dht.self)
Jeromy's avatar
Jeromy committed
258 259 260
	if !brdcst {
		return nil
	}
261

262
	peers, err := dht.GetClosestPeers(ctx, key.KeyString())
263 264
	if err != nil {
		return err
265 266
	}

267 268 269 270 271
	mes, err := dht.makeProvRecord(key)
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
272
	wg := sync.WaitGroup{}
273
	for p := range peers {
Jeromy's avatar
Jeromy committed
274 275 276
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
277
			log.Debugf("putProvider(%s, %s)", key, p)
278
			err := dht.sendMessage(ctx, p, mes)
Jeromy's avatar
Jeromy committed
279
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
280
				log.Debug(err)
Jeromy's avatar
Jeromy committed
281 282
			}
		}(p)
283
	}
Jeromy's avatar
Jeromy committed
284
	wg.Wait()
285
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
286
}
287
func (dht *IpfsDHT) makeProvRecord(skey *cid.Cid) (*pb.Message, error) {
288 289 290 291 292 293 294 295 296 297 298
	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.")
	}

299
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, skey.KeyString(), 0)
300 301 302
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]pstore.PeerInfo{pi})
	return pmes, nil
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
303

Brian Tiger Chow's avatar
Brian Tiger Chow committed
304
// FindProviders searches until the context expires.
305
func (dht *IpfsDHT) FindProviders(ctx context.Context, c *cid.Cid) ([]pstore.PeerInfo, error) {
Jeromy's avatar
Jeromy committed
306
	var providers []pstore.PeerInfo
307
	for p := range dht.FindProvidersAsync(ctx, c, KValue) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
308 309 310 311 312
		providers = append(providers, p)
	}
	return providers, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
313 314 315
// 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.
316 317
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
318
	peerOut := make(chan pstore.PeerInfo, count)
Jeromy's avatar
Jeromy committed
319 320 321 322
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

323 324
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
325 326
	defer close(peerOut)

Jeromy's avatar
Jeromy committed
327
	ps := pset.NewLimited(count)
Jeromy's avatar
Jeromy committed
328 329
	provs := dht.providers.GetProviders(ctx, key)
	for _, p := range provs {
330
		// NOTE: Assuming that this list of peers is unique
Jeromy's avatar
Jeromy committed
331
		if ps.TryAdd(p) {
Jeromy's avatar
Jeromy committed
332
			pi := dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
333
			select {
Jeromy's avatar
Jeromy committed
334
			case peerOut <- pi:
Jeromy's avatar
Jeromy committed
335 336 337
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
338
		}
Jeromy's avatar
Jeromy committed
339 340

		// If we have enough peers locally, dont bother with remote RPC
Jeromy's avatar
Jeromy committed
341
		// TODO: is this a DOS vector?
Jeromy's avatar
Jeromy committed
342
		if ps.Size() >= count {
Jeromy's avatar
Jeromy committed
343 344 345 346 347
			return
		}
	}

	// setup the Query
Jeromy's avatar
Jeromy committed
348
	parent := ctx
349
	query := dht.newQuery(key.KeyString(), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
350
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
351 352 353
			Type: notif.SendingQuery,
			ID:   p,
		})
354
		pmes, err := dht.findProvidersSingle(ctx, p, key)
Jeromy's avatar
Jeromy committed
355 356 357 358
		if err != nil {
			return nil, err
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
359
		log.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
360
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
361
		log.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
362 363 364

		// Add unique providers from request, up to 'count'
		for _, prov := range provs {
365 366 367
			if prov.ID != dht.self {
				dht.peerstore.AddAddrs(prov.ID, prov.Addrs, pstore.TempAddrTTL)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
368
			log.Debugf("got provider: %s", prov)
369
			if ps.TryAdd(prov.ID) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
370
				log.Debugf("using provider: %s", prov)
Jeromy's avatar
Jeromy committed
371
				select {
Jeromy's avatar
Jeromy committed
372
				case peerOut <- *prov:
Jeromy's avatar
Jeromy committed
373
				case <-ctx.Done():
374
					log.Debug("context timed out sending more providers")
Jeromy's avatar
Jeromy committed
375 376
					return nil, ctx.Err()
				}
377
			}
Jeromy's avatar
Jeromy committed
378
			if ps.Size() >= count {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
379
				log.Debugf("got enough providers (%d/%d)", ps.Size(), count)
Jeromy's avatar
Jeromy committed
380
				return &dhtQueryResult{success: true}, nil
381 382 383
			}
		}

Jeromy's avatar
Jeromy committed
384 385
		// Give closer peers back to the query to be queried
		closer := pmes.GetCloserPeers()
386
		clpeers := pb.PBPeersToPeerInfos(closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
387
		log.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
388

Jeromy's avatar
Jeromy committed
389
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
390 391
			Type:      notif.PeerResponse,
			ID:        p,
Jeromy's avatar
Jeromy committed
392
			Responses: clpeers,
393
		})
Jeromy's avatar
Jeromy committed
394 395 396
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

Jeromy's avatar
Jeromy committed
397
	peers := dht.routingTable.NearestPeers(kb.ConvertKey(key.KeyString()), AlphaValue)
Jeromy's avatar
Jeromy committed
398 399
	_, err := query.Run(ctx, peers)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
400
		log.Debugf("Query error: %s", err)
401 402 403 404 405 406 407 408 409 410
		// 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>")
		}
411 412 413 414
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type:  notif.QueryError,
			Extra: err.Error(),
		})
Jeromy's avatar
Jeromy committed
415
	}
416 417
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
418
// FindPeer searches for a peer with given ID.
419 420 421 422 423 424 425 426
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
427

428
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
429
	if pi := dht.FindLocal(id); pi.ID != "" {
430
		return pi, nil
431 432
	}

Jeromy's avatar
Jeromy committed
433
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
434
	if len(peers) == 0 {
Jeromy's avatar
Jeromy committed
435
		return pstore.PeerInfo{}, kb.ErrLookupFailure
436
	}
437

Jeromy's avatar
Jeromy committed
438
	// Sanity...
439
	for _, p := range peers {
440
		if p == id {
441
			log.Debug("found target peer in list of closest peers...")
442
			return dht.peerstore.PeerInfo(p), nil
443
		}
444
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
445

Jeromy's avatar
Jeromy committed
446
	// setup the Query
Jeromy's avatar
Jeromy committed
447
	parent := ctx
448
	query := dht.newQuery(string(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
449
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
450 451 452
			Type: notif.SendingQuery,
			ID:   p,
		})
Jeromy's avatar
Jeromy committed
453

454
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
455
		if err != nil {
456
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
457
		}
458

Jeromy's avatar
Jeromy committed
459
		closer := pmes.GetCloserPeers()
460
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
461

462
		// see if we got the peer here
463 464
		for _, npi := range clpeerInfos {
			if npi.ID == id {
Jeromy's avatar
Jeromy committed
465
				return &dhtQueryResult{
466
					peer:    npi,
Jeromy's avatar
Jeromy committed
467 468 469
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
470 471
		}

Jeromy's avatar
Jeromy committed
472
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
473
			Type:      notif.PeerResponse,
474
			ID:        p,
Jeromy's avatar
Jeromy committed
475
			Responses: clpeerInfos,
476 477
		})

478
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
479
	})
480

Jeromy's avatar
Jeromy committed
481
	// run it!
482
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
483
	if err != nil {
Jeromy's avatar
Jeromy committed
484
		return pstore.PeerInfo{}, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
485 486
	}

487
	log.Debugf("FindPeer %v %v", id, result.success)
488
	if result.peer.ID == "" {
Jeromy's avatar
Jeromy committed
489
		return pstore.PeerInfo{}, routing.ErrNotFound
490
	}
Jeromy's avatar
Jeromy committed
491

Jeromy's avatar
Jeromy committed
492
	return *result.peer, nil
493 494
}

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

Jeromy's avatar
Jeromy committed
498
	peerchan := make(chan *pstore.PeerInfo, asyncQueryBuffer)
Jeromy's avatar
Jeromy committed
499
	peersSeen := make(map[peer.ID]struct{})
500

Jeromy's avatar
Jeromy committed
501
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
502
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
503
		return nil, kb.ErrLookupFailure
504 505 506
	}

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

509
		pmes, err := dht.findPeerSingle(ctx, p, id)
510 511 512 513
		if err != nil {
			return nil, err
		}

Jeromy's avatar
Jeromy committed
514
		var clpeers []*pstore.PeerInfo
515 516
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
517
			pi := pb.PBPeerToPeerInfo(pbp)
518

519 520
			// skip peers already seen
			if _, found := peersSeen[pi.ID]; found {
521 522
				continue
			}
523
			peersSeen[pi.ID] = struct{}{}
524 525 526 527 528 529

			// if peer is connected, send it to our client.
			if pb.Connectedness(*pbp.Connection) == inet.Connected {
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
530
				case peerchan <- pi:
531 532 533 534
				}
			}

			// if peer is the peer we're looking for, don't bother querying it.
535
			// TODO maybe query it?
536
			if pb.Connectedness(*pbp.Connection) != inet.Connected {
537
				clpeers = append(clpeers, pi)
538 539 540 541 542 543 544 545 546
			}
		}

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

	// run it! run it asynchronously to gen peers as results are found.
	// this does no error checking
	go func() {
547
		if _, err := query.Run(ctx, peers); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
548
			log.Debug(err)
549 550 551 552 553 554 555 556
		}

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

	return peerchan, nil
}