dht.go 18.4 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2
package dht

3
import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4
	"bytes"
Jeromy's avatar
Jeromy committed
5
	"context"
6
	"errors"
7
	"fmt"
Adin Schmahmann's avatar
Adin Schmahmann committed
8
	"math/rand"
9 10
	"sync"
	"time"
11

12 13 14 15 16 17 18
	"github.com/libp2p/go-libp2p-core/host"
	"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/protocol"
	"github.com/libp2p/go-libp2p-core/routing"

19
	"go.opencensus.io/tag"
20

21
	"github.com/libp2p/go-libp2p-kad-dht/metrics"
22
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
Aarsh Shah's avatar
Aarsh Shah committed
23
	"github.com/libp2p/go-libp2p-kad-dht/providers"
24

Aarsh Shah's avatar
Aarsh Shah committed
25
	"github.com/gogo/protobuf/proto"
26 27
	ds "github.com/ipfs/go-datastore"
	logging "github.com/ipfs/go-log"
Aarsh Shah's avatar
Aarsh Shah committed
28
	"github.com/jbenet/goprocess"
Henrique Dias's avatar
Henrique Dias committed
29
	goprocessctx "github.com/jbenet/goprocess/context"
George Antoniadis's avatar
George Antoniadis committed
30
	kb "github.com/libp2p/go-libp2p-kbucket"
Henrique Dias's avatar
Henrique Dias committed
31
	record "github.com/libp2p/go-libp2p-record"
George Antoniadis's avatar
George Antoniadis committed
32
	recpb "github.com/libp2p/go-libp2p-record/pb"
Steven Allen's avatar
Steven Allen committed
33
	"github.com/multiformats/go-base32"
Adin Schmahmann's avatar
Adin Schmahmann committed
34
	"github.com/multiformats/go-multihash"
35 36
)

Matt Joiner's avatar
Matt Joiner committed
37
var logger = logging.Logger("dht")
Aarsh Shah's avatar
Aarsh Shah committed
38
var rtPvLogger = logging.Logger("dht/rt-validation")
39

Henrique Dias's avatar
Henrique Dias committed
40 41
const BaseConnMgrScore = 5

42 43 44 45 46 47 48
type mode int

const (
	modeServer mode = 1
	modeClient      = 2
)

Adin Schmahmann's avatar
Adin Schmahmann committed
49 50 51 52 53
const (
	kad1 protocol.ID = "/kad/1.0.0"
	kad2 protocol.ID = "/kad/2.0.0"
)

54
// IpfsDHT is an implementation of Kademlia with S/Kademlia modifications.
55
// It is used to implement the base Routing module.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56
type IpfsDHT struct {
57 58 59
	host      host.Host           // the network services we need
	self      peer.ID             // Local peer (yourself)
	peerstore peerstore.Peerstore // Peer Registry
60

61
	datastore ds.Datastore // Local data
62

63
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
64 65
	// ProviderManager stores & manages the provider records for this Dht peer.
	ProviderManager *providers.ProviderManager
66

Adin Schmahmann's avatar
Adin Schmahmann committed
67 68
	birth time.Time  // When this peer started up
	rng   *rand.Rand // Source of randomness
69
	rnglk sync.Mutex // Rand does not support concurrency
70

71
	Validator record.Validator
72

73 74
	ctx  context.Context
	proc goprocess.Process
75 76 77

	strmap map[peer.ID]*messageSender
	smlk   sync.Mutex
78

Steven Allen's avatar
Steven Allen committed
79
	plk sync.Mutex
80

81 82
	stripedPutLocks [256]sync.Mutex

Adin Schmahmann's avatar
Adin Schmahmann committed
83 84 85 86 87
	// Primary DHT protocols - we query and respond to these protocols
	protocols []protocol.ID

	// DHT protocols we can respond to (may contain protocols in addition to the primary protocols)
	serverProtocols []protocol.ID
88

89 90 91 92
	auto   bool
	mode   mode
	modeLk sync.Mutex

93
	bucketSize int
94
	alpha      int // The concurrency parameter per path
Adin Schmahmann's avatar
Adin Schmahmann committed
95
	beta       int // The number of peers closest to a target that must have responded for a query path to terminate
Adin Schmahmann's avatar
Adin Schmahmann committed
96
	d          int // Number of Disjoint Paths to query
97

98 99 100
	autoRefresh           bool
	rtRefreshQueryTimeout time.Duration
	rtRefreshPeriod       time.Duration
Steven Allen's avatar
Steven Allen committed
101
	triggerRtRefresh      chan chan<- error
Aarsh Shah's avatar
Aarsh Shah committed
102
	triggerSelfLookup     chan chan<- error
Aarsh Shah's avatar
Aarsh Shah committed
103 104

	maxRecordAge time.Duration
105

106 107 108
	// Allows disabling dht subsystems. These should _only_ be set on
	// "forked" DHTs (e.g., DHTs with custom protocols and/or private
	// networks).
109
	enableProviders, enableValues bool
110 111
}

Matt Joiner's avatar
Matt Joiner committed
112 113 114 115
// Assert that IPFS assumptions about interfaces aren't broken. These aren't a
// guarantee, but we can use them to aid refactoring.
var (
	_ routing.ContentRouting = (*IpfsDHT)(nil)
116
	_ routing.Routing        = (*IpfsDHT)(nil)
Matt Joiner's avatar
Matt Joiner committed
117 118 119 120 121
	_ routing.PeerRouting    = (*IpfsDHT)(nil)
	_ routing.PubKeyFetcher  = (*IpfsDHT)(nil)
	_ routing.ValueStore     = (*IpfsDHT)(nil)
)

122
// New creates a new DHT with the specified host and options.
123 124
func New(ctx context.Context, h host.Host, options ...Option) (*IpfsDHT, error) {
	var cfg config
Adin Schmahmann's avatar
Adin Schmahmann committed
125
	if err := cfg.apply(append([]Option{defaults}, options...)...); err != nil {
126 127
		return nil, err
	}
Adin Schmahmann's avatar
Adin Schmahmann committed
128 129 130 131 132
	if err := cfg.applyFallbacks(); err != nil {
		return nil, err
	}
	if err := cfg.validate(); err != nil {
		return nil, err
133
	}
Aarsh Shah's avatar
Aarsh Shah committed
134 135 136 137
	dht, err := makeDHT(ctx, h, cfg)
	if err != nil {
		return nil, fmt.Errorf("failed to create DHT, err=%s", err)
	}
Adin Schmahmann's avatar
Adin Schmahmann committed
138

139 140 141
	dht.autoRefresh = cfg.routingTable.autoRefresh
	dht.rtRefreshPeriod = cfg.routingTable.refreshPeriod
	dht.rtRefreshQueryTimeout = cfg.routingTable.refreshQueryTimeout
142

143 144 145
	dht.maxRecordAge = cfg.maxRecordAge
	dht.enableProviders = cfg.enableProviders
	dht.enableValues = cfg.enableValues
Aarsh Shah's avatar
Aarsh Shah committed
146

147
	dht.Validator = cfg.validator
148

149 150
	switch cfg.mode {
	case ModeAuto:
151 152
		dht.auto = true
		dht.mode = modeClient
153
	case ModeClient:
154 155
		dht.auto = false
		dht.mode = modeClient
156
	case ModeServer:
157 158 159
		dht.auto = false
		dht.mode = modeServer
	default:
160
		return nil, fmt.Errorf("invalid dht mode %d", cfg.mode)
161 162 163 164 165
	}

	if dht.mode == modeServer {
		if err := dht.moveToServerMode(); err != nil {
			return nil, err
166
		}
167
	}
168 169 170 171 172 173 174 175 176 177

	// register for event bus and network notifications
	sn, err := newSubscriberNotifiee(dht)
	if err != nil {
		return nil, err
	}
	dht.proc.Go(sn.subscribe)
	// handle providers
	dht.proc.AddChild(dht.ProviderManager.Process())

Aarsh Shah's avatar
Aarsh Shah committed
178
	dht.startSelfLookup()
179
	dht.startRefreshing()
180 181
	return dht, nil
}
182

183 184 185 186
// NewDHT creates a new DHT object with the given peer as the 'local' host.
// IpfsDHT's initialized with this function will respond to DHT requests,
// whereas IpfsDHT's initialized with NewDHTClient will not.
func NewDHT(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
187
	dht, err := New(ctx, h, Datastore(dstore))
188 189 190 191 192 193 194 195 196 197 198
	if err != nil {
		panic(err)
	}
	return dht
}

// NewDHTClient creates a new DHT object with the given peer as the 'local'
// host. IpfsDHT clients initialized with this function will not respond to DHT
// requests. If you need a peer to respond to DHT requests, use NewDHT instead.
// NewDHTClient creates a new DHT object with the given peer as the 'local' host
func NewDHTClient(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
Adin Schmahmann's avatar
Adin Schmahmann committed
199
	dht, err := New(ctx, h, Datastore(dstore), Mode(ModeClient))
200 201 202
	if err != nil {
		panic(err)
	}
203 204 205
	return dht
}

Aarsh Shah's avatar
Aarsh Shah committed
206
func makeDHT(ctx context.Context, h host.Host, cfg config) (*IpfsDHT, error) {
207

Adin Schmahmann's avatar
Adin Schmahmann committed
208 209 210 211 212 213 214 215 216 217 218 219 220
	protocols := []protocol.ID{cfg.protocolPrefix + kad2}
	serverProtocols := []protocol.ID{cfg.protocolPrefix + kad2, cfg.protocolPrefix + kad1}

	// check if custom test protocols were set
	if len(cfg.testProtocols) > 0 {
		protocols = make([]protocol.ID, len(cfg.testProtocols))
		serverProtocols = make([]protocol.ID, len(cfg.testProtocols))
		for i, p := range cfg.testProtocols {
			protocols[i] = cfg.protocolPrefix + p
			serverProtocols[i] = cfg.protocolPrefix + p
		}
	}

221
	dht := &IpfsDHT{
Aarsh Shah's avatar
Aarsh Shah committed
222 223 224 225 226 227 228 229 230 231 232
		datastore:         cfg.datastore,
		self:              h.ID(),
		peerstore:         h.Peerstore(),
		host:              h,
		strmap:            make(map[peer.ID]*messageSender),
		birth:             time.Now(),
		rng:               rand.New(rand.NewSource(rand.Int63())),
		protocols:         protocols,
		serverProtocols:   serverProtocols,
		bucketSize:        cfg.bucketSize,
		alpha:             cfg.concurrency,
Adin Schmahmann's avatar
Adin Schmahmann committed
233
		beta:              cfg.resiliency,
Aarsh Shah's avatar
Aarsh Shah committed
234 235 236
		d:                 cfg.disjointPaths,
		triggerRtRefresh:  make(chan chan<- error),
		triggerSelfLookup: make(chan chan<- error),
Jeromy's avatar
Jeromy committed
237
	}
238

Aarsh Shah's avatar
Aarsh Shah committed
239 240 241 242 243 244 245
	// construct routing table
	rt, err := makeRoutingTable(dht, cfg)
	if err != nil {
		return nil, fmt.Errorf("failed to construct routing table,err=%s", err)
	}
	dht.routingTable = rt

246 247
	// create a DHT proc with the given context
	dht.proc = goprocessctx.WithContext(ctx)
Aarsh Shah's avatar
Aarsh Shah committed
248 249 250 251 252 253

	// create a tagged context derived from the original context
	ctxTags := dht.newContextWithLocalTags(ctx)
	// the DHT context should be done when the process is closed
	dht.ctx = goprocessctx.WithProcessClosing(ctxTags, dht.proc)

254
	dht.ProviderManager = providers.NewProviderManager(dht.ctx, h.ID(), cfg.datastore)
255

Aarsh Shah's avatar
Aarsh Shah committed
256
	return dht, nil
Jeromy's avatar
Jeromy committed
257 258
}

Aarsh Shah's avatar
Aarsh Shah committed
259 260
func makeRoutingTable(dht *IpfsDHT, cfg config) (*kb.RoutingTable, error) {
	self := kb.ConvertPeerID(dht.host.ID())
Aarsh Shah's avatar
Aarsh Shah committed
261 262
	// construct the routing table with a peer validation function
	pvF := func(c context.Context, p peer.ID) bool {
Aarsh Shah's avatar
Aarsh Shah committed
263 264
		// connect should work
		if err := dht.host.Connect(c, peer.AddrInfo{ID: p}); err != nil {
Aarsh Shah's avatar
Aarsh Shah committed
265
			rtPvLogger.Infof("failed to connect to peer %s for validation, err=%s", p, err)
Aarsh Shah's avatar
Aarsh Shah committed
266
			return false
267
		}
Aarsh Shah's avatar
Aarsh Shah committed
268 269 270 271 272

		// peer should support the DHT protocol
		b, err := dht.validRTPeer(p)
		if err != nil {
			rtPvLogger.Errorf("failed to check if peer %s supports DHT protocol, err=%s", p, err)
Aarsh Shah's avatar
Aarsh Shah committed
273
			return false
Aarsh Shah's avatar
Aarsh Shah committed
274 275 276
		}

		return b
277 278
	}

Aarsh Shah's avatar
Aarsh Shah committed
279 280 281
	rtOpts := []kb.Option{kb.PeerValidationFnc(pvF)}
	if !(cfg.routingTable.checkInterval == 0) {
		rtOpts = append(rtOpts, kb.TableCleanupInterval(cfg.routingTable.checkInterval))
282
	}
Aarsh Shah's avatar
Aarsh Shah committed
283

Aarsh Shah's avatar
Aarsh Shah committed
284
	rt, err := kb.NewRoutingTable(cfg.bucketSize, self, time.Minute, dht.host.Peerstore(),
Aarsh Shah's avatar
Aarsh Shah committed
285
		rtOpts...)
Aarsh Shah's avatar
Aarsh Shah committed
286
	cmgr := dht.host.ConnManager()
Aarsh Shah's avatar
Aarsh Shah committed
287 288 289 290 291 292 293 294 295 296 297

	rt.PeerAdded = func(p peer.ID) {
		commonPrefixLen := kb.CommonPrefixLen(self, kb.ConvertPeerID(p))
		cmgr.TagPeer(p, "kbucket", BaseConnMgrScore+commonPrefixLen)
	}
	rt.PeerRemoved = func(p peer.ID) {
		cmgr.UntagPeer(p, "kbucket")
	}

	return rt, err
}
298

Jeromy's avatar
Jeromy committed
299
// putValueToPeer stores the given key/value pair at the peer 'p'
300 301
func (dht *IpfsDHT) putValueToPeer(ctx context.Context, p peer.ID, rec *recpb.Record) error {
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, rec.Key, 0)
302
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
303
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
304
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
305
		logger.Debugf("putValueToPeer: %v. (peer: %s, key: %s)", err, p.Pretty(), loggableKey(string(rec.Key)))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
306 307
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
308

309
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Matt Joiner's avatar
Matt Joiner committed
310
		logger.Warningf("putValueToPeer: value not put correctly. (%v != %v)", pmes, rpmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
311 312
		return errors.New("value not put correctly")
	}
gpestana's avatar
gpestana committed
313

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
314
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
315 316
}

317 318
var errInvalidRecord = errors.New("received invalid record")

319 320
// getValueOrPeers queries a particular peer p for the value for
// key. It returns either the value or a list of closer peers.
321
// NOTE: It will update the dht's peerstore with any new addresses
322
// it finds for the given peer.
323
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.ID, key string) (*recpb.Record, []*peer.AddrInfo, error) {
324
	pmes, err := dht.getValueSingle(ctx, p, key)
325
	if err != nil {
326
		return nil, nil, err
327 328
	}

329 330 331
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

332
	if record := pmes.GetRecord(); record != nil {
333
		// Success! We were given the value
Matt Joiner's avatar
Matt Joiner committed
334
		logger.Debug("getValueOrPeers: got value")
335

336
		// make sure record is valid.
337
		err = dht.Validator.Validate(string(record.GetKey()), record.GetValue())
338
		if err != nil {
Matt Joiner's avatar
Matt Joiner committed
339
			logger.Info("Received invalid record! (discarded)")
340 341
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
George Antoniadis's avatar
George Antoniadis committed
342
			record = new(recpb.Record)
343
		}
344
		return record, peers, err
345
	}
346

347
	if len(peers) > 0 {
Matt Joiner's avatar
Matt Joiner committed
348
		logger.Debug("getValueOrPeers: peers")
349 350 351
		return nil, peers, nil
	}

Matt Joiner's avatar
Matt Joiner committed
352
	logger.Warning("getValueOrPeers: routing.ErrNotFound")
353
	return nil, nil, routing.ErrNotFound
354 355
}

356
// getValueSingle simply performs the get value RPC with the given parameters
357 358 359 360 361 362
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID, key string) (*pb.Message, error) {
	meta := logging.LoggableMap{
		"key":  key,
		"peer": p,
	}

Matt Joiner's avatar
Matt Joiner committed
363
	eip := logger.EventBegin(ctx, "getValueSingle", meta)
ForrestWeston's avatar
ForrestWeston committed
364
	defer eip.Done()
365

366
	pmes := pb.NewMessage(pb.Message_GET_VALUE, []byte(key), 0)
367 368 369 370 371
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Matt Joiner's avatar
Matt Joiner committed
372
		logger.Warningf("getValueSingle: read timeout %s %s", p.Pretty(), key)
373 374
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
375
		eip.SetError(err)
376 377
		return nil, err
	}
Jeromy's avatar
Jeromy committed
378 379
}

380
// getLocal attempts to retrieve the value from the datastore
381
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
Matt Joiner's avatar
Matt Joiner committed
382
	logger.Debugf("getLocal %s", key)
383
	rec, err := dht.getRecordFromDatastore(mkDsKey(key))
384
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
385
		logger.Warningf("getLocal: %s", err)
386 387
		return nil, err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
388

389
	// Double check the key. Can't hurt.
390
	if rec != nil && string(rec.GetKey()) != key {
Matt Joiner's avatar
Matt Joiner committed
391
		logger.Errorf("BUG getLocal: found a DHT record that didn't match it's key: %s != %s", rec.GetKey(), key)
Steven Allen's avatar
Steven Allen committed
392
		return nil, nil
393 394

	}
395
	return rec, nil
396 397
}

398
// putLocal stores the key value pair in the datastore
399
func (dht *IpfsDHT) putLocal(key string, rec *recpb.Record) error {
Matt Joiner's avatar
Matt Joiner committed
400
	logger.Debugf("putLocal: %v %v", key, rec)
401 402
	data, err := proto.Marshal(rec)
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
403
		logger.Warningf("putLocal: %s", err)
404 405 406
		return err
	}

407
	return dht.datastore.Put(mkDsKey(key), data)
408
}
409

Aarsh Shah's avatar
Aarsh Shah committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
// peerFound signals the routingTable that we've found a peer that
// supports the DHT protocol.
func (dht *IpfsDHT) peerFound(ctx context.Context, p peer.ID) {
	logger.Event(ctx, "peerFound", p)
	dht.routingTable.HandlePeerAlive(p)
}

// peerStoppedDHT signals the routing table that a peer has stopped supporting the DHT protocol.
func (dht *IpfsDHT) peerStoppedDHT(ctx context.Context, p peer.ID) {
	logger.Event(ctx, "peerStoppedDHT", p)
	// A peer that does not support the DHT protocol is dead for us.
	// There's no point in talking to anymore till it starts supporting the DHT protocol again.
	dht.routingTable.HandlePeerDead(p)
}

// peerDisconnected signals the routing table that a peer is not connected anymore.
func (dht *IpfsDHT) peerDisconnected(ctx context.Context, p peer.ID) {
	logger.Event(ctx, "peerDisconnected", p)
	dht.routingTable.HandlePeerDisconnect(p)

430
}
Jeromy's avatar
Jeromy committed
431

Jeromy's avatar
Jeromy committed
432
// FindLocal looks for a peer with a given ID connected to this dht and returns the peer and the table it was found in.
433
func (dht *IpfsDHT) FindLocal(id peer.ID) peer.AddrInfo {
434
	switch dht.host.Network().Connectedness(id) {
435
	case network.Connected, network.CanConnect:
436 437
		return dht.peerstore.PeerInfo(id)
	default:
438
		return peer.AddrInfo{}
Jeromy's avatar
Jeromy committed
439 440
	}
}
441

Jeromy's avatar
Jeromy committed
442
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
443
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
Matt Joiner's avatar
Matt Joiner committed
444
	eip := logger.EventBegin(ctx, "findPeerSingle",
445 446 447 448
		logging.LoggableMap{
			"peer":   p,
			"target": id,
		})
ForrestWeston's avatar
ForrestWeston committed
449
	defer eip.Done()
450

451
	pmes := pb.NewMessage(pb.Message_FIND_NODE, []byte(id), 0)
452 453 454 455 456
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Matt Joiner's avatar
Matt Joiner committed
457
		logger.Warningf("read timeout: %s %s", p.Pretty(), id)
458 459
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
460
		eip.SetError(err)
461 462
		return nil, err
	}
463
}
464

Adin Schmahmann's avatar
Adin Schmahmann committed
465 466
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.ID, key multihash.Multihash) (*pb.Message, error) {
	eip := logger.EventBegin(ctx, "findProvidersSingle", p, multihashLoggableKey(key))
ForrestWeston's avatar
ForrestWeston committed
467
	defer eip.Done()
468

Adin Schmahmann's avatar
Adin Schmahmann committed
469
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, key, 0)
470 471 472 473 474
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Adin Schmahmann's avatar
Adin Schmahmann committed
475
		logger.Warningf("read timeout: %s %s", p.Pretty(), key)
476 477
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
478
		eip.SetError(err)
479 480
		return nil, err
	}
Jeromy's avatar
Jeromy committed
481 482
}

483
// nearestPeersToQuery returns the routing tables closest peers.
484
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
485
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(string(pmes.GetKey())), count)
486 487 488
	return closer
}

Aarsh Shah's avatar
Aarsh Shah committed
489
// betterPeersToQuery returns nearestPeersToQuery with some additional filtering
490
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
491
	closer := dht.nearestPeersToQuery(pmes, count)
492 493 494

	// no node? nil
	if closer == nil {
Matt Joiner's avatar
Matt Joiner committed
495
		logger.Warning("betterPeersToQuery: no closer peers to send:", p)
496 497 498
		return nil
	}

Steven Allen's avatar
Steven Allen committed
499
	filtered := make([]peer.ID, 0, len(closer))
Jeromy's avatar
Jeromy committed
500 501 502
	for _, clp := range closer {

		// == to self? thats bad
Jeromy's avatar
Jeromy committed
503
		if clp == dht.self {
Matt Joiner's avatar
Matt Joiner committed
504
			logger.Error("BUG betterPeersToQuery: attempted to return self! this shouldn't happen...")
505 506
			return nil
		}
507
		// Dont send a peer back themselves
Jeromy's avatar
Jeromy committed
508
		if clp == p {
509 510 511
			continue
		}

Jeromy's avatar
Jeromy committed
512
		filtered = append(filtered, clp)
513 514
	}

515 516
	// ok seems like closer nodes
	return filtered
517 518
}

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
func (dht *IpfsDHT) setMode(m mode) error {
	dht.modeLk.Lock()
	defer dht.modeLk.Unlock()

	if m == dht.mode {
		return nil
	}

	switch m {
	case modeServer:
		return dht.moveToServerMode()
	case modeClient:
		return dht.moveToClientMode()
	default:
		return fmt.Errorf("unrecognized dht mode: %d", m)
	}
}

Adin Schmahmann's avatar
Adin Schmahmann committed
537 538 539
// moveToServerMode advertises (via libp2p identify updates) that we are able to respond to DHT queries and sets the appropriate stream handlers.
// Note: We may support responding to queries with protocols aside from our primary ones in order to support
// interoperability with older versions of the DHT protocol.
540 541
func (dht *IpfsDHT) moveToServerMode() error {
	dht.mode = modeServer
Adin Schmahmann's avatar
Adin Schmahmann committed
542
	for _, p := range dht.serverProtocols {
543 544 545 546 547
		dht.host.SetStreamHandler(p, dht.handleNewStream)
	}
	return nil
}

Adin Schmahmann's avatar
Adin Schmahmann committed
548 549 550 551 552
// moveToClientMode stops advertising (and rescinds advertisements via libp2p identify updates) that we are able to
// respond to DHT queries and removes the appropriate stream handlers. We also kill all inbound streams that were
// utilizing the handled protocols.
// Note: We may support responding to queries with protocols aside from our primary ones in order to support
// interoperability with older versions of the DHT protocol.
553 554
func (dht *IpfsDHT) moveToClientMode() error {
	dht.mode = modeClient
Adin Schmahmann's avatar
Adin Schmahmann committed
555
	for _, p := range dht.serverProtocols {
556 557 558 559
		dht.host.RemoveStreamHandler(p)
	}

	pset := make(map[protocol.ID]bool)
Adin Schmahmann's avatar
Adin Schmahmann committed
560
	for _, p := range dht.serverProtocols {
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
		pset[p] = true
	}

	for _, c := range dht.host.Network().Conns() {
		for _, s := range c.GetStreams() {
			if pset[s.Protocol()] {
				if s.Stat().Direction == network.DirInbound {
					s.Reset()
				}
			}
		}
	}
	return nil
}

func (dht *IpfsDHT) getMode() mode {
	dht.modeLk.Lock()
	defer dht.modeLk.Unlock()
	return dht.mode
}

582 583 584 585 586 587 588 589 590 591
// Context return dht's context
func (dht *IpfsDHT) Context() context.Context {
	return dht.ctx
}

// Process return dht's process
func (dht *IpfsDHT) Process() goprocess.Process {
	return dht.proc
}

ZhengQi's avatar
ZhengQi committed
592 593 594 595 596
// RoutingTable return dht's routingTable
func (dht *IpfsDHT) RoutingTable() *kb.RoutingTable {
	return dht.routingTable
}

597 598 599 600
// Close calls Process Close
func (dht *IpfsDHT) Close() error {
	return dht.proc.Close()
}
601 602 603 604

func mkDsKey(s string) ds.Key {
	return ds.NewKey(base32.RawStdEncoding.EncodeToString([]byte(s)))
}
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621

func (dht *IpfsDHT) PeerID() peer.ID {
	return dht.self
}

func (dht *IpfsDHT) PeerKey() []byte {
	return kb.ConvertPeerID(dht.self)
}

func (dht *IpfsDHT) Host() host.Host {
	return dht.host
}

func (dht *IpfsDHT) Ping(ctx context.Context, p peer.ID) error {
	req := pb.NewMessage(pb.Message_PING, nil, 0)
	resp, err := dht.sendRequest(ctx, p, req)
	if err != nil {
Steven Allen's avatar
Steven Allen committed
622
		return fmt.Errorf("sending request: %w", err)
623 624
	}
	if resp.Type != pb.Message_PING {
Steven Allen's avatar
Steven Allen committed
625
		return fmt.Errorf("got unexpected response type: %v", resp.Type)
626 627 628
	}
	return nil
}
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644

// newContextWithLocalTags returns a new context.Context with the InstanceID and
// PeerID keys populated. It will also take any extra tags that need adding to
// the context as tag.Mutators.
func (dht *IpfsDHT) newContextWithLocalTags(ctx context.Context, extraTags ...tag.Mutator) context.Context {
	extraTags = append(
		extraTags,
		tag.Upsert(metrics.KeyPeerID, dht.self.Pretty()),
		tag.Upsert(metrics.KeyInstanceID, fmt.Sprintf("%p", dht)),
	)
	ctx, _ = tag.New(
		ctx,
		extraTags...,
	) // ignoring error as it is unrelated to the actual function of this code.
	return ctx
}