routing.go 18 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
	cid "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 101
			}
		}(p)
	}
	wg.Wait()
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
102 103
}

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

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

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

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

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

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

149 150
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
151
	if err := cfg.Apply(opts...); err != nil {
152
		return nil, err
Steven Allen's avatar
Steven Allen committed
153 154 155 156
	}

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

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

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

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

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

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

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

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

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

247
	return out, nil
248 249
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

369 370
		return res, nil
	})
371

Łukasz Magiera's avatar
Łukasz Magiera committed
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
	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)
	}()
387

388
	return vals, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
389 390
}

391 392 393
// 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
394

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

	// add self locally
406
	dht.providers.AddProvider(ctx, key, dht.self)
Jeromy's avatar
Jeromy committed
407 408 409
	if !brdcst {
		return nil
	}
410

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

437 438 439 440 441
	mes, err := dht.makeProvRecord(key)
	if err != nil {
		return err
	}

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

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

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

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

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

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

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

517 518
	peers := dht.routingTable.NearestPeers(kb.ConvertKey(key.KeyString()), AlphaValue)
	if len(peers) == 0 {
519 520
		routing.PublishQueryEvent(ctx, &routing.QueryEvent{
			Type:  routing.QueryError,
521 522 523 524 525
			Extra: kb.ErrLookupFailure.Error(),
		})
		return
	}

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

Matt Joiner's avatar
Matt Joiner committed
538
		logger.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
539
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Matt Joiner's avatar
Matt Joiner committed
540
		logger.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
541 542 543

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

Jeromy's avatar
Jeromy committed
563 564
		// Give closer peers back to the query to be queried
		closer := pmes.GetCloserPeers()
565
		clpeers := pb.PBPeersToPeerInfos(closer)
Matt Joiner's avatar
Matt Joiner committed
566
		logger.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
567

568 569
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type:      routing.PeerResponse,
570
			ID:        p,
Jeromy's avatar
Jeromy committed
571
			Responses: clpeers,
572
		})
Jeromy's avatar
Jeromy committed
573 574 575 576 577
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

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

			// replace problematic error with something that won't crash the daemon
			err = fmt.Errorf("<nil>")
		}
589 590
		routing.PublishQueryEvent(ctx, &routing.QueryEvent{
			Type:  routing.QueryError,
591 592
			Extra: err.Error(),
		})
Jeromy's avatar
Jeromy committed
593
	}
594 595
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
596
// FindPeer searches for a peer with given ID.
597
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (_ peer.AddrInfo, err error) {
Matt Joiner's avatar
Matt Joiner committed
598
	eip := logger.EventBegin(ctx, "FindPeer", id)
599 600 601 602 603 604
	defer func() {
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
605

606
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
607
	if pi := dht.FindLocal(id); pi.ID != "" {
608
		return pi, nil
609 610
	}

Jeromy's avatar
Jeromy committed
611
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
612
	if len(peers) == 0 {
613
		return peer.AddrInfo{}, kb.ErrLookupFailure
614
	}
615

Jeromy's avatar
Jeromy committed
616
	// Sanity...
617
	for _, p := range peers {
618
		if p == id {
Matt Joiner's avatar
Matt Joiner committed
619
			logger.Debug("found target peer in list of closest peers...")
620
			return dht.peerstore.PeerInfo(p), nil
621
		}
622
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
623

Jeromy's avatar
Jeromy committed
624
	// setup the Query
Jeromy's avatar
Jeromy committed
625
	parent := ctx
626
	query := dht.newQuery(string(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
627 628
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type: routing.SendingQuery,
629 630
			ID:   p,
		})
Jeromy's avatar
Jeromy committed
631

632
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
633
		if err != nil {
634
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
635
		}
636

Jeromy's avatar
Jeromy committed
637
		closer := pmes.GetCloserPeers()
638
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
639

640
		// see if we got the peer here
641 642
		for _, npi := range clpeerInfos {
			if npi.ID == id {
Jeromy's avatar
Jeromy committed
643
				return &dhtQueryResult{
644
					peer:    npi,
Jeromy's avatar
Jeromy committed
645 646 647
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
648 649
		}

650 651
		routing.PublishQueryEvent(parent, &routing.QueryEvent{
			Type:      routing.PeerResponse,
652
			ID:        p,
Jeromy's avatar
Jeromy committed
653
			Responses: clpeerInfos,
654 655
		})

656
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
657
	})
658

Jeromy's avatar
Jeromy committed
659
	// run it!
660
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
661
	if err != nil {
662
		return peer.AddrInfo{}, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
663 664
	}

Matt Joiner's avatar
Matt Joiner committed
665
	logger.Debugf("FindPeer %v %v", id, result.success)
666
	if result.peer.ID == "" {
667
		return peer.AddrInfo{}, routing.ErrNotFound
668
	}
Jeromy's avatar
Jeromy committed
669

Jeromy's avatar
Jeromy committed
670
	return *result.peer, nil
671 672
}

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

676
	peerchan := make(chan *peer.AddrInfo, asyncQueryBuffer)
Jeromy's avatar
Jeromy committed
677
	peersSeen := make(map[peer.ID]struct{})
678
	var peersSeenMx sync.Mutex
679

Jeromy's avatar
Jeromy committed
680
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
681
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
682
		return nil, kb.ErrLookupFailure
683 684 685
	}

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

688
		pmes, err := dht.findPeerSingle(ctx, p, id)
689 690 691 692
		if err != nil {
			return nil, err
		}

693
		var clpeers []*peer.AddrInfo
694 695
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
696
			pi := pb.PBPeerToPeerInfo(pbp)
697

698
			// skip peers already seen
699
			peersSeenMx.Lock()
700
			if _, found := peersSeen[pi.ID]; found {
701
				peersSeenMx.Unlock()
702 703
				continue
			}
704
			peersSeen[pi.ID] = struct{}{}
705
			peersSeenMx.Unlock()
706 707

			// if peer is connected, send it to our client.
708
			if pb.Connectedness(pbp.Connection) == network.Connected {
709 710 711
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
712
				case peerchan <- pi:
713 714 715 716
				}
			}

			// if peer is the peer we're looking for, don't bother querying it.
717
			// TODO maybe query it?
718
			if pb.Connectedness(pbp.Connection) != network.Connected {
719
				clpeers = append(clpeers, pi)
720 721 722 723 724 725 726 727 728
			}
		}

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

	// run it! run it asynchronously to gen peers as results are found.
	// this does no error checking
	go func() {
729
		if _, err := query.Run(ctx, peers); err != nil {
Matt Joiner's avatar
Matt Joiner committed
730
			logger.Debug(err)
731 732 733 734 735 736 737 738
		}

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

	return peerchan, nil
}