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 17
	mh "github.com/multiformats/go-multihash"

18
	"github.com/ipfs/go-cid"
19
	u "github.com/ipfs/go-ipfs-util"
Jeromy's avatar
Jeromy committed
20
	logging "github.com/ipfs/go-log"
21
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
George Antoniadis's avatar
George Antoniadis committed
22 23
	kb "github.com/libp2p/go-libp2p-kbucket"
	record "github.com/libp2p/go-libp2p-record"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
24 25
)

26 27 28 29 30 31
// 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
32 33 34 35 36
// This file implements the Routing interface for the IpfsDHT struct.

// Basic Put/Get

// PutValue adds value corresponding to given Key.
37
// This is the top level "Store" operation of the DHT
38
func (dht *IpfsDHT) PutValue(ctx context.Context, key string, value []byte, opts ...routing.Option) (err error) {
39 40 41 42
	if !dht.enableValues {
		return routing.ErrNotSupported
	}

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

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
	// 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")
		}
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

262
	return out, nil
263 264
}

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

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

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

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

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

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

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

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

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

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

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

Łukasz Magiera's avatar
Łukasz Magiera committed
329 330 331
	var valslock sync.Mutex
	var got int

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

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

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

358 359
		res := &dhtQueryResult{closerPeers: peers}

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

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

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

387 388
		return res, nil
	})
389

Łukasz Magiera's avatar
Łukasz Magiera committed
390 391 392 393 394 395 396 397 398 399 400
	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) {
Aarsh Shah's avatar
Aarsh Shah committed
401 402
			// refresh the cpl for this key as the query was successful
			dht.routingTable.ResetCplRefreshedAtForID(kb.ConvertKey(key), time.Now())
Łukasz Magiera's avatar
Łukasz Magiera committed
403 404 405 406
			err = nil
		}
		done(err)
	}()
407

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

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

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

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

435 436 437 438 439 440 441 442 443 444
	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.
445
			deadline = deadline.Add(-timeout / 10)
446 447 448 449 450 451 452 453 454 455
		} 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()
	}

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

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

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

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

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

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

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

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

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

530 531
	key := keyCid.Hash()

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

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

552
	peers := dht.routingTable.NearestPeers(kb.ConvertKey(string(key)), AlphaValue)
553
	if len(peers) == 0 {
554 555
		routing.PublishQueryEvent(ctx, &routing.QueryEvent{
			Type:  routing.QueryError,
556 557 558 559 560
			Extra: kb.ErrLookupFailure.Error(),
		})
		return
	}

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

Matt Joiner's avatar
Matt Joiner committed
573
		logger.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
574
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Matt Joiner's avatar
Matt Joiner committed
575
		logger.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
576 577 578

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

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

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

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

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

Aarsh Shah's avatar
Aarsh Shah committed
630
	// refresh the cpl for this key after the query is run
631
	dht.routingTable.ResetCplRefreshedAtForID(kb.ConvertKey(string(key)), time.Now())
632 633
}

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

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

Jeromy's avatar
Jeromy committed
649
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
650
	if len(peers) == 0 {
651
		return peer.AddrInfo{}, kb.ErrLookupFailure
652
	}
653

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

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

670
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
671
		if err != nil {
672
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
673
		}
674

Jeromy's avatar
Jeromy committed
675
		closer := pmes.GetCloserPeers()
676
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
677

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

688 689
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type:      routing.PeerResponse,
690
			ID:        p,
Jeromy's avatar
Jeromy committed
691
			Responses: clpeerInfos,
692 693
		})

694
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
695
	})
696

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

Aarsh Shah's avatar
Aarsh Shah committed
703 704
	// refresh the cpl for this key since the lookup was successful
	dht.routingTable.ResetCplRefreshedAtForID(kb.ConvertPeerID(id), time.Now())
705

Matt Joiner's avatar
Matt Joiner committed
706
	logger.Debugf("FindPeer %v %v", id, result.success)
707
	if result.peer.ID == "" {
708
		return peer.AddrInfo{}, routing.ErrNotFound
709
	}
Jeromy's avatar
Jeromy committed
710

Jeromy's avatar
Jeromy committed
711
	return *result.peer, nil
712 713
}

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

717
	peerchan := make(chan *peer.AddrInfo, asyncQueryBuffer)
Jeromy's avatar
Jeromy committed
718
	peersSeen := make(map[peer.ID]struct{})
719
	var peersSeenMx sync.Mutex
720

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

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

729
		pmes, err := dht.findPeerSingle(ctx, p, id)
730 731 732 733
		if err != nil {
			return nil, err
		}

734
		var clpeers []*peer.AddrInfo
735 736
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
737
			pi := pb.PBPeerToPeerInfo(pbp)
738

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

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

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

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

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

Aarsh Shah's avatar
Aarsh Shah committed
774 775
		// refresh the cpl for this key
		dht.routingTable.ResetCplRefreshedAtForID(kb.ConvertPeerID(id), time.Now())
776

777 778 779 780 781 782
		// close the peerchan channel when done.
		close(peerchan)
	}()

	return peerchan, nil
}