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

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

10
	key "github.com/ipfs/go-ipfs/blocks/key"
11 12 13 14 15
	notif "github.com/ipfs/go-ipfs/notifications"
	"github.com/ipfs/go-ipfs/routing"
	pb "github.com/ipfs/go-ipfs/routing/dht/pb"
	kb "github.com/ipfs/go-ipfs/routing/kbucket"
	record "github.com/ipfs/go-ipfs/routing/record"
16
	pset "github.com/ipfs/go-ipfs/thirdparty/peerset"
Jeromy's avatar
Jeromy committed
17

18 19
	pstore "gx/ipfs/QmQdnfvZQuhdT93LNc5bos52wAmdr3G2p6G8teLJMEN32P/go-libp2p-peerstore"
	peer "gx/ipfs/QmRBqJF7hb8ZSpRcMwUt8hNhydWcxGEhtk81HKq6oUwKvs/go-libp2p-peer"
Jeromy's avatar
Jeromy committed
20
	inet "gx/ipfs/QmVCe3SNMjkcPgnpFhZs719dheq6xE7gJwjzV7aWcUM4Ms/go-libp2p/p2p/net"
Jeromy's avatar
Jeromy committed
21
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
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
func (dht *IpfsDHT) PutValue(ctx context.Context, key key.Key, value []byte) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37
	log.Debugf("PutValue %s", key)
Jeromy's avatar
Jeromy committed
38
	sk, err := dht.getOwnPrivateKey()
Jeromy's avatar
Jeromy committed
39 40 41
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42

43 44 45 46 47
	sign, err := dht.Validator.IsSigned(key)
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
48
	rec, err := record.MakePutRecord(sk, key, value, sign)
Jeromy's avatar
Jeromy committed
49
	if err != nil {
50
		log.Debug("creation of record failed!")
Jeromy's avatar
Jeromy committed
51 52 53
		return err
	}

Jeromy's avatar
Jeromy committed
54
	err = dht.putLocal(key, rec)
55 56 57 58
	if err != nil {
		return err
	}

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

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

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

// GetValue searches for the value corresponding to given Key.
87
func (dht *IpfsDHT) GetValue(ctx context.Context, key key.Key) ([]byte, error) {
Jeromy's avatar
Jeromy committed
88 89 90 91
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()

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

	var recs [][]byte
	for _, v := range vals {
98 99 100
		if v.Val != nil {
			recs = append(recs, v.Val)
		}
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
	}

	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
	}

	fixupRec, err := record.MakePutRecord(dht.peerstore.PrivKey(dht.self), key, best, true)
	if err != nil {
		// probably shouldnt actually 'error' here as we have found a value we like,
		// but this call failing probably isnt something we want to ignore
		return nil, err
	}

	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) {
126 127 128 129 130 131 132
				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
133 134
				ctx, cancel := context.WithTimeout(dht.Context(), time.Second*30)
				defer cancel()
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
				err := dht.putValueToPeer(ctx, v.From, key, fixupRec)
				if err != nil {
					log.Error("Error correcting DHT entry: ", err)
				}
			}(v)
		}
	}

	return best, nil
}

func (dht *IpfsDHT) GetValues(ctx context.Context, key key.Key, nvals int) ([]routing.RecvdVal, error) {
	var vals []routing.RecvdVal
	var valslock sync.Mutex

Jeromy's avatar
Jeromy committed
150
	// If we have it local, dont bother doing an RPC!
151
	lrec, err := dht.getLocal(key)
Jeromy's avatar
Jeromy committed
152
	if err == nil {
153 154
		// 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
155
		log.Debug("have it locally")
156 157 158 159 160 161 162 163 164 165
		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
166 167
	}

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

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

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

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

202 203
		res := &dhtQueryResult{closerPeers: peers}

204
		if rec.GetValue() != nil || err == errInvalidRecord {
205 206 207 208 209 210 211 212 213 214 215 216
			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()
217 218
		}

Jeromy's avatar
Jeromy committed
219
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
Jeromy's avatar
Jeromy committed
220 221 222 223 224
			Type:      notif.PeerResponse,
			ID:        p,
			Responses: pointerizePeerInfos(peers),
		})

225 226
		return res, nil
	})
227

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

236
	return vals, nil
237

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238 239 240 241 242
}

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

243
// Provide makes this node announce that it can provide a value for the given key
244
func (dht *IpfsDHT) Provide(ctx context.Context, key key.Key) error {
Jeromy's avatar
Jeromy committed
245
	defer log.EventBegin(ctx, "provide", &key).Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
246 247

	// add self locally
248
	dht.providers.AddProvider(ctx, key, dht.self)
249

250
	peers, err := dht.GetClosestPeers(ctx, key)
251 252
	if err != nil {
		return err
253 254
	}

255 256 257 258 259
	mes, err := dht.makeProvRecord(key)
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
260
	wg := sync.WaitGroup{}
261
	for p := range peers {
Jeromy's avatar
Jeromy committed
262 263 264
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
265
			log.Debugf("putProvider(%s, %s)", key, p)
266
			err := dht.sendMessage(ctx, p, mes)
Jeromy's avatar
Jeromy committed
267
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
268
				log.Debug(err)
Jeromy's avatar
Jeromy committed
269 270
			}
		}(p)
271
	}
Jeromy's avatar
Jeromy committed
272
	wg.Wait()
273
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
274
}
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
func (dht *IpfsDHT) makeProvRecord(skey key.Key) (*pb.Message, error) {
	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.")
	}

	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(skey), 0)
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]pstore.PeerInfo{pi})
	return pmes, nil
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
291

Brian Tiger Chow's avatar
Brian Tiger Chow committed
292
// FindProviders searches until the context expires.
Jeromy's avatar
Jeromy committed
293 294
func (dht *IpfsDHT) FindProviders(ctx context.Context, key key.Key) ([]pstore.PeerInfo, error) {
	var providers []pstore.PeerInfo
Jeromy's avatar
Jeromy committed
295
	for p := range dht.FindProvidersAsync(ctx, key, KValue) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
296 297 298 299 300
		providers = append(providers, p)
	}
	return providers, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
301 302 303
// 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.
Jeromy's avatar
Jeromy committed
304
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key key.Key, count int) <-chan pstore.PeerInfo {
305
	log.Event(ctx, "findProviders", &key)
Jeromy's avatar
Jeromy committed
306
	peerOut := make(chan pstore.PeerInfo, count)
Jeromy's avatar
Jeromy committed
307 308 309 310
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

Jeromy's avatar
Jeromy committed
311
func (dht *IpfsDHT) findProvidersAsyncRoutine(ctx context.Context, key key.Key, count int, peerOut chan pstore.PeerInfo) {
Jeromy's avatar
Jeromy committed
312
	defer log.EventBegin(ctx, "findProvidersAsync", &key).Done()
Jeromy's avatar
Jeromy committed
313 314
	defer close(peerOut)

Jeromy's avatar
Jeromy committed
315
	ps := pset.NewLimited(count)
Jeromy's avatar
Jeromy committed
316 317
	provs := dht.providers.GetProviders(ctx, key)
	for _, p := range provs {
318
		// NOTE: Assuming that this list of peers is unique
Jeromy's avatar
Jeromy committed
319
		if ps.TryAdd(p) {
Jeromy's avatar
Jeromy committed
320
			select {
321
			case peerOut <- dht.peerstore.PeerInfo(p):
Jeromy's avatar
Jeromy committed
322 323 324
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
325
		}
Jeromy's avatar
Jeromy committed
326 327 328

		// If we have enough peers locally, dont bother with remote RPC
		if ps.Size() >= count {
Jeromy's avatar
Jeromy committed
329 330 331 332 333
			return
		}
	}

	// setup the Query
Jeromy's avatar
Jeromy committed
334
	parent := ctx
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
335
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
336
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
337 338 339
			Type: notif.SendingQuery,
			ID:   p,
		})
340
		pmes, err := dht.findProvidersSingle(ctx, p, key)
Jeromy's avatar
Jeromy committed
341 342 343 344
		if err != nil {
			return nil, err
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
345
		log.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
346
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
347
		log.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
348 349 350

		// Add unique providers from request, up to 'count'
		for _, prov := range provs {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
351
			log.Debugf("got provider: %s", prov)
352
			if ps.TryAdd(prov.ID) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
353
				log.Debugf("using provider: %s", prov)
Jeromy's avatar
Jeromy committed
354 355 356
				select {
				case peerOut <- prov:
				case <-ctx.Done():
357
					log.Debug("context timed out sending more providers")
Jeromy's avatar
Jeromy committed
358 359
					return nil, ctx.Err()
				}
360
			}
Jeromy's avatar
Jeromy committed
361
			if ps.Size() >= count {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
362
				log.Debugf("got enough providers (%d/%d)", ps.Size(), count)
Jeromy's avatar
Jeromy committed
363
				return &dhtQueryResult{success: true}, nil
364 365 366
			}
		}

Jeromy's avatar
Jeromy committed
367 368
		// Give closer peers back to the query to be queried
		closer := pmes.GetCloserPeers()
369
		clpeers := pb.PBPeersToPeerInfos(closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
370
		log.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
371

Jeromy's avatar
Jeromy committed
372
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
373 374 375 376
			Type:      notif.PeerResponse,
			ID:        p,
			Responses: pointerizePeerInfos(clpeers),
		})
Jeromy's avatar
Jeromy committed
377 378 379
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

Jeromy's avatar
Jeromy committed
380
	peers := dht.routingTable.NearestPeers(kb.ConvertKey(key), KValue)
Jeromy's avatar
Jeromy committed
381 382
	_, err := query.Run(ctx, peers)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
383
		log.Debugf("Query error: %s", err)
384 385 386 387 388 389 390 391 392 393
		// 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>")
		}
394 395 396 397
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type:  notif.QueryError,
			Extra: err.Error(),
		})
Jeromy's avatar
Jeromy committed
398
	}
399 400
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
401
// FindPeer searches for a peer with given ID.
Jeromy's avatar
Jeromy committed
402
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (pstore.PeerInfo, error) {
Jeromy's avatar
Jeromy committed
403
	defer log.EventBegin(ctx, "FindPeer", id).Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
404

405
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
406
	if pi := dht.FindLocal(id); pi.ID != "" {
407
		return pi, nil
408 409
	}

Jeromy's avatar
Jeromy committed
410
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), KValue)
411
	if len(peers) == 0 {
Jeromy's avatar
Jeromy committed
412
		return pstore.PeerInfo{}, kb.ErrLookupFailure
413
	}
414

Jeromy's avatar
Jeromy committed
415
	// Sanity...
416
	for _, p := range peers {
417
		if p == id {
418
			log.Debug("found target peer in list of closest peers...")
419
			return dht.peerstore.PeerInfo(p), nil
420
		}
421
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
422

Jeromy's avatar
Jeromy committed
423
	// setup the Query
Jeromy's avatar
Jeromy committed
424
	parent := ctx
425
	query := dht.newQuery(key.Key(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
426
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
427 428 429
			Type: notif.SendingQuery,
			ID:   p,
		})
Jeromy's avatar
Jeromy committed
430

431
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
432
		if err != nil {
433
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
434
		}
435

Jeromy's avatar
Jeromy committed
436
		closer := pmes.GetCloserPeers()
437
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
438

439
		// see it we got the peer here
440 441
		for _, npi := range clpeerInfos {
			if npi.ID == id {
Jeromy's avatar
Jeromy committed
442
				return &dhtQueryResult{
443
					peer:    npi,
Jeromy's avatar
Jeromy committed
444 445 446
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
447 448
		}

Jeromy's avatar
Jeromy committed
449
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
450 451 452 453
			Type:      notif.PeerResponse,
			Responses: pointerizePeerInfos(clpeerInfos),
		})

454
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
455
	})
456

Jeromy's avatar
Jeromy committed
457
	// run it!
458
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
459
	if err != nil {
Jeromy's avatar
Jeromy committed
460
		return pstore.PeerInfo{}, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
461 462
	}

463
	log.Debugf("FindPeer %v %v", id, result.success)
464
	if result.peer.ID == "" {
Jeromy's avatar
Jeromy committed
465
		return pstore.PeerInfo{}, routing.ErrNotFound
466
	}
Jeromy's avatar
Jeromy committed
467

468
	return result.peer, nil
469 470
}

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

Jeromy's avatar
Jeromy committed
474 475
	peerchan := make(chan pstore.PeerInfo, asyncQueryBuffer)
	peersSeen := make(map[peer.ID]struct{})
476

Jeromy's avatar
Jeromy committed
477
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), KValue)
478
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
479
		return nil, kb.ErrLookupFailure
480 481 482
	}

	// setup the Query
483
	query := dht.newQuery(key.Key(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
484

485
		pmes, err := dht.findPeerSingle(ctx, p, id)
486 487 488 489
		if err != nil {
			return nil, err
		}

Jeromy's avatar
Jeromy committed
490
		var clpeers []pstore.PeerInfo
491 492
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
493
			pi := pb.PBPeerToPeerInfo(pbp)
494

495 496
			// skip peers already seen
			if _, found := peersSeen[pi.ID]; found {
497 498
				continue
			}
499
			peersSeen[pi.ID] = struct{}{}
500 501 502 503 504 505

			// if peer is connected, send it to our client.
			if pb.Connectedness(*pbp.Connection) == inet.Connected {
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
506
				case peerchan <- pi:
507 508 509 510
				}
			}

			// if peer is the peer we're looking for, don't bother querying it.
511
			// TODO maybe query it?
512
			if pb.Connectedness(*pbp.Connection) != inet.Connected {
513
				clpeers = append(clpeers, pi)
514 515 516 517 518 519 520 521 522
			}
		}

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

	// run it! run it asynchronously to gen peers as results are found.
	// this does no error checking
	go func() {
523
		if _, err := query.Run(ctx, peers); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
524
			log.Debug(err)
525 526 527 528 529 530 531 532
		}

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

	return peerchan, nil
}