routing.go 14.2 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"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24 25
)

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

// Basic Put/Get

// PutValue adds value corresponding to given Key.
37
// This is the top level "Store" operation of the DHT
38 39 40 41 42 43 44 45 46
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
47
	log.Debugf("PutValue %s", key)
Jeromy's avatar
Jeromy committed
48

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

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

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

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

// GetValue searches for the value corresponding to given Key.
84 85 86 87 88 89 90 91 92
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
93 94 95 96
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()

	vals, err := dht.GetValues(ctx, key, 16)
97 98 99 100
	if err != nil {
		return nil, err
	}

Steven Allen's avatar
Steven Allen committed
101
	recs := make([][]byte, 0, len(vals))
102
	for _, v := range vals {
103 104 105
		if v.Val != nil {
			recs = append(recs, v.Val)
		}
106
	}
107 108 109
	if len(recs) == 0 {
		return nil, routing.ErrNotFound
	}
110 111 112 113 114 115 116 117 118 119 120 121 122

	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
	}

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

	return best, nil
}

148 149 150 151 152 153 154 155 156
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
157
	vals := make([]routing.RecvdVal, 0, nvals)
158 159
	var valslock sync.Mutex

Jeromy's avatar
Jeromy committed
160
	// If we have it local, dont bother doing an RPC!
161
	lrec, err := dht.getLocal(key)
Jeromy's avatar
Jeromy committed
162
	if err == nil {
163 164
		// 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
165
		log.Debug("have it locally")
166 167 168 169 170 171 172 173 174 175
		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
176 177
	}

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

186
	// setup the Query
Jeromy's avatar
Jeromy committed
187
	parent := ctx
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
189
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
Jeromy's avatar
Jeromy committed
190 191 192 193
			Type: notif.SendingQuery,
			ID:   p,
		})

194
		rec, peers, err := dht.getValueOrPeers(ctx, p, key)
195 196 197 198 199 200 201 202 203
		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,
			})
204
			return nil, err
205 206 207 208 209
		default:
			return nil, err

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

212 213
		res := &dhtQueryResult{closerPeers: peers}

214
		if rec.GetValue() != nil || err == errInvalidRecord {
215 216 217 218 219 220 221 222 223 224 225 226
			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()
227 228
		}

Jeromy's avatar
Jeromy committed
229
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
Jeromy's avatar
Jeromy committed
230 231
			Type:      notif.PeerResponse,
			ID:        p,
Jeromy's avatar
Jeromy committed
232
			Responses: peers,
Jeromy's avatar
Jeromy committed
233 234
		})

235 236
		return res, nil
	})
237

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238
	// run it!
239 240 241 242 243
	_, err = query.Run(ctx, rtp)
	if len(vals) == 0 {
		if err != nil {
			return nil, err
		}
244 245
	}

246
	return vals, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247 248 249 250 251
}

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

252
// Provide makes this node announce that it can provide a value for the given key
253 254 255 256 257 258 259 260
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
261 262

	// add self locally
263
	dht.providers.AddProvider(ctx, key, dht.self)
Jeromy's avatar
Jeromy committed
264 265 266
	if !brdcst {
		return nil
	}
267

268
	peers, err := dht.GetClosestPeers(ctx, key.KeyString())
269 270
	if err != nil {
		return err
271 272
	}

273 274 275 276 277
	mes, err := dht.makeProvRecord(key)
	if err != nil {
		return err
	}

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

305
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, skey.KeyString(), 0)
306 307 308
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]pstore.PeerInfo{pi})
	return pmes, nil
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
309

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
319 320 321
// 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.
322 323
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
324
	peerOut := make(chan pstore.PeerInfo, count)
Jeromy's avatar
Jeromy committed
325 326 327 328
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

329 330
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
331 332
	defer close(peerOut)

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

		// If we have enough peers locally, dont bother with remote RPC
Jeromy's avatar
Jeromy committed
347
		// TODO: is this a DOS vector?
Jeromy's avatar
Jeromy committed
348
		if ps.Size() >= count {
Jeromy's avatar
Jeromy committed
349 350 351 352 353
			return
		}
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
365
		log.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
366
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
367
		log.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
368 369 370

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

Jeromy's avatar
Jeromy committed
390 391
		// Give closer peers back to the query to be queried
		closer := pmes.GetCloserPeers()
392
		clpeers := pb.PBPeersToPeerInfos(closer)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
393
		log.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
394

Jeromy's avatar
Jeromy committed
395
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
396 397
			Type:      notif.PeerResponse,
			ID:        p,
Jeromy's avatar
Jeromy committed
398
			Responses: clpeers,
399
		})
Jeromy's avatar
Jeromy committed
400 401 402
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
424
// FindPeer searches for a peer with given ID.
425 426 427 428 429 430 431 432
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
433

434
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
435
	if pi := dht.FindLocal(id); pi.ID != "" {
436
		return pi, nil
437 438
	}

Jeromy's avatar
Jeromy committed
439
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
440
	if len(peers) == 0 {
Jeromy's avatar
Jeromy committed
441
		return pstore.PeerInfo{}, kb.ErrLookupFailure
442
	}
443

Jeromy's avatar
Jeromy committed
444
	// Sanity...
445
	for _, p := range peers {
446
		if p == id {
447
			log.Debug("found target peer in list of closest peers...")
448
			return dht.peerstore.PeerInfo(p), nil
449
		}
450
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
451

Jeromy's avatar
Jeromy committed
452
	// setup the Query
Jeromy's avatar
Jeromy committed
453
	parent := ctx
454
	query := dht.newQuery(string(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
455
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
456 457 458
			Type: notif.SendingQuery,
			ID:   p,
		})
Jeromy's avatar
Jeromy committed
459

460
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
461
		if err != nil {
462
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
463
		}
464

Jeromy's avatar
Jeromy committed
465
		closer := pmes.GetCloserPeers()
466
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
467

468
		// see if we got the peer here
469 470
		for _, npi := range clpeerInfos {
			if npi.ID == id {
Jeromy's avatar
Jeromy committed
471
				return &dhtQueryResult{
472
					peer:    npi,
Jeromy's avatar
Jeromy committed
473 474 475
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
476 477
		}

Jeromy's avatar
Jeromy committed
478
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
479
			Type:      notif.PeerResponse,
480
			ID:        p,
Jeromy's avatar
Jeromy committed
481
			Responses: clpeerInfos,
482 483
		})

484
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
485
	})
486

Jeromy's avatar
Jeromy committed
487
	// run it!
488
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
489
	if err != nil {
Jeromy's avatar
Jeromy committed
490
		return pstore.PeerInfo{}, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
491 492
	}

493
	log.Debugf("FindPeer %v %v", id, result.success)
494
	if result.peer.ID == "" {
Jeromy's avatar
Jeromy committed
495
		return pstore.PeerInfo{}, routing.ErrNotFound
496
	}
Jeromy's avatar
Jeromy committed
497

Jeromy's avatar
Jeromy committed
498
	return *result.peer, nil
499 500
}

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

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

Jeromy's avatar
Jeromy committed
507
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
508
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
509
		return nil, kb.ErrLookupFailure
510 511 512
	}

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

515
		pmes, err := dht.findPeerSingle(ctx, p, id)
516 517 518 519
		if err != nil {
			return nil, err
		}

Jeromy's avatar
Jeromy committed
520
		var clpeers []*pstore.PeerInfo
521 522
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
523
			pi := pb.PBPeerToPeerInfo(pbp)
524

525 526
			// skip peers already seen
			if _, found := peersSeen[pi.ID]; found {
527 528
				continue
			}
529
			peersSeen[pi.ID] = struct{}{}
530 531 532 533 534 535

			// if peer is connected, send it to our client.
			if pb.Connectedness(*pbp.Connection) == inet.Connected {
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
536
				case peerchan <- pi:
537 538 539 540
				}
			}

			// if peer is the peer we're looking for, don't bother querying it.
541
			// TODO maybe query it?
542
			if pb.Connectedness(*pbp.Connection) != inet.Connected {
543
				clpeers = append(clpeers, pi)
544 545 546 547 548 549 550 551 552
			}
		}

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

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

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

	return peerchan, nil
}