routing.go 17.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
	cid "github.com/ipfs/go-cid"
12
	u "github.com/ipfs/go-ipfs-util"
Jeromy's avatar
Jeromy committed
13
	logging "github.com/ipfs/go-log"
14
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
George Antoniadis's avatar
George Antoniadis committed
15
	kb "github.com/libp2p/go-libp2p-kbucket"
16 17 18 19
	inet "github.com/libp2p/go-libp2p-net"
	peer "github.com/libp2p/go-libp2p-peer"
	pset "github.com/libp2p/go-libp2p-peer/peerset"
	pstore "github.com/libp2p/go-libp2p-peerstore"
George Antoniadis's avatar
George Antoniadis committed
20 21 22
	record "github.com/libp2p/go-libp2p-record"
	routing "github.com/libp2p/go-libp2p-routing"
	notif "github.com/libp2p/go-libp2p-routing/notifications"
Steven Allen's avatar
Steven Allen committed
23
	ropts "github.com/libp2p/go-libp2p-routing/options"
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
Steven Allen's avatar
Steven Allen committed
38
func (dht *IpfsDHT) PutValue(ctx context.Context, key string, value []byte, opts ...ropts.Option) (err error) {
Matt Joiner's avatar
Matt Joiner committed
39
	eip := logger.EventBegin(ctx, "PutValue")
40 41 42 43 44 45 46
	defer func() {
		eip.Append(loggableKey(key))
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Matt Joiner's avatar
Matt Joiner committed
47
	logger.Debugf("PutValue %s", key)
Jeromy's avatar
Jeromy committed
48

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

249
	return out, nil
250 251
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

371 372
		return res, nil
	})
373

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

390
	return vals, nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
391 392
}

393 394 395
// 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
396

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

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

413
	peers, err := dht.GetClosestPeers(ctx, key.KeyString())
414 415
	if err != nil {
		return err
416 417
	}

418 419 420 421 422
	mes, err := dht.makeProvRecord(key)
	if err != nil {
		return err
	}

Jeromy's avatar
Jeromy committed
423
	wg := sync.WaitGroup{}
424
	for p := range peers {
Jeromy's avatar
Jeromy committed
425 426 427
		wg.Add(1)
		go func(p peer.ID) {
			defer wg.Done()
Matt Joiner's avatar
Matt Joiner committed
428
			logger.Debugf("putProvider(%s, %s)", key, p)
429
			err := dht.sendMessage(ctx, p, mes)
Jeromy's avatar
Jeromy committed
430
			if err != nil {
Matt Joiner's avatar
Matt Joiner committed
431
				logger.Debug(err)
Jeromy's avatar
Jeromy committed
432 433
			}
		}(p)
434
	}
Jeromy's avatar
Jeromy committed
435
	wg.Wait()
436
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
437
}
438
func (dht *IpfsDHT) makeProvRecord(skey cid.Cid) (*pb.Message, error) {
439 440 441 442 443 444 445 446 447 448 449
	pi := pstore.PeerInfo{
		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.")
	}

450
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, skey.Bytes(), 0)
451 452 453
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]pstore.PeerInfo{pi})
	return pmes, nil
}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
454

Brian Tiger Chow's avatar
Brian Tiger Chow committed
455
// FindProviders searches until the context expires.
456
func (dht *IpfsDHT) FindProviders(ctx context.Context, c cid.Cid) ([]pstore.PeerInfo, error) {
Jeromy's avatar
Jeromy committed
457
	var providers []pstore.PeerInfo
458
	for p := range dht.FindProvidersAsync(ctx, c, KValue) {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
459 460 461 462 463
		providers = append(providers, p)
	}
	return providers, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
464 465 466
// 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.
467
func (dht *IpfsDHT) FindProvidersAsync(ctx context.Context, key cid.Cid, count int) <-chan pstore.PeerInfo {
Matt Joiner's avatar
Matt Joiner committed
468
	logger.Event(ctx, "findProviders", key)
Jeromy's avatar
Jeromy committed
469
	peerOut := make(chan pstore.PeerInfo, count)
Jeromy's avatar
Jeromy committed
470 471 472 473
	go dht.findProvidersAsyncRoutine(ctx, key, count, peerOut)
	return peerOut
}

474
func (dht *IpfsDHT) findProvidersAsyncRoutine(ctx context.Context, key cid.Cid, count int, peerOut chan pstore.PeerInfo) {
Matt Joiner's avatar
Matt Joiner committed
475
	defer logger.EventBegin(ctx, "findProvidersAsync", key).Done()
Jeromy's avatar
Jeromy committed
476 477
	defer close(peerOut)

Jeromy's avatar
Jeromy committed
478
	ps := pset.NewLimited(count)
Jeromy's avatar
Jeromy committed
479 480
	provs := dht.providers.GetProviders(ctx, key)
	for _, p := range provs {
481
		// NOTE: Assuming that this list of peers is unique
Jeromy's avatar
Jeromy committed
482
		if ps.TryAdd(p) {
Jeromy's avatar
Jeromy committed
483
			pi := dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
484
			select {
Jeromy's avatar
Jeromy committed
485
			case peerOut <- pi:
Jeromy's avatar
Jeromy committed
486 487 488
			case <-ctx.Done():
				return
			}
Jeromy's avatar
Jeromy committed
489
		}
Jeromy's avatar
Jeromy committed
490

491
		// If we have enough peers locally, don't bother with remote RPC
Jeromy's avatar
Jeromy committed
492
		// TODO: is this a DOS vector?
Jeromy's avatar
Jeromy committed
493
		if ps.Size() >= count {
Jeromy's avatar
Jeromy committed
494 495 496 497
			return
		}
	}

498 499 500 501 502 503 504 505 506
	peers := dht.routingTable.NearestPeers(kb.ConvertKey(key.KeyString()), AlphaValue)
	if len(peers) == 0 {
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type:  notif.QueryError,
			Extra: kb.ErrLookupFailure.Error(),
		})
		return
	}

Jeromy's avatar
Jeromy committed
507
	// setup the Query
Jeromy's avatar
Jeromy committed
508
	parent := ctx
509
	query := dht.newQuery(key.KeyString(), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
510
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
511 512 513
			Type: notif.SendingQuery,
			ID:   p,
		})
514
		pmes, err := dht.findProvidersSingle(ctx, p, key)
Jeromy's avatar
Jeromy committed
515 516 517 518
		if err != nil {
			return nil, err
		}

Matt Joiner's avatar
Matt Joiner committed
519
		logger.Debugf("%d provider entries", len(pmes.GetProviderPeers()))
520
		provs := pb.PBPeersToPeerInfos(pmes.GetProviderPeers())
Matt Joiner's avatar
Matt Joiner committed
521
		logger.Debugf("%d provider entries decoded", len(provs))
Jeromy's avatar
Jeromy committed
522 523 524

		// Add unique providers from request, up to 'count'
		for _, prov := range provs {
525 526 527
			if prov.ID != dht.self {
				dht.peerstore.AddAddrs(prov.ID, prov.Addrs, pstore.TempAddrTTL)
			}
Matt Joiner's avatar
Matt Joiner committed
528
			logger.Debugf("got provider: %s", prov)
529
			if ps.TryAdd(prov.ID) {
Matt Joiner's avatar
Matt Joiner committed
530
				logger.Debugf("using provider: %s", prov)
Jeromy's avatar
Jeromy committed
531
				select {
Jeromy's avatar
Jeromy committed
532
				case peerOut <- *prov:
Jeromy's avatar
Jeromy committed
533
				case <-ctx.Done():
Matt Joiner's avatar
Matt Joiner committed
534
					logger.Debug("context timed out sending more providers")
Jeromy's avatar
Jeromy committed
535 536
					return nil, ctx.Err()
				}
537
			}
Jeromy's avatar
Jeromy committed
538
			if ps.Size() >= count {
Matt Joiner's avatar
Matt Joiner committed
539
				logger.Debugf("got enough providers (%d/%d)", ps.Size(), count)
Jeromy's avatar
Jeromy committed
540
				return &dhtQueryResult{success: true}, nil
541 542 543
			}
		}

Jeromy's avatar
Jeromy committed
544 545
		// Give closer peers back to the query to be queried
		closer := pmes.GetCloserPeers()
546
		clpeers := pb.PBPeersToPeerInfos(closer)
Matt Joiner's avatar
Matt Joiner committed
547
		logger.Debugf("got closer peers: %d %s", len(clpeers), clpeers)
548

Jeromy's avatar
Jeromy committed
549
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
550 551
			Type:      notif.PeerResponse,
			ID:        p,
Jeromy's avatar
Jeromy committed
552
			Responses: clpeers,
553
		})
Jeromy's avatar
Jeromy committed
554 555 556 557 558
		return &dhtQueryResult{closerPeers: clpeers}, nil
	})

	_, err := query.Run(ctx, peers)
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
559
		logger.Debugf("Query error: %s", err)
560 561
		// Special handling for issue: https://github.com/ipfs/go-ipfs/issues/3032
		if fmt.Sprint(err) == "<nil>" {
Matt Joiner's avatar
Matt Joiner committed
562 563 564 565
			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")
566 567 568 569

			// replace problematic error with something that won't crash the daemon
			err = fmt.Errorf("<nil>")
		}
570 571 572 573
		notif.PublishQueryEvent(ctx, &notif.QueryEvent{
			Type:  notif.QueryError,
			Extra: err.Error(),
		})
Jeromy's avatar
Jeromy committed
574
	}
575 576
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
577
// FindPeer searches for a peer with given ID.
578
func (dht *IpfsDHT) FindPeer(ctx context.Context, id peer.ID) (_ pstore.PeerInfo, err error) {
Matt Joiner's avatar
Matt Joiner committed
579
	eip := logger.EventBegin(ctx, "FindPeer", id)
580 581 582 583 584 585
	defer func() {
		if err != nil {
			eip.SetError(err)
		}
		eip.Done()
	}()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
586

587
	// Check if were already connected to them
Jeromy's avatar
Jeromy committed
588
	if pi := dht.FindLocal(id); pi.ID != "" {
589
		return pi, nil
590 591
	}

Jeromy's avatar
Jeromy committed
592
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
593
	if len(peers) == 0 {
Steven Allen's avatar
Steven Allen committed
594
		return pstore.PeerInfo{}, kb.ErrLookupFailure
595
	}
596

Jeromy's avatar
Jeromy committed
597
	// Sanity...
598
	for _, p := range peers {
599
		if p == id {
Matt Joiner's avatar
Matt Joiner committed
600
			logger.Debug("found target peer in list of closest peers...")
601
			return dht.peerstore.PeerInfo(p), nil
602
		}
603
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
604

Jeromy's avatar
Jeromy committed
605
	// setup the Query
Jeromy's avatar
Jeromy committed
606
	parent := ctx
607
	query := dht.newQuery(string(id), func(ctx context.Context, p peer.ID) (*dhtQueryResult, error) {
Jeromy's avatar
Jeromy committed
608
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
609 610 611
			Type: notif.SendingQuery,
			ID:   p,
		})
Jeromy's avatar
Jeromy committed
612

613
		pmes, err := dht.findPeerSingle(ctx, p, id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
614
		if err != nil {
615
			return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
616
		}
617

Jeromy's avatar
Jeromy committed
618
		closer := pmes.GetCloserPeers()
619
		clpeerInfos := pb.PBPeersToPeerInfos(closer)
620

621
		// see if we got the peer here
622 623
		for _, npi := range clpeerInfos {
			if npi.ID == id {
Jeromy's avatar
Jeromy committed
624
				return &dhtQueryResult{
625
					peer:    npi,
Jeromy's avatar
Jeromy committed
626 627 628
					success: true,
				}, nil
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
629 630
		}

Jeromy's avatar
Jeromy committed
631
		notif.PublishQueryEvent(parent, &notif.QueryEvent{
632
			Type:      notif.PeerResponse,
633
			ID:        p,
Jeromy's avatar
Jeromy committed
634
			Responses: clpeerInfos,
635 636
		})

637
		return &dhtQueryResult{closerPeers: clpeerInfos}, nil
638
	})
639

Jeromy's avatar
Jeromy committed
640
	// run it!
641
	result, err := query.Run(ctx, peers)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
642
	if err != nil {
Jeromy's avatar
Jeromy committed
643
		return pstore.PeerInfo{}, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
644 645
	}

Matt Joiner's avatar
Matt Joiner committed
646
	logger.Debugf("FindPeer %v %v", id, result.success)
647
	if result.peer.ID == "" {
Jeromy's avatar
Jeromy committed
648
		return pstore.PeerInfo{}, routing.ErrNotFound
649
	}
Jeromy's avatar
Jeromy committed
650

Jeromy's avatar
Jeromy committed
651
	return *result.peer, nil
652 653
}

654
// FindPeersConnectedToPeer searches for peers directly connected to a given peer.
Jeromy's avatar
Jeromy committed
655
func (dht *IpfsDHT) FindPeersConnectedToPeer(ctx context.Context, id peer.ID) (<-chan *pstore.PeerInfo, error) {
656

Jeromy's avatar
Jeromy committed
657
	peerchan := make(chan *pstore.PeerInfo, asyncQueryBuffer)
Jeromy's avatar
Jeromy committed
658
	peersSeen := make(map[peer.ID]struct{})
659
	var peersSeenMx sync.Mutex
660

Jeromy's avatar
Jeromy committed
661
	peers := dht.routingTable.NearestPeers(kb.ConvertPeerID(id), AlphaValue)
662
	if len(peers) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
663
		return nil, kb.ErrLookupFailure
664 665 666
	}

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

669
		pmes, err := dht.findPeerSingle(ctx, p, id)
670 671 672 673
		if err != nil {
			return nil, err
		}

Jeromy's avatar
Jeromy committed
674
		var clpeers []*pstore.PeerInfo
675 676
		closer := pmes.GetCloserPeers()
		for _, pbp := range closer {
677
			pi := pb.PBPeerToPeerInfo(pbp)
678

679
			// skip peers already seen
680
			peersSeenMx.Lock()
681
			if _, found := peersSeen[pi.ID]; found {
682
				peersSeenMx.Unlock()
683 684
				continue
			}
685
			peersSeen[pi.ID] = struct{}{}
686
			peersSeenMx.Unlock()
687 688

			// if peer is connected, send it to our client.
689
			if pb.Connectedness(pbp.Connection) == inet.Connected {
690 691 692
				select {
				case <-ctx.Done():
					return nil, ctx.Err()
693
				case peerchan <- pi:
694 695 696 697
				}
			}

			// if peer is the peer we're looking for, don't bother querying it.
698
			// TODO maybe query it?
699
			if pb.Connectedness(pbp.Connection) != inet.Connected {
700
				clpeers = append(clpeers, pi)
701 702 703 704 705 706 707 708 709
			}
		}

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

	// run it! run it asynchronously to gen peers as results are found.
	// this does no error checking
	go func() {
710
		if _, err := query.Run(ctx, peers); err != nil {
Matt Joiner's avatar
Matt Joiner committed
711
			logger.Debug(err)
712 713 714 715 716 717 718 719
		}

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

	return peerchan, nil
}