dht.go 18.3 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
	d          int // Number of Disjoint Paths to query
96

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

	maxRecordAge time.Duration
104

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

Matt Joiner's avatar
Matt Joiner committed
111 112 113 114
// 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)
115
	_ routing.Routing        = (*IpfsDHT)(nil)
Matt Joiner's avatar
Matt Joiner committed
116 117 118 119 120
	_ routing.PeerRouting    = (*IpfsDHT)(nil)
	_ routing.PubKeyFetcher  = (*IpfsDHT)(nil)
	_ routing.ValueStore     = (*IpfsDHT)(nil)
)

121
// New creates a new DHT with the specified host and options.
122 123
func New(ctx context.Context, h host.Host, options ...Option) (*IpfsDHT, error) {
	var cfg config
Adin Schmahmann's avatar
Adin Schmahmann committed
124
	if err := cfg.apply(append([]Option{defaults}, options...)...); err != nil {
125 126
		return nil, err
	}
Adin Schmahmann's avatar
Adin Schmahmann committed
127 128 129 130 131
	if err := cfg.applyFallbacks(); err != nil {
		return nil, err
	}
	if err := cfg.validate(); err != nil {
		return nil, err
132
	}
Aarsh Shah's avatar
Aarsh Shah committed
133 134 135 136
	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
137

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

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

146
	dht.Validator = cfg.validator
147

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

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

	// 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
177
	dht.startSelfLookup()
178
	dht.startRefreshing()
179 180
	return dht, nil
}
181

182 183 184 185
// 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 {
186
	dht, err := New(ctx, h, Datastore(dstore))
187 188 189 190 191 192 193 194 195 196 197
	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
198
	dht, err := New(ctx, h, Datastore(dstore), Mode(ModeClient))
199 200 201
	if err != nil {
		panic(err)
	}
202 203 204
	return dht
}

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

Adin Schmahmann's avatar
Adin Schmahmann committed
207 208 209 210 211 212 213 214 215 216 217 218 219
	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
		}
	}

220
	dht := &IpfsDHT{
Aarsh Shah's avatar
Aarsh Shah committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234
		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,
		d:                 cfg.disjointPaths,
		triggerRtRefresh:  make(chan chan<- error),
		triggerSelfLookup: make(chan chan<- error),
Jeromy's avatar
Jeromy committed
235
	}
236

Aarsh Shah's avatar
Aarsh Shah committed
237 238 239 240 241 242 243
	// 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

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

	// 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)

252
	dht.ProviderManager = providers.NewProviderManager(dht.ctx, h.ID(), cfg.datastore)
253

Aarsh Shah's avatar
Aarsh Shah committed
254
	return dht, nil
Jeromy's avatar
Jeromy committed
255 256
}

Aarsh Shah's avatar
Aarsh Shah committed
257 258
func makeRoutingTable(dht *IpfsDHT, cfg config) (*kb.RoutingTable, error) {
	self := kb.ConvertPeerID(dht.host.ID())
Aarsh Shah's avatar
Aarsh Shah committed
259 260
	// 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
261 262
		// connect should work
		if err := dht.host.Connect(c, peer.AddrInfo{ID: p}); err != nil {
Aarsh Shah's avatar
Aarsh Shah committed
263
			rtPvLogger.Infof("failed to connect to peer %s for validation, err=%s", p, err)
Aarsh Shah's avatar
Aarsh Shah committed
264
			return false
265
		}
Aarsh Shah's avatar
Aarsh Shah committed
266 267 268 269 270 271 272 273

		// 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)
		}

		return b
274 275
	}

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

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

	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
}
295

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
311
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
312 313
}

314 315
var errInvalidRecord = errors.New("received invalid record")

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

326 327 328
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

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

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

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

Matt Joiner's avatar
Matt Joiner committed
349
	logger.Warning("getValueOrPeers: routing.ErrNotFound")
350
	return nil, nil, routing.ErrNotFound
351 352
}

353
// getValueSingle simply performs the get value RPC with the given parameters
354 355 356 357 358 359
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
360
	eip := logger.EventBegin(ctx, "getValueSingle", meta)
ForrestWeston's avatar
ForrestWeston committed
361
	defer eip.Done()
362

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

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

386
	// Double check the key. Can't hurt.
387
	if rec != nil && string(rec.GetKey()) != key {
Matt Joiner's avatar
Matt Joiner committed
388
		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
389
		return nil, nil
390 391

	}
392
	return rec, nil
393 394
}

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

404
	return dht.datastore.Put(mkDsKey(key), data)
405
}
406

Aarsh Shah's avatar
Aarsh Shah committed
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
// 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)

427
}
Jeromy's avatar
Jeromy committed
428

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

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

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

Adin Schmahmann's avatar
Adin Schmahmann committed
462 463
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
464
	defer eip.Done()
465

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

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

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

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

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

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

Jeromy's avatar
Jeromy committed
509
		filtered = append(filtered, clp)
510 511
	}

512 513
	// ok seems like closer nodes
	return filtered
514 515
}

516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
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
534 535 536
// 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.
537 538
func (dht *IpfsDHT) moveToServerMode() error {
	dht.mode = modeServer
Adin Schmahmann's avatar
Adin Schmahmann committed
539
	for _, p := range dht.serverProtocols {
540 541 542 543 544
		dht.host.SetStreamHandler(p, dht.handleNewStream)
	}
	return nil
}

Adin Schmahmann's avatar
Adin Schmahmann committed
545 546 547 548 549
// 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.
550 551
func (dht *IpfsDHT) moveToClientMode() error {
	dht.mode = modeClient
Adin Schmahmann's avatar
Adin Schmahmann committed
552
	for _, p := range dht.serverProtocols {
553 554 555 556
		dht.host.RemoveStreamHandler(p)
	}

	pset := make(map[protocol.ID]bool)
Adin Schmahmann's avatar
Adin Schmahmann committed
557
	for _, p := range dht.serverProtocols {
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
		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
}

579 580 581 582 583 584 585 586 587 588
// 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
589 590 591 592 593
// RoutingTable return dht's routingTable
func (dht *IpfsDHT) RoutingTable() *kb.RoutingTable {
	return dht.routingTable
}

594 595 596 597
// Close calls Process Close
func (dht *IpfsDHT) Close() error {
	return dht.proc.Close()
}
598 599 600 601

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

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
619
		return fmt.Errorf("sending request: %w", err)
620 621
	}
	if resp.Type != pb.Message_PING {
Steven Allen's avatar
Steven Allen committed
622
		return fmt.Errorf("got unexpected response type: %v", resp.Type)
623 624 625
	}
	return nil
}
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641

// 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
}