routing.go 19.1 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 12 13 14 15
	"github.com/libp2p/go-libp2p-core/network"
	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/libp2p/go-libp2p-core/peerstore"
	"github.com/libp2p/go-libp2p-core/routing"

16
	"github.com/ipfs/go-cid"
17
	u "github.com/ipfs/go-ipfs-util"
Jeromy's avatar
Jeromy committed
18
	logging "github.com/ipfs/go-log"
19
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
George Antoniadis's avatar
George Antoniadis committed
20 21
	kb "github.com/libp2p/go-libp2p-kbucket"
	record "github.com/libp2p/go-libp2p-record"
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 string, value []byte, opts ...routing.Option) (err error) {
37 38 39 40
	if !dht.enableValues {
		return routing.ErrNotSupported
	}

Matt Joiner's avatar
Matt Joiner committed
41
	eip := logger.EventBegin(ctx, "PutValue")
42 43 44 45 46 47 48
	defer func() {
		eip.Append(loggableKey(key))
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Matt Joiner's avatar
Matt Joiner committed
49
	logger.Debugf("PutValue %s", key)
Jeromy's avatar
Jeromy committed
50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
	// don't even allow local users to put bad values.
	if err := dht.Validator.Validate(key, value); err != nil {
		return err
	}

	old, err := dht.getLocal(key)
	if err != nil {
		// Means something is wrong with the datastore.
		return err
	}

	// Check if we have an old value that's not the same as the new one.
	if old != nil && !bytes.Equal(old.GetValue(), value) {
		// Check to see if the new one is better.
		i, err := dht.Validator.Select(key, [][]byte{value, old.GetValue()})
		if err != nil {
			return err
		}
		if i != 0 {
			return fmt.Errorf("can't replace a newer value with an older value")
		}
	}

74
	rec := record.MakePutRecord(key, value)
75
	rec.TimeReceived = u.FormatRFC3339(time.Now())
Jeromy's avatar
Jeromy committed
76
	err = dht.putLocal(key, rec)
77 78 79 80
	if err != nil {
		return err
	}

81
	pchan, err := dht.GetClosestPeers(ctx, key)
82 83 84
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85

86 87 88 89
	wg := sync.WaitGroup{}
	for p := range pchan {
		wg.Add(1)
		go func(p peer.ID) {
Jeromy's avatar
Jeromy committed
90 91
			ctx, cancel := context.WithCancel(ctx)
			defer cancel()
92
			defer wg.Done()
93 94
			routing.PublishQueryEvent(ctx, &routing.QueryEvent{
				Type: routing.Value,
Jeromy's avatar
Jeromy committed
95 96 97
				ID:   p,
			})

98
			err := dht.putValueToPeer(ctx, p, rec)
99
			if err != nil {
Matt Joiner's avatar
Matt Joiner committed
100
				logger.Debugf("failed putting value to peer: %s", err)
101 102 103 104
			}
		}(p)
	}
	wg.Wait()
105

106
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107 108
}

Steven Allen's avatar
Steven Allen committed
109 110 111 112 113 114
// 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
115
// GetValue searches for the value corresponding to given Key.
116
func (dht *IpfsDHT) GetValue(ctx context.Context, key string, opts ...routing.Option) (_ []byte, err error) {
117 118 119 120
	if !dht.enableValues {
		return nil, routing.ErrNotSupported
	}

Matt Joiner's avatar
Matt Joiner committed
121
	eip := logger.EventBegin(ctx, "GetValue")
122 123 124 125 126 127 128
	defer func() {
		eip.Append(loggableKey(key))
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Jeromy's avatar
Jeromy committed
129

130
	// apply defaultQuorum if relevant
131
	var cfg routing.Options
132 133 134 135 136
	if err := cfg.Apply(opts...); err != nil {
		return nil, err
	}
	opts = append(opts, Quorum(getQuorum(&cfg, defaultQuorum)))

137 138 139 140
	responses, err := dht.SearchValue(ctx, key, opts...)
	if err != nil {
		return nil, err
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
141 142
	var best []byte

143 144
	for r := range responses {
		best = r
Łukasz Magiera's avatar
Łukasz Magiera committed
145 146
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
147 148 149 150
	if ctx.Err() != nil {
		return best, ctx.Err()
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
151 152 153
	if best == nil {
		return nil, routing.ErrNotFound
	}
Matt Joiner's avatar
Matt Joiner committed
154
	logger.Debugf("GetValue %v %v", key, best)
Łukasz Magiera's avatar
Łukasz Magiera committed
155 156 157
	return best, nil
}

158
func (dht *IpfsDHT) SearchValue(ctx context.Context, key string, opts ...routing.Option) (<-chan []byte, error) {
159 160 161 162
	if !dht.enableValues {
		return nil, routing.ErrNotSupported
	}

163
	var cfg routing.Options
Steven Allen's avatar
Steven Allen committed
164
	if err := cfg.Apply(opts...); err != nil {
165
		return nil, err
Steven Allen's avatar
Steven Allen committed
166 167 168 169
	}

	responsesNeeded := 0
	if !cfg.Offline {
170
		responsesNeeded = getQuorum(&cfg, -1)
Steven Allen's avatar
Steven Allen committed
171 172
	}

173 174 175 176 177 178
	valCh, err := dht.getValues(ctx, key, responsesNeeded)
	if err != nil {
		return nil, err
	}

	out := make(chan []byte)
Łukasz Magiera's avatar
Łukasz Magiera committed
179 180
	go func() {
		defer close(out)
181

Łukasz Magiera's avatar
Łukasz Magiera committed
182 183 184 185
		maxVals := responsesNeeded
		if maxVals < 0 {
			maxVals = defaultQuorum * 4 // we want some upper bound on how
			// much correctional entries we will send
186
		}
187 188 189

		// vals is used collect entries we got so far and send corrections to peers
		// when we exit this function
Łukasz Magiera's avatar
Łukasz Magiera committed
190
		vals := make([]RecvdVal, 0, maxVals)
191
		var best *RecvdVal
192

Łukasz Magiera's avatar
Łukasz Magiera committed
193
		defer func() {
194
			if len(vals) <= 1 || best == nil {
Łukasz Magiera's avatar
Łukasz Magiera committed
195 196
				return
			}
197
			fixupRec := record.MakePutRecord(key, best.Val)
Łukasz Magiera's avatar
Łukasz Magiera committed
198 199
			for _, v := range vals {
				// if someone sent us a different 'less-valid' record, lets correct them
200
				if !bytes.Equal(v.Val, best.Val) {
Łukasz Magiera's avatar
Łukasz Magiera committed
201 202 203 204
					go func(v RecvdVal) {
						if v.From == dht.self {
							err := dht.putLocal(key, fixupRec)
							if err != nil {
Matt Joiner's avatar
Matt Joiner committed
205
								logger.Error("Error correcting local dht entry:", err)
Łukasz Magiera's avatar
Łukasz Magiera committed
206 207 208 209 210 211 212
							}
							return
						}
						ctx, cancel := context.WithTimeout(dht.Context(), time.Second*30)
						defer cancel()
						err := dht.putValueToPeer(ctx, v.From, fixupRec)
						if err != nil {
Matt Joiner's avatar
Matt Joiner committed
213
							logger.Debug("Error correcting DHT entry: ", err)
Łukasz Magiera's avatar
Łukasz Magiera committed
214 215 216 217 218
						}
					}(v)
				}
			}
		}()
219

Łukasz Magiera's avatar
Łukasz Magiera committed
220 221 222 223
		for {
			select {
			case v, ok := <-valCh:
				if !ok {
224
					return
Łukasz Magiera's avatar
Łukasz Magiera committed
225 226
				}

Łukasz Magiera's avatar
Łukasz Magiera committed
227 228 229
				if len(vals) < maxVals {
					vals = append(vals, v)
				}
230

Łukasz Magiera's avatar
Łukasz Magiera committed
231 232 233 234
				if v.Val == nil {
					continue
				}
				// Select best value
235
				if best != nil {
Steven Allen's avatar
Steven Allen committed
236 237 238
					if bytes.Equal(best.Val, v.Val) {
						continue
					}
239
					sel, err := dht.Validator.Select(key, [][]byte{best.Val, v.Val})
240
					if err != nil {
Matt Joiner's avatar
Matt Joiner committed
241
						logger.Warning("Failed to select dht key: ", err)
Łukasz Magiera's avatar
Łukasz Magiera committed
242
						continue
Łukasz Magiera's avatar
Łukasz Magiera committed
243
					}
Steven Allen's avatar
Steven Allen committed
244 245
					if sel != 1 {
						continue
246 247
					}
				}
Steven Allen's avatar
Steven Allen committed
248 249 250 251 252 253
				best = &v
				select {
				case out <- v.Val:
				case <-ctx.Done():
					return
				}
Łukasz Magiera's avatar
Łukasz Magiera committed
254 255 256
			case <-ctx.Done():
				return
			}
257
		}
Łukasz Magiera's avatar
Łukasz Magiera committed
258
	}()
259

260
	return out, nil
261 262
}

Steven Allen's avatar
Steven Allen committed
263
// GetValues gets nvals values corresponding to the given key.
264
func (dht *IpfsDHT) GetValues(ctx context.Context, key string, nvals int) (_ []RecvdVal, err error) {
265 266 267
	if !dht.enableValues {
		return nil, routing.ErrNotSupported
	}
268

269
	eip := logger.EventBegin(ctx, "GetValues")
270 271 272
	eip.Append(loggableKey(key))
	defer eip.Done()

273 274
	valCh, err := dht.getValues(ctx, key, nvals)
	if err != nil {
275
		eip.SetError(err)
276 277 278 279 280 281 282 283
		return nil, err
	}

	out := make([]RecvdVal, 0, nvals)
	for val := range valCh {
		out = append(out, val)
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
284
	return out, ctx.Err()
285 286
}

287
func (dht *IpfsDHT) getValues(ctx context.Context, key string, nvals int) (<-chan RecvdVal, error) {
288
	vals := make(chan RecvdVal, 1)
Łukasz Magiera's avatar
Łukasz Magiera committed
289

290
	done := func(err error) (<-chan RecvdVal, error) {
Łukasz Magiera's avatar
Łukasz Magiera committed
291
		defer close(vals)
292
		return vals, err
Łukasz Magiera's avatar
Łukasz Magiera committed
293
	}
294

295
	// If we have it local, don't bother doing an RPC!
296
	lrec, err := dht.getLocal(key)
297 298
	if err != nil {
		// something is wrong with the datastore.
Łukasz Magiera's avatar
Łukasz Magiera committed
299
		return done(err)
300 301
	}
	if lrec != nil {
302
		// TODO: this is tricky, we don't always want to trust our own value
303
		// what if the authoritative source updated it?
Matt Joiner's avatar
Matt Joiner committed
304
		logger.Debug("have it locally")
Łukasz Magiera's avatar
Łukasz Magiera committed
305
		vals <- RecvdVal{
306 307
			Val:  lrec.GetValue(),
			From: dht.self,
Łukasz Magiera's avatar
Łukasz Magiera committed
308
		}
309

310
		if nvals == 0 || nvals == 1 {
Łukasz Magiera's avatar
Łukasz Magiera committed
311
			return done(nil)
312
		}
Łukasz Magiera's avatar
Łukasz Magiera committed
313 314

		nvals--
315
	} else if nvals == 0 {
Łukasz Magiera's avatar
Łukasz Magiera committed
316
		return done(routing.ErrNotFound)
Jeromy's avatar
Jeromy committed
317 318
	}

319
	// get closest peers in the routing table
Jeromy's avatar
Jeromy committed
320
	rtp := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
Matt Joiner's avatar
Matt Joiner committed
321
	logger.Debugf("peers in rt: %d %s", len(rtp), rtp)
322
	if len(rtp) == 0 {
Matt Joiner's avatar
Matt Joiner committed
323
		logger.Warning("No peers from routing table!")
Łukasz Magiera's avatar
Łukasz Magiera committed
324
		return done(kb.ErrLookupFailure)
325 326
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
327 328 329
	var valslock sync.Mutex
	var got int

330
	// setup the Query
Jeromy's avatar
Jeromy committed
331
	parent := ctx
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
332
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
333 334
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type: routing.SendingQuery,
Jeromy's avatar
Jeromy committed
335 336 337
			ID:   p,
		})

338
		rec, peers, err := dht.getValueOrPeers(ctx, p, key)
339 340 341 342 343
		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'
344 345
			routing.PublishQueryEvent(parent, &routing.QueryEvent{
				Type: routing.PeerResponse,
346 347
				ID:   p,
			})
348
			return nil, err
349 350 351 352 353
		default:
			return nil, err

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

356 357
		res := &dhtQueryResult{closerPeers: peers}

358
		if rec.GetValue() != nil || err == errInvalidRecord {
Steven Allen's avatar
Steven Allen committed
359
			rv := RecvdVal{
360 361 362 363
				Val:  rec.GetValue(),
				From: p,
			}
			valslock.Lock()
364 365 366 367 368 369
			select {
			case vals <- rv:
			case <-ctx.Done():
				valslock.Unlock()
				return nil, ctx.Err()
			}
Łukasz Magiera's avatar
Łukasz Magiera committed
370
			got++
371

372
			// If we have collected enough records, we're done
Łukasz Magiera's avatar
Łukasz Magiera committed
373
			if nvals == got {
374 375 376
				res.success = true
			}
			valslock.Unlock()
377 378
		}

379 380
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type:      routing.PeerResponse,
Jeromy's avatar
Jeromy committed
381
			ID:        p,
Jeromy's avatar
Jeromy committed
382
			Responses: peers,
Jeromy's avatar
Jeromy committed
383 384
		})

385 386
		return res, nil
	})
387

Łukasz Magiera's avatar
Łukasz Magiera committed
388 389 390 391 392 393 394 395 396 397 398
	go func() {
		reqCtx, cancel := context.WithTimeout(ctx, time.Minute)
		defer cancel()

		_, err = query.Run(reqCtx, rtp)

		// We do have some values but we either ran out of peers to query or
		// searched for a whole minute.
		//
		// We'll just call this a success.
		if got > 0 && (err == routing.ErrNotFound || reqCtx.Err() == context.DeadlineExceeded) {
399 400 401
			// refresh the k-bucket containing this key as the query was successful
			dht.routingTable.BucketForID(kb.ConvertKey(key)).ResetRefreshedAt(time.Now())

Łukasz Magiera's avatar
Łukasz Magiera committed
402 403 404 405
			err = nil
		}
		done(err)
	}()
406

407
	return vals, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
408 409
}

410 411 412
// 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
413

414
// Provide makes this node announce that it can provide a value for the given key
415
func (dht *IpfsDHT) Provide(ctx context.Context, key cid.Cid, brdcst bool) (err error) {
416 417 418
	if !dht.enableProviders {
		return routing.ErrNotSupported
	}
Matt Joiner's avatar
Matt Joiner committed
419
	eip := logger.EventBegin(ctx, "Provide", key, logging.LoggableMap{"broadcast": brdcst})
420 421 422 423 424 425
	defer func() {
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
426 427

	// add self locally
428
	dht.providers.AddProvider(ctx, key, dht.self)
Jeromy's avatar
Jeromy committed
429 430 431
	if !brdcst {
		return nil
	}
432

433 434 435 436 437 438 439 440 441 442
	closerCtx := ctx
	if deadline, ok := ctx.Deadline(); ok {
		now := time.Now()
		timeout := deadline.Sub(now)

		if timeout < 0 {
			// timed out
			return context.DeadlineExceeded
		} else if timeout < 10*time.Second {
			// Reserve 10% for the final put.
443
			deadline = deadline.Add(-timeout / 10)
444 445 446 447 448 449 450 451 452 453 454
		} else {
			// Otherwise, reserve a second (we'll already be
			// connected so this should be fast).
			deadline = deadline.Add(-time.Second)
		}
		var cancel context.CancelFunc
		closerCtx, cancel = context.WithDeadline(ctx, deadline)
		defer cancel()
	}

	peers, err := dht.GetClosestPeers(closerCtx, key.KeyString())
455 456
	if err != nil {
		return err
457 458
	}

459 460 461 462 463
	mes, err := dht.makeProvRecord(key)
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
464
	wg := sync.WaitGroup{}
465
	for p := range peers {
Jeromy's avatar
Jeromy committed
466 467 468
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Matt Joiner's avatar
Matt Joiner committed
469
			logger.Debugf("putProvider(%s, %s)", key, p)
470
			err := dht.sendMessage(ctx, p, mes)
Jeromy's avatar
Jeromy committed
471
			if err != nil {
Matt Joiner's avatar
Matt Joiner committed
472
				logger.Debug(err)
Jeromy's avatar
Jeromy committed
473 474
			}
		}(p)
475
	}
Jeromy's avatar
Jeromy committed
476
	wg.Wait()
477
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
478
}
479
func (dht *IpfsDHT) makeProvRecord(skey cid.Cid) (*pb.Message, error) {
480
	pi := peer.AddrInfo{
481 482 483 484 485 486 487 488 489 490
		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.")
	}

491
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, skey.Bytes(), 0)
492
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]peer.AddrInfo{pi})
493 494
	return pmes, nil
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
495

Brian Tiger Chow's avatar
Brian Tiger Chow committed
496
// FindProviders searches until the context expires.
497
func (dht *IpfsDHT) FindProviders(ctx context.Context, c cid.Cid) ([]peer.AddrInfo, error) {
498 499 500
	if !dht.enableProviders {
		return nil, routing.ErrNotSupported
	}
501
	var providers []peer.AddrInfo
502
	for p := range dht.FindProvidersAsync(ctx, c, dht.bucketSize) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
503 504 505 506 507
		providers = append(providers, p)
	}
	return providers, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
508 509 510
// 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.
511
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key cid.Cid, count int) <-chan peer.AddrInfo {
512 513 514 515
	if !dht.enableProviders {
		return nil
	}

Matt Joiner's avatar
Matt Joiner committed
516
	logger.Event(ctx, "findProviders", key)
517
	peerOut := make(chan peer.AddrInfo, count)
518

Jeromy's avatar
Jeromy committed
519 520 521 522
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

523
func (dht *IpfsDHT) findProvidersAsyncRoutine(ctx context.Context, key cid.Cid, count int, peerOut chan peer.AddrInfo) {
Matt Joiner's avatar
Matt Joiner committed
524
	defer logger.EventBegin(ctx, "findProvidersAsync", key).Done()
Jeromy's avatar
Jeromy committed
525 526
	defer close(peerOut)

527
	ps := peer.NewLimitedSet(count)
Jeromy's avatar
Jeromy committed
528 529
	provs := dht.providers.GetProviders(ctx, key)
	for _, p := range provs {
530
		// NOTE: Assuming that this list of peers is unique
Jeromy's avatar
Jeromy committed
531
		if ps.TryAdd(p) {
Jeromy's avatar
Jeromy committed
532
			pi := dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
533
			select {
Jeromy's avatar
Jeromy committed
534
			case peerOut <- pi:
Jeromy's avatar
Jeromy committed
535 536 537
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
538
		}
Jeromy's avatar
Jeromy committed
539

540
		// If we have enough peers locally, don't bother with remote RPC
Jeromy's avatar
Jeromy committed
541
		// TODO: is this a DOS vector?
Jeromy's avatar
Jeromy committed
542
		if ps.Size() >= count {
Jeromy's avatar
Jeromy committed
543 544 545 546
			return
		}
	}

547 548
	peers := dht.routingTable.NearestPeers(kb.ConvertKey(key.KeyString()), AlphaValue)
	if len(peers) == 0 {
549 550
		routing.PublishQueryEvent(ctx, &routing.QueryEvent{
			Type:  routing.QueryError,
551 552 553 554 555
			Extra: kb.ErrLookupFailure.Error(),
		})
		return
	}

Jeromy's avatar
Jeromy committed
556
	// setup the Query
Jeromy's avatar
Jeromy committed
557
	parent := ctx
558
	query := dht.newQuery(key.KeyString(), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
559 560
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type: routing.SendingQuery,
561 562
			ID:   p,
		})
563
		pmes, err := dht.findProvidersSingle(ctx, p, key)
Jeromy's avatar
Jeromy committed
564 565 566 567
		if err != nil {
			return nil, err
		}

Matt Joiner's avatar
Matt Joiner committed
568
		logger.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
569
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Matt Joiner's avatar
Matt Joiner committed
570
		logger.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
571 572 573

		// Add unique providers from request, up to 'count'
		for _, prov := range provs {
574
			if prov.ID != dht.self {
575
				dht.peerstore.AddAddrs(prov.ID, prov.Addrs, peerstore.TempAddrTTL)
576
			}
Matt Joiner's avatar
Matt Joiner committed
577
			logger.Debugf("got provider: %s", prov)
578
			if ps.TryAdd(prov.ID) {
Matt Joiner's avatar
Matt Joiner committed
579
				logger.Debugf("using provider: %s", prov)
Jeromy's avatar
Jeromy committed
580
				select {
Jeromy's avatar
Jeromy committed
581
				case peerOut <- *prov:
Jeromy's avatar
Jeromy committed
582
				case <-ctx.Done():
Matt Joiner's avatar
Matt Joiner committed
583
					logger.Debug("context timed out sending more providers")
Jeromy's avatar
Jeromy committed
584 585
					return nil, ctx.Err()
				}
586
			}
Jeromy's avatar
Jeromy committed
587
			if ps.Size() >= count {
Matt Joiner's avatar
Matt Joiner committed
588
				logger.Debugf("got enough providers (%d/%d)", ps.Size(), count)
Jeromy's avatar
Jeromy committed
589
				return &dhtQueryResult{success: true}, nil
590 591 592
			}
		}

Jeromy's avatar
Jeromy committed
593 594
		// Give closer peers back to the query to be queried
		closer := pmes.GetCloserPeers()
595
		clpeers := pb.PBPeersToPeerInfos(closer)
Matt Joiner's avatar
Matt Joiner committed
596
		logger.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
597

598 599
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type:      routing.PeerResponse,
600
			ID:        p,
Jeromy's avatar
Jeromy committed
601
			Responses: clpeers,
602
		})
Jeromy's avatar
Jeromy committed
603 604 605 606 607
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

	_, err := query.Run(ctx, peers)
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
608
		logger.Debugf("Query error: %s", err)
609 610
		// Special handling for issue: https://github.com/ipfs/go-ipfs/issues/3032
		if fmt.Sprint(err) == "<nil>" {
Matt Joiner's avatar
Matt Joiner committed
611 612 613 614
			logger.Error("reproduced bug 3032:")
			logger.Errorf("Errors type information: %#v", err)
			logger.Errorf("go version: %s", runtime.Version())
			logger.Error("please report this information to: https://github.com/ipfs/go-ipfs/issues/3032")
615 616 617 618

			// replace problematic error with something that won't crash the daemon
			err = fmt.Errorf("<nil>")
		}
619 620
		routing.PublishQueryEvent(ctx, &routing.QueryEvent{
			Type:  routing.QueryError,
621 622
			Extra: err.Error(),
		})
Jeromy's avatar
Jeromy committed
623
	}
624 625 626

	// refresh the k-bucket containing this key after the query is run
	dht.routingTable.BucketForID(kb.ConvertKey(key.KeyString())).ResetRefreshedAt(time.Now())
627 628
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
629
// FindPeer searches for a peer with given ID.
630
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (_ peer.AddrInfo, err error) {
Matt Joiner's avatar
Matt Joiner committed
631
	eip := logger.EventBegin(ctx, "FindPeer", id)
632 633 634 635 636 637
	defer func() {
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
638

639
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
640
	if pi := dht.FindLocal(id); pi.ID != "" {
641
		return pi, nil
642 643
	}

Jeromy's avatar
Jeromy committed
644
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
645
	if len(peers) == 0 {
646
		return peer.AddrInfo{}, kb.ErrLookupFailure
647
	}
648

Jeromy's avatar
Jeromy committed
649
	// Sanity...
650
	for _, p := range peers {
651
		if p == id {
Matt Joiner's avatar
Matt Joiner committed
652
			logger.Debug("found target peer in list of closest peers...")
653
			return dht.peerstore.PeerInfo(p), nil
654
		}
655
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
656

Jeromy's avatar
Jeromy committed
657
	// setup the Query
Jeromy's avatar
Jeromy committed
658
	parent := ctx
659
	query := dht.newQuery(string(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
660 661
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type: routing.SendingQuery,
662 663
			ID:   p,
		})
Jeromy's avatar
Jeromy committed
664

665
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
666
		if err != nil {
667
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
668
		}
669

Jeromy's avatar
Jeromy committed
670
		closer := pmes.GetCloserPeers()
671
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
672

673
		// see if we got the peer here
674 675
		for _, npi := range clpeerInfos {
			if npi.ID == id {
Jeromy's avatar
Jeromy committed
676
				return &dhtQueryResult{
677
					peer:    npi,
Jeromy's avatar
Jeromy committed
678 679 680
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
681 682
		}

683 684
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type:      routing.PeerResponse,
685
			ID:        p,
Jeromy's avatar
Jeromy committed
686
			Responses: clpeerInfos,
687 688
		})

689
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
690
	})
691

Jeromy's avatar
Jeromy committed
692
	// run it!
693
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
694
	if err != nil {
695
		return peer.AddrInfo{}, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
696 697
	}

698 699 700
	// refresh the k-bucket containing this key since the lookup was successful
	dht.routingTable.BucketForID(kb.ConvertPeerID(id)).ResetRefreshedAt(time.Now())

Matt Joiner's avatar
Matt Joiner committed
701
	logger.Debugf("FindPeer %v %v", id, result.success)
702
	if result.peer.ID == "" {
703
		return peer.AddrInfo{}, routing.ErrNotFound
704
	}
Jeromy's avatar
Jeromy committed
705

Jeromy's avatar
Jeromy committed
706
	return *result.peer, nil
707 708
}

709
// FindPeersConnectedToPeer searches for peers directly connected to a given peer.
710
func (dht *IpfsDHT) FindPeersConnectedToPeer(ctx context.Context, id peer.ID) (<-chan *peer.AddrInfo, error) {
711

712
	peerchan := make(chan *peer.AddrInfo, asyncQueryBuffer)
Jeromy's avatar
Jeromy committed
713
	peersSeen := make(map[peer.ID]struct{})
714
	var peersSeenMx sync.Mutex
715

Jeromy's avatar
Jeromy committed
716
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
717
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
718
		return nil, kb.ErrLookupFailure
719 720 721
	}

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

724
		pmes, err := dht.findPeerSingle(ctx, p, id)
725 726 727 728
		if err != nil {
			return nil, err
		}

729
		var clpeers []*peer.AddrInfo
730 731
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
732
			pi := pb.PBPeerToPeerInfo(pbp)
733

734
			// skip peers already seen
735
			peersSeenMx.Lock()
736
			if _, found := peersSeen[pi.ID]; found {
737
				peersSeenMx.Unlock()
738 739
				continue
			}
740
			peersSeen[pi.ID] = struct{}{}
741
			peersSeenMx.Unlock()
742 743

			// if peer is connected, send it to our client.
744
			if pb.Connectedness(pbp.Connection) == network.Connected {
745 746 747
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
748
				case peerchan <- pi:
749 750 751 752
				}
			}

			// if peer is the peer we're looking for, don't bother querying it.
753
			// TODO maybe query it?
754
			if pb.Connectedness(pbp.Connection) != network.Connected {
755
				clpeers = append(clpeers, pi)
756 757 758 759 760 761 762 763 764
			}
		}

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

	// run it! run it asynchronously to gen peers as results are found.
	// this does no error checking
	go func() {
765
		if _, err := query.Run(ctx, peers); err != nil {
Matt Joiner's avatar
Matt Joiner committed
766
			logger.Debug(err)
767 768
		}

769 770 771
		// refresh the k-bucket containing this key
		dht.routingTable.BucketForID(kb.ConvertPeerID(id)).ResetRefreshedAt(time.Now())

772 773 774 775 776 777
		// close the peerchan channel when done.
		close(peerchan)
	}()

	return peerchan, nil
}