routing.go 18.6 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) {
Matt Joiner's avatar
Matt Joiner committed
37
	eip := logger.EventBegin(ctx, "PutValue")
38 39 40 41 42 43 44
	defer func() {
		eip.Append(loggableKey(key))
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Matt Joiner's avatar
Matt Joiner committed
45
	logger.Debugf("PutValue %s", key)
Jeromy's avatar
Jeromy committed
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	// 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")
		}
	}

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

77
	pchan, err := dht.GetClosestPeers(ctx, key)
78 79 80
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
81

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

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

102
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103 104
}

Steven Allen's avatar
Steven Allen committed
105 106 107 108 109 110
// 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
111
// GetValue searches for the value corresponding to given Key.
112
func (dht *IpfsDHT) GetValue(ctx context.Context, key string, opts ...routing.Option) (_ []byte, err error) {
Matt Joiner's avatar
Matt Joiner committed
113
	eip := logger.EventBegin(ctx, "GetValue")
114 115 116 117 118 119 120
	defer func() {
		eip.Append(loggableKey(key))
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Jeromy's avatar
Jeromy committed
121

122
	// apply defaultQuorum if relevant
123
	var cfg routing.Options
124 125 126 127 128
	if err := cfg.Apply(opts...); err != nil {
		return nil, err
	}
	opts = append(opts, Quorum(getQuorum(&cfg, defaultQuorum)))

129 130 131 132
	responses, err := dht.SearchValue(ctx, key, opts...)
	if err != nil {
		return nil, err
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
133 134
	var best []byte

135 136
	for r := range responses {
		best = r
Łukasz Magiera's avatar
Łukasz Magiera committed
137 138
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
139 140 141 142
	if ctx.Err() != nil {
		return best, ctx.Err()
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
143 144 145
	if best == nil {
		return nil, routing.ErrNotFound
	}
Matt Joiner's avatar
Matt Joiner committed
146
	logger.Debugf("GetValue %v %v", key, best)
Łukasz Magiera's avatar
Łukasz Magiera committed
147 148 149
	return best, nil
}

150 151
func (dht *IpfsDHT) SearchValue(ctx context.Context, key string, opts ...routing.Option) (<-chan []byte, error) {
	var cfg routing.Options
Steven Allen's avatar
Steven Allen committed
152
	if err := cfg.Apply(opts...); err != nil {
153
		return nil, err
Steven Allen's avatar
Steven Allen committed
154 155 156 157
	}

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

161 162 163 164 165 166
	valCh, err := dht.getValues(ctx, key, responsesNeeded)
	if err != nil {
		return nil, err
	}

	out := make(chan []byte)
Łukasz Magiera's avatar
Łukasz Magiera committed
167 168
	go func() {
		defer close(out)
169

Łukasz Magiera's avatar
Łukasz Magiera committed
170 171 172 173
		maxVals := responsesNeeded
		if maxVals < 0 {
			maxVals = defaultQuorum * 4 // we want some upper bound on how
			// much correctional entries we will send
174
		}
175 176 177

		// 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
178
		vals := make([]RecvdVal, 0, maxVals)
179
		var best *RecvdVal
180

Łukasz Magiera's avatar
Łukasz Magiera committed
181
		defer func() {
182
			if len(vals) <= 1 || best == nil {
Łukasz Magiera's avatar
Łukasz Magiera committed
183 184
				return
			}
185
			fixupRec := record.MakePutRecord(key, best.Val)
Łukasz Magiera's avatar
Łukasz Magiera committed
186 187
			for _, v := range vals {
				// if someone sent us a different 'less-valid' record, lets correct them
188
				if !bytes.Equal(v.Val, best.Val) {
Łukasz Magiera's avatar
Łukasz Magiera committed
189 190 191 192
					go func(v RecvdVal) {
						if v.From == dht.self {
							err := dht.putLocal(key, fixupRec)
							if err != nil {
Matt Joiner's avatar
Matt Joiner committed
193
								logger.Error("Error correcting local dht entry:", err)
Łukasz Magiera's avatar
Łukasz Magiera committed
194 195 196 197 198 199 200
							}
							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
201
							logger.Debug("Error correcting DHT entry: ", err)
Łukasz Magiera's avatar
Łukasz Magiera committed
202 203 204 205 206
						}
					}(v)
				}
			}
		}()
207

Łukasz Magiera's avatar
Łukasz Magiera committed
208 209 210 211
		for {
			select {
			case v, ok := <-valCh:
				if !ok {
212
					return
Łukasz Magiera's avatar
Łukasz Magiera committed
213 214
				}

Łukasz Magiera's avatar
Łukasz Magiera committed
215 216 217
				if len(vals) < maxVals {
					vals = append(vals, v)
				}
218

Łukasz Magiera's avatar
Łukasz Magiera committed
219 220 221 222
				if v.Val == nil {
					continue
				}
				// Select best value
223
				if best != nil {
Steven Allen's avatar
Steven Allen committed
224 225 226
					if bytes.Equal(best.Val, v.Val) {
						continue
					}
227
					sel, err := dht.Validator.Select(key, [][]byte{best.Val, v.Val})
228
					if err != nil {
Matt Joiner's avatar
Matt Joiner committed
229
						logger.Warning("Failed to select dht key: ", err)
Łukasz Magiera's avatar
Łukasz Magiera committed
230
						continue
Łukasz Magiera's avatar
Łukasz Magiera committed
231
					}
Steven Allen's avatar
Steven Allen committed
232 233
					if sel != 1 {
						continue
234 235
					}
				}
Steven Allen's avatar
Steven Allen committed
236 237 238 239 240 241
				best = &v
				select {
				case out <- v.Val:
				case <-ctx.Done():
					return
				}
Łukasz Magiera's avatar
Łukasz Magiera committed
242 243 244
			case <-ctx.Done():
				return
			}
245
		}
Łukasz Magiera's avatar
Łukasz Magiera committed
246
	}()
247

248
	return out, nil
249 250
}

Steven Allen's avatar
Steven Allen committed
251
// GetValues gets nvals values corresponding to the given key.
252
func (dht *IpfsDHT) GetValues(ctx context.Context, key string, nvals int) (_ []RecvdVal, err error) {
Matt Joiner's avatar
Matt Joiner committed
253
	eip := logger.EventBegin(ctx, "GetValues")
254 255 256 257

	eip.Append(loggableKey(key))
	defer eip.Done()

258 259
	valCh, err := dht.getValues(ctx, key, nvals)
	if err != nil {
260
		eip.SetError(err)
261 262 263 264 265 266 267 268
		return nil, err
	}

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

Łukasz Magiera's avatar
Łukasz Magiera committed
269
	return out, ctx.Err()
270 271
}

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

275
	done := func(err error) (<-chan RecvdVal, error) {
Łukasz Magiera's avatar
Łukasz Magiera committed
276
		defer close(vals)
277
		return vals, err
Łukasz Magiera's avatar
Łukasz Magiera committed
278
	}
279

280
	// If we have it local, don't bother doing an RPC!
281
	lrec, err := dht.getLocal(key)
282 283
	if err != nil {
		// something is wrong with the datastore.
Łukasz Magiera's avatar
Łukasz Magiera committed
284
		return done(err)
285 286
	}
	if lrec != nil {
287
		// TODO: this is tricky, we don't always want to trust our own value
288
		// what if the authoritative source updated it?
Matt Joiner's avatar
Matt Joiner committed
289
		logger.Debug("have it locally")
Łukasz Magiera's avatar
Łukasz Magiera committed
290
		vals <- RecvdVal{
291 292
			Val:  lrec.GetValue(),
			From: dht.self,
Łukasz Magiera's avatar
Łukasz Magiera committed
293
		}
294

295
		if nvals == 0 || nvals == 1 {
Łukasz Magiera's avatar
Łukasz Magiera committed
296
			return done(nil)
297
		}
Łukasz Magiera's avatar
Łukasz Magiera committed
298 299

		nvals--
300
	} else if nvals == 0 {
Łukasz Magiera's avatar
Łukasz Magiera committed
301
		return done(routing.ErrNotFound)
Jeromy's avatar
Jeromy committed
302 303
	}

304
	// get closest peers in the routing table
Jeromy's avatar
Jeromy committed
305
	rtp := dht.routingTable.NearestPeers(kb.ConvertKey(key), AlphaValue)
Matt Joiner's avatar
Matt Joiner committed
306
	logger.Debugf("peers in rt: %d %s", len(rtp), rtp)
307
	if len(rtp) == 0 {
Matt Joiner's avatar
Matt Joiner committed
308
		logger.Warning("No peers from routing table!")
Łukasz Magiera's avatar
Łukasz Magiera committed
309
		return done(kb.ErrLookupFailure)
310 311
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
312 313 314
	var valslock sync.Mutex
	var got int

315
	// setup the Query
Jeromy's avatar
Jeromy committed
316
	parent := ctx
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
317
	query := dht.newQuery(key, func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
318 319
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type: routing.SendingQuery,
Jeromy's avatar
Jeromy committed
320 321 322
			ID:   p,
		})

323
		rec, peers, err := dht.getValueOrPeers(ctx, p, key)
324 325 326 327 328
		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'
329 330
			routing.PublishQueryEvent(parent, &routing.QueryEvent{
				Type: routing.PeerResponse,
331 332
				ID:   p,
			})
333
			return nil, err
334 335 336 337 338
		default:
			return nil, err

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

341 342
		res := &dhtQueryResult{closerPeers: peers}

343
		if rec.GetValue() != nil || err == errInvalidRecord {
Steven Allen's avatar
Steven Allen committed
344
			rv := RecvdVal{
345 346 347 348
				Val:  rec.GetValue(),
				From: p,
			}
			valslock.Lock()
349 350 351 352 353 354
			select {
			case vals <- rv:
			case <-ctx.Done():
				valslock.Unlock()
				return nil, ctx.Err()
			}
Łukasz Magiera's avatar
Łukasz Magiera committed
355
			got++
356

357
			// If we have collected enough records, we're done
Łukasz Magiera's avatar
Łukasz Magiera committed
358
			if nvals == got {
359 360 361
				res.success = true
			}
			valslock.Unlock()
362 363
		}

364 365
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type:      routing.PeerResponse,
Jeromy's avatar
Jeromy committed
366
			ID:        p,
Jeromy's avatar
Jeromy committed
367
			Responses: peers,
Jeromy's avatar
Jeromy committed
368 369
		})

370 371
		return res, nil
	})
372

Łukasz Magiera's avatar
Łukasz Magiera committed
373 374 375 376 377 378 379 380 381 382 383
	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) {
384 385 386
			// 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
387 388 389 390
			err = nil
		}
		done(err)
	}()
391

392
	return vals, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
393 394
}

395 396 397
// 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
398

399
// Provide makes this node announce that it can provide a value for the given key
400
func (dht *IpfsDHT) Provide(ctx context.Context, key cid.Cid, brdcst bool) (err error) {
Matt Joiner's avatar
Matt Joiner committed
401
	eip := logger.EventBegin(ctx, "Provide", key, logging.LoggableMap{"broadcast": brdcst})
402 403 404 405 406 407
	defer func() {
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
408 409

	// add self locally
410
	dht.providers.AddProvider(ctx, key, dht.self)
Jeromy's avatar
Jeromy committed
411 412 413
	if !brdcst {
		return nil
	}
414

415 416 417 418 419 420 421 422 423 424
	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.
425
			deadline = deadline.Add(-timeout / 10)
426 427 428 429 430 431 432 433 434 435 436
		} 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())
437 438
	if err != nil {
		return err
439 440
	}

441 442 443 444 445
	mes, err := dht.makeProvRecord(key)
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
446
	wg := sync.WaitGroup{}
447
	for p := range peers {
Jeromy's avatar
Jeromy committed
448 449 450
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Matt Joiner's avatar
Matt Joiner committed
451
			logger.Debugf("putProvider(%s, %s)", key, p)
452
			err := dht.sendMessage(ctx, p, mes)
Jeromy's avatar
Jeromy committed
453
			if err != nil {
Matt Joiner's avatar
Matt Joiner committed
454
				logger.Debug(err)
Jeromy's avatar
Jeromy committed
455 456
			}
		}(p)
457
	}
Jeromy's avatar
Jeromy committed
458
	wg.Wait()
459
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
460
}
461
func (dht *IpfsDHT) makeProvRecord(skey cid.Cid) (*pb.Message, error) {
462
	pi := peer.AddrInfo{
463 464 465 466 467 468 469 470 471 472
		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.")
	}

473
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, skey.Bytes(), 0)
474
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]peer.AddrInfo{pi})
475 476
	return pmes, nil
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
477

Brian Tiger Chow's avatar
Brian Tiger Chow committed
478
// FindProviders searches until the context expires.
479 480
func (dht *IpfsDHT) FindProviders(ctx context.Context, c cid.Cid) ([]peer.AddrInfo, error) {
	var providers []peer.AddrInfo
481
	for p := range dht.FindProvidersAsync(ctx, c, dht.bucketSize) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
482 483 484 485 486
		providers = append(providers, p)
	}
	return providers, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
487 488 489
// 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.
490
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key cid.Cid, count int) <-chan peer.AddrInfo {
Matt Joiner's avatar
Matt Joiner committed
491
	logger.Event(ctx, "findProviders", key)
492
	peerOut := make(chan peer.AddrInfo, count)
493

Jeromy's avatar
Jeromy committed
494 495 496 497
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

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

502
	ps := peer.NewLimitedSet(count)
Jeromy's avatar
Jeromy committed
503 504
	provs := dht.providers.GetProviders(ctx, key)
	for _, p := range provs {
505
		// NOTE: Assuming that this list of peers is unique
Jeromy's avatar
Jeromy committed
506
		if ps.TryAdd(p) {
Jeromy's avatar
Jeromy committed
507
			pi := dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
508
			select {
Jeromy's avatar
Jeromy committed
509
			case peerOut <- pi:
Jeromy's avatar
Jeromy committed
510 511 512
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
513
		}
Jeromy's avatar
Jeromy committed
514

515
		// If we have enough peers locally, don't bother with remote RPC
Jeromy's avatar
Jeromy committed
516
		// TODO: is this a DOS vector?
Jeromy's avatar
Jeromy committed
517
		if ps.Size() >= count {
Jeromy's avatar
Jeromy committed
518 519 520 521
			return
		}
	}

522 523
	peers := dht.routingTable.NearestPeers(kb.ConvertKey(key.KeyString()), AlphaValue)
	if len(peers) == 0 {
524 525
		routing.PublishQueryEvent(ctx, &routing.QueryEvent{
			Type:  routing.QueryError,
526 527 528 529 530
			Extra: kb.ErrLookupFailure.Error(),
		})
		return
	}

Jeromy's avatar
Jeromy committed
531
	// setup the Query
Jeromy's avatar
Jeromy committed
532
	parent := ctx
533
	query := dht.newQuery(key.KeyString(), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
534 535
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type: routing.SendingQuery,
536 537
			ID:   p,
		})
538
		pmes, err := dht.findProvidersSingle(ctx, p, key)
Jeromy's avatar
Jeromy committed
539 540 541 542
		if err != nil {
			return nil, err
		}

Matt Joiner's avatar
Matt Joiner committed
543
		logger.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
544
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Matt Joiner's avatar
Matt Joiner committed
545
		logger.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
546 547 548

		// Add unique providers from request, up to 'count'
		for _, prov := range provs {
549
			if prov.ID != dht.self {
550
				dht.peerstore.AddAddrs(prov.ID, prov.Addrs, peerstore.TempAddrTTL)
551
			}
Matt Joiner's avatar
Matt Joiner committed
552
			logger.Debugf("got provider: %s", prov)
553
			if ps.TryAdd(prov.ID) {
Matt Joiner's avatar
Matt Joiner committed
554
				logger.Debugf("using provider: %s", prov)
Jeromy's avatar
Jeromy committed
555
				select {
Jeromy's avatar
Jeromy committed
556
				case peerOut <- *prov:
Jeromy's avatar
Jeromy committed
557
				case <-ctx.Done():
Matt Joiner's avatar
Matt Joiner committed
558
					logger.Debug("context timed out sending more providers")
Jeromy's avatar
Jeromy committed
559 560
					return nil, ctx.Err()
				}
561
			}
Jeromy's avatar
Jeromy committed
562
			if ps.Size() >= count {
Matt Joiner's avatar
Matt Joiner committed
563
				logger.Debugf("got enough providers (%d/%d)", ps.Size(), count)
Jeromy's avatar
Jeromy committed
564
				return &dhtQueryResult{success: true}, nil
565 566 567
			}
		}

Jeromy's avatar
Jeromy committed
568 569
		// Give closer peers back to the query to be queried
		closer := pmes.GetCloserPeers()
570
		clpeers := pb.PBPeersToPeerInfos(closer)
Matt Joiner's avatar
Matt Joiner committed
571
		logger.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
572

573 574
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type:      routing.PeerResponse,
575
			ID:        p,
Jeromy's avatar
Jeromy committed
576
			Responses: clpeers,
577
		})
Jeromy's avatar
Jeromy committed
578 579 580 581 582
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

	_, err := query.Run(ctx, peers)
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
583
		logger.Debugf("Query error: %s", err)
584 585
		// Special handling for issue: https://github.com/ipfs/go-ipfs/issues/3032
		if fmt.Sprint(err) == "<nil>" {
Matt Joiner's avatar
Matt Joiner committed
586 587 588 589
			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")
590 591 592 593

			// replace problematic error with something that won't crash the daemon
			err = fmt.Errorf("<nil>")
		}
594 595
		routing.PublishQueryEvent(ctx, &routing.QueryEvent{
			Type:  routing.QueryError,
596 597
			Extra: err.Error(),
		})
Jeromy's avatar
Jeromy committed
598
	}
599 600 601

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
604
// FindPeer searches for a peer with given ID.
605
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (_ peer.AddrInfo, err error) {
Matt Joiner's avatar
Matt Joiner committed
606
	eip := logger.EventBegin(ctx, "FindPeer", id)
607 608 609 610 611 612
	defer func() {
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
613

614
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
615
	if pi := dht.FindLocal(id); pi.ID != "" {
616
		return pi, nil
617 618
	}

Jeromy's avatar
Jeromy committed
619
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
620
	if len(peers) == 0 {
621
		return peer.AddrInfo{}, kb.ErrLookupFailure
622
	}
623

Jeromy's avatar
Jeromy committed
624
	// Sanity...
625
	for _, p := range peers {
626
		if p == id {
Matt Joiner's avatar
Matt Joiner committed
627
			logger.Debug("found target peer in list of closest peers...")
628
			return dht.peerstore.PeerInfo(p), nil
629
		}
630
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
631

Jeromy's avatar
Jeromy committed
632
	// setup the Query
Jeromy's avatar
Jeromy committed
633
	parent := ctx
634
	query := dht.newQuery(string(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
635 636
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type: routing.SendingQuery,
637 638
			ID:   p,
		})
Jeromy's avatar
Jeromy committed
639

640
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
641
		if err != nil {
642
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
643
		}
644

Jeromy's avatar
Jeromy committed
645
		closer := pmes.GetCloserPeers()
646
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
647

648
		// see if we got the peer here
649 650
		for _, npi := range clpeerInfos {
			if npi.ID == id {
Jeromy's avatar
Jeromy committed
651
				return &dhtQueryResult{
652
					peer:    npi,
Jeromy's avatar
Jeromy committed
653 654 655
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
656 657
		}

658 659
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type:      routing.PeerResponse,
660
			ID:        p,
Jeromy's avatar
Jeromy committed
661
			Responses: clpeerInfos,
662 663
		})

664
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
665
	})
666

Jeromy's avatar
Jeromy committed
667
	// run it!
668
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
669
	if err != nil {
670
		return peer.AddrInfo{}, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
671 672
	}

673 674 675
	// 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
676
	logger.Debugf("FindPeer %v %v", id, result.success)
677
	if result.peer.ID == "" {
678
		return peer.AddrInfo{}, routing.ErrNotFound
679
	}
Jeromy's avatar
Jeromy committed
680

Jeromy's avatar
Jeromy committed
681
	return *result.peer, nil
682 683
}

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

687
	peerchan := make(chan *peer.AddrInfo, asyncQueryBuffer)
Jeromy's avatar
Jeromy committed
688
	peersSeen := make(map[peer.ID]struct{})
689
	var peersSeenMx sync.Mutex
690

Jeromy's avatar
Jeromy committed
691
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
692
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
693
		return nil, kb.ErrLookupFailure
694 695 696
	}

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

699
		pmes, err := dht.findPeerSingle(ctx, p, id)
700 701 702 703
		if err != nil {
			return nil, err
		}

704
		var clpeers []*peer.AddrInfo
705 706
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
707
			pi := pb.PBPeerToPeerInfo(pbp)
708

709
			// skip peers already seen
710
			peersSeenMx.Lock()
711
			if _, found := peersSeen[pi.ID]; found {
712
				peersSeenMx.Unlock()
713 714
				continue
			}
715
			peersSeen[pi.ID] = struct{}{}
716
			peersSeenMx.Unlock()
717 718

			// if peer is connected, send it to our client.
719
			if pb.Connectedness(pbp.Connection) == network.Connected {
720 721 722
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
723
				case peerchan <- pi:
724 725 726 727
				}
			}

			// if peer is the peer we're looking for, don't bother querying it.
728
			// TODO maybe query it?
729
			if pb.Connectedness(pbp.Connection) != network.Connected {
730
				clpeers = append(clpeers, pi)
731 732 733 734 735 736 737 738 739
			}
		}

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

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

744 745 746
		// refresh the k-bucket containing this key
		dht.routingTable.BucketForID(kb.ConvertPeerID(id)).ResetRefreshedAt(time.Now())

747 748 749 750 751 752
		// close the peerchan channel when done.
		close(peerchan)
	}()

	return peerchan, nil
}