routing.go 14.7 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)
Jeromy's avatar
Jeromy committed
180
	if err == nil {
181
		// TODO: this is tricky, we don't always want to trust our own value
182
		// what if the authoritative source updated it?
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183
		log.Debug("have it locally")
Steven Allen's avatar
Steven Allen committed
184
		vals = append(vals, RecvdVal{
185 186 187 188 189 190 191 192 193
			Val:  lrec.GetValue(),
			From: dht.self,
		})

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

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

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

212
		rec, peers, err := dht.getValueOrPeers(ctx, p, key)
213 214 215 216 217 218 219 220 221
		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,
			})
222
			return nil, err
223 224 225 226 227
		default:
			return nil, err

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

230 231
		res := &dhtQueryResult{closerPeers: peers}

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

240
			// If we have collected enough records, we're done
241 242 243 244
			if len(vals) >= nvals {
				res.success = true
			}
			valslock.Unlock()
245 246
		}

Jeromy's avatar
Jeromy committed
247
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
Jeromy's avatar
Jeromy committed
248 249
			Type:      notif.PeerResponse,
			ID:        p,
Jeromy's avatar
Jeromy committed
250
			Responses: peers,
Jeromy's avatar
Jeromy committed
251 252
		})

253 254
		return res, nil
	})
255

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

264
	return vals, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
265 266
}

267 268 269
// 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
270

271
// Provide makes this node announce that it can provide a value for the given key
272 273 274 275 276 277 278 279
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
280 281

	// add self locally
282
	dht.providers.AddProvider(ctx, key, dht.self)
Jeromy's avatar
Jeromy committed
283 284 285
	if !brdcst {
		return nil
	}
286

287
	peers, err := dht.GetClosestPeers(ctx, key.KeyString())
288 289
	if err != nil {
		return err
290 291
	}

292 293 294 295 296
	mes, err := dht.makeProvRecord(key)
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
297
	wg := sync.WaitGroup{}
298
	for p := range peers {
Jeromy's avatar
Jeromy committed
299 300 301
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
302
			log.Debugf("putProvider(%s, %s)", key, p)
303
			err := dht.sendMessage(ctx, p, mes)
Jeromy's avatar
Jeromy committed
304
			if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
305
				log.Debug(err)
Jeromy's avatar
Jeromy committed
306 307
			}
		}(p)
308
	}
Jeromy's avatar
Jeromy committed
309
	wg.Wait()
310
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
311
}
312
func (dht *IpfsDHT) makeProvRecord(skey *cid.Cid) (*pb.Message, error) {
313 314 315 316 317 318 319 320 321 322 323
	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.")
	}

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
338 339 340
// 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.
341 342
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
343
	peerOut := make(chan pstore.PeerInfo, count)
Jeromy's avatar
Jeromy committed
344 345 346 347
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

348 349
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
350 351
	defer close(peerOut)

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
384
		log.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
385
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
386
		log.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
387 388 389

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

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

Jeromy's avatar
Jeromy committed
414
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
415 416
			Type:      notif.PeerResponse,
			ID:        p,
Jeromy's avatar
Jeromy committed
417
			Responses: clpeers,
418
		})
Jeromy's avatar
Jeromy committed
419 420 421
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

Jeromy's avatar
Jeromy committed
422
	peers := dht.routingTable.NearestPeers(kb.ConvertKey(key.KeyString()), AlphaValue)
Jeromy's avatar
Jeromy committed
423 424
	_, err := query.Run(ctx, peers)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
425
		log.Debugf("Query error: %s", err)
426 427 428 429 430 431 432 433 434 435
		// 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>")
		}
436 437 438 439
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type:  notif.QueryError,
			Extra: err.Error(),
		})
Jeromy's avatar
Jeromy committed
440
	}
441 442
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
443
// FindPeer searches for a peer with given ID.
444 445 446 447 448 449 450 451
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
452

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

Jeromy's avatar
Jeromy committed
458
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
459
	if len(peers) == 0 {
Jeromy's avatar
Jeromy committed
460
		return pstore.PeerInfo{}, kb.ErrLookupFailure
461
	}
462

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

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

479
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
480
		if err != nil {
481
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
482
		}
483

Jeromy's avatar
Jeromy committed
484
		closer := pmes.GetCloserPeers()
485
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
486

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

Jeromy's avatar
Jeromy committed
497
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
498
			Type:      notif.PeerResponse,
499
			ID:        p,
Jeromy's avatar
Jeromy committed
500
			Responses: clpeerInfos,
501 502
		})

503
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
504
	})
505

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

512
	log.Debugf("FindPeer %v %v", id, result.success)
513
	if result.peer.ID == "" {
Jeromy's avatar
Jeromy committed
514
		return pstore.PeerInfo{}, routing.ErrNotFound
515
	}
Jeromy's avatar
Jeromy committed
516

Jeromy's avatar
Jeromy committed
517
	return *result.peer, nil
518 519
}

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

Jeromy's avatar
Jeromy committed
523
	peerchan := make(chan *pstore.PeerInfo, asyncQueryBuffer)
Jeromy's avatar
Jeromy committed
524
	peersSeen := make(map[peer.ID]struct{})
525
	var peersSeenMx sync.Mutex
526

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

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

535
		pmes, err := dht.findPeerSingle(ctx, p, id)
536 537 538 539
		if err != nil {
			return nil, err
		}

Jeromy's avatar
Jeromy committed
540
		var clpeers []*pstore.PeerInfo
541 542
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
543
			pi := pb.PBPeerToPeerInfo(pbp)
544

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

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

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

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

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

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

	return peerchan, nil
}