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
	peerOut := make(chan peer.AddrInfo, count)
513
	if !dht.enableProviders {
514 515
		close(peerOut)
		return peerOut
516 517
	}

Matt Joiner's avatar
Matt Joiner committed
518
	logger.Event(ctx, "findProviders", key)
519

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

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

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

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

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

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

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

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

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

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

	_, err := query.Run(ctx, peers)
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
609
		logger.Debugf("Query error: %s", err)
610 611
		// Special handling for issue: https://github.com/ipfs/go-ipfs/issues/3032
		if fmt.Sprint(err) == "<nil>" {
Matt Joiner's avatar
Matt Joiner committed
612 613 614 615
			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")
616 617 618 619

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

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

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

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

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

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

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

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

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

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

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

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

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

699 700 701
	// 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
702
	logger.Debugf("FindPeer %v %v", id, result.success)
703
	if result.peer.ID == "" {
704
		return peer.AddrInfo{}, routing.ErrNotFound
705
	}
Jeromy's avatar
Jeromy committed
706

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return peerchan, nil
}