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) {
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 78 79 80 81
	// refresh the k-bucket containing this key
	defer func() {
		dht.routingTable.BucketForID(kb.ConvertKey(key)).ResetRefreshedAt(time.Now())
	}()

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

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

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

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

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

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

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

140 141
	for r := range responses {
		best = r
Łukasz Magiera's avatar
Łukasz Magiera committed
142 143
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
144 145 146 147
	if ctx.Err() != nil {
		return best, ctx.Err()
	}

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

155 156
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
157
	if err := cfg.Apply(opts...); err != nil {
158
		return nil, err
Steven Allen's avatar
Steven Allen committed
159 160 161 162
	}

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

166 167 168 169 170
	// refresh the k-bucket containing this key
	defer func() {
		dht.routingTable.BucketForID(kb.ConvertKey(key)).ResetRefreshedAt(time.Now())
	}()

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

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

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

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

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

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

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

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

258
	return out, nil
259 260
}

Steven Allen's avatar
Steven Allen committed
261
// GetValues gets nvals values corresponding to the given key.
262
func (dht *IpfsDHT) GetValues(ctx context.Context, key string, nvals int) (_ []RecvdVal, err error) {
Matt Joiner's avatar
Matt Joiner committed
263
	eip := logger.EventBegin(ctx, "GetValues")
264 265 266 267

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

268 269 270 271 272
	// refresh the k-bucket containing this key
	defer func() {
		dht.routingTable.BucketForID(kb.ConvertKey(key)).ResetRefreshedAt(time.Now())
	}()

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 399 400 401 402
	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) {
			err = nil
		}
		done(err)
	}()
403

404
	return vals, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
405 406
}

407 408 409
// 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
410

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

	// add self locally
422
	dht.providers.AddProvider(ctx, key, dht.self)
Jeromy's avatar
Jeromy committed
423 424 425
	if !brdcst {
		return nil
	}
426

427 428 429 430 431 432 433 434 435 436
	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.
437
			deadline = deadline.Add(-timeout / 10)
438 439 440 441 442 443 444 445 446 447
		} 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()
	}

448 449 450 451 452
	// refresh the k-bucket containing this key
	defer func() {
		dht.routingTable.BucketForID(kb.ConvertKey(key.KeyString())).ResetRefreshedAt(time.Now())
	}()

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

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
504 505 506
// 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.
507
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key cid.Cid, count int) <-chan peer.AddrInfo {
Matt Joiner's avatar
Matt Joiner committed
508
	logger.Event(ctx, "findProviders", key)
509
	peerOut := make(chan peer.AddrInfo, count)
510 511 512 513 514 515

	// refresh the k-bucket containing this key
	defer func() {
		dht.routingTable.BucketForID(kb.ConvertKey(key.KeyString())).ResetRefreshedAt(time.Now())
	}()

Jeromy's avatar
Jeromy committed
516 517 518 519
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

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

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

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

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

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

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

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

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

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

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

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

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

633
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
634
	if pi := dht.FindLocal(id); pi.ID != "" {
635
		return pi, nil
636 637
	}

Jeromy's avatar
Jeromy committed
638
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
639
	if len(peers) == 0 {
640
		return peer.AddrInfo{}, kb.ErrLookupFailure
641
	}
642

Jeromy's avatar
Jeromy committed
643
	// Sanity...
644
	for _, p := range peers {
645
		if p == id {
Matt Joiner's avatar
Matt Joiner committed
646
			logger.Debug("found target peer in list of closest peers...")
647
			return dht.peerstore.PeerInfo(p), nil
648
		}
649
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
650

651 652 653 654 655
	// refresh the k-bucket containing this key
	defer func() {
		dht.routingTable.BucketForID(kb.ConvertPeerID(id)).ResetRefreshedAt(time.Now())
	}()

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

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

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

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

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

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

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

Matt Joiner's avatar
Matt Joiner committed
697
	logger.Debugf("FindPeer %v %v", id, result.success)
698
	if result.peer.ID == "" {
699
		return peer.AddrInfo{}, routing.ErrNotFound
700
	}
Jeromy's avatar
Jeromy committed
701

Jeromy's avatar
Jeromy committed
702
	return *result.peer, nil
703 704
}

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

708
	peerchan := make(chan *peer.AddrInfo, asyncQueryBuffer)
Jeromy's avatar
Jeromy committed
709
	peersSeen := make(map[peer.ID]struct{})
710
	var peersSeenMx sync.Mutex
711

Jeromy's avatar
Jeromy committed
712
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
713
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
714
		return nil, kb.ErrLookupFailure
715 716
	}

717 718 719 720 721
	// refresh the k-bucket containing this key
	defer func() {
		dht.routingTable.BucketForID(kb.ConvertPeerID(id)).ResetRefreshedAt(time.Now())
	}()

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 773 774 775
		}

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

	return peerchan, nil
}