dht.go 18 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

70
	Validator record.Validator
71

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

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

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

80 81
	stripedPutLocks [256]sync.Mutex

Adin Schmahmann's avatar
Adin Schmahmann committed
82 83 84 85 86
	// 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
87

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

92
	bucketSize int
93
	alpha      int // The concurrency parameter per path
Adin Schmahmann's avatar
Adin Schmahmann committed
94
	d          int // Number of Disjoint Paths to query
95

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

	maxRecordAge time.Duration
103

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

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

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

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

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

145
	dht.Validator = cfg.validator
146

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

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

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

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

Aarsh Shah's avatar
Aarsh Shah committed
204 205 206 207
func makeDHT(ctx context.Context, h host.Host, cfg config) (*IpfsDHT, error) {
	rt, err := makeRoutingTable(h, cfg)
	if err != nil {
		return nil, fmt.Errorf("failed to construct routing table,err=%s", err)
208 209
	}

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

223
	dht := &IpfsDHT{
Aarsh Shah's avatar
Aarsh Shah committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
		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())),
		routingTable:      rt,
		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
239
	}
240

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

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

249
	dht.ProviderManager = providers.NewProviderManager(dht.ctx, h.ID(), cfg.datastore)
250

Aarsh Shah's avatar
Aarsh Shah committed
251
	return dht, nil
Jeromy's avatar
Jeromy committed
252 253
}

Aarsh Shah's avatar
Aarsh Shah committed
254 255 256 257 258
func makeRoutingTable(h host.Host, cfg config) (*kb.RoutingTable, error) {
	self := kb.ConvertPeerID(h.ID())
	// construct the routing table with a peer validation function
	pvF := func(c context.Context, p peer.ID) bool {
		if err := h.Connect(c, peer.AddrInfo{ID: p}); err != nil {
Aarsh Shah's avatar
Aarsh Shah committed
259
			rtPvLogger.Infof("failed to connect to peer %s for validation, err=%s", p, err)
Aarsh Shah's avatar
Aarsh Shah committed
260
			return false
261
		}
Aarsh Shah's avatar
Aarsh Shah committed
262
		return true
263 264
	}

Aarsh Shah's avatar
Aarsh Shah committed
265 266 267
	rtOpts := []kb.Option{kb.PeerValidationFnc(pvF)}
	if !(cfg.routingTable.checkInterval == 0) {
		rtOpts = append(rtOpts, kb.TableCleanupInterval(cfg.routingTable.checkInterval))
268
	}
Aarsh Shah's avatar
Aarsh Shah committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

	rt, err := kb.NewRoutingTable(cfg.bucketSize, self, time.Minute, h.Peerstore(),
		rtOpts...)
	cmgr := h.ConnManager()

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

Jeromy's avatar
Jeromy committed
285
// putValueToPeer stores the given key/value pair at the peer 'p'
286 287
func (dht *IpfsDHT) putValueToPeer(ctx context.Context, p peer.ID, rec *recpb.Record) error {
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, rec.Key, 0)
288
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
289
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
290
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
291
		logger.Debugf("putValueToPeer: %v. (peer: %s, key: %s)", err, p.Pretty(), loggableKey(string(rec.Key)))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
292 293
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
300
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
301 302
}

303 304
var errInvalidRecord = errors.New("received invalid record")

305 306
// getValueOrPeers queries a particular peer p for the value for
// key. It returns either the value or a list of closer peers.
307
// NOTE: It will update the dht's peerstore with any new addresses
308
// it finds for the given peer.
309
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.ID, key string) (*recpb.Record, []*peer.AddrInfo, error) {
310
	pmes, err := dht.getValueSingle(ctx, p, key)
311
	if err != nil {
312
		return nil, nil, err
313 314
	}

315 316 317
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

318
	if record := pmes.GetRecord(); record != nil {
319
		// Success! We were given the value
Matt Joiner's avatar
Matt Joiner committed
320
		logger.Debug("getValueOrPeers: got value")
321

322
		// make sure record is valid.
323
		err = dht.Validator.Validate(string(record.GetKey()), record.GetValue())
324
		if err != nil {
Matt Joiner's avatar
Matt Joiner committed
325
			logger.Info("Received invalid record! (discarded)")
326 327
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
George Antoniadis's avatar
George Antoniadis committed
328
			record = new(recpb.Record)
329
		}
330
		return record, peers, err
331
	}
332

333
	if len(peers) > 0 {
Matt Joiner's avatar
Matt Joiner committed
334
		logger.Debug("getValueOrPeers: peers")
335 336 337
		return nil, peers, nil
	}

Matt Joiner's avatar
Matt Joiner committed
338
	logger.Warning("getValueOrPeers: routing.ErrNotFound")
339
	return nil, nil, routing.ErrNotFound
340 341
}

342
// getValueSingle simply performs the get value RPC with the given parameters
343 344 345 346 347 348
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
349
	eip := logger.EventBegin(ctx, "getValueSingle", meta)
ForrestWeston's avatar
ForrestWeston committed
350
	defer eip.Done()
351

352
	pmes := pb.NewMessage(pb.Message_GET_VALUE, []byte(key), 0)
353 354 355 356 357
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Matt Joiner's avatar
Matt Joiner committed
358
		logger.Warningf("getValueSingle: read timeout %s %s", p.Pretty(), key)
359 360
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
361
		eip.SetError(err)
362 363
		return nil, err
	}
Jeromy's avatar
Jeromy committed
364 365
}

366
// getLocal attempts to retrieve the value from the datastore
367
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
Matt Joiner's avatar
Matt Joiner committed
368
	logger.Debugf("getLocal %s", key)
369
	rec, err := dht.getRecordFromDatastore(mkDsKey(key))
370
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
371
		logger.Warningf("getLocal: %s", err)
372 373
		return nil, err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
374

375
	// Double check the key. Can't hurt.
376
	if rec != nil && string(rec.GetKey()) != key {
Matt Joiner's avatar
Matt Joiner committed
377
		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
378
		return nil, nil
379 380

	}
381
	return rec, nil
382 383
}

384
// putLocal stores the key value pair in the datastore
385
func (dht *IpfsDHT) putLocal(key string, rec *recpb.Record) error {
Matt Joiner's avatar
Matt Joiner committed
386
	logger.Debugf("putLocal: %v %v", key, rec)
387 388
	data, err := proto.Marshal(rec)
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
389
		logger.Warningf("putLocal: %s", err)
390 391 392
		return err
	}

393
	return dht.datastore.Put(mkDsKey(key), data)
394
}
395

Aarsh Shah's avatar
Aarsh Shah committed
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
// 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)

416
}
Jeromy's avatar
Jeromy committed
417

Jeromy's avatar
Jeromy committed
418
// FindLocal looks for a peer with a given ID connected to this dht and returns the peer and the table it was found in.
419
func (dht *IpfsDHT) FindLocal(id peer.ID) peer.AddrInfo {
420
	switch dht.host.Network().Connectedness(id) {
421
	case network.Connected, network.CanConnect:
422 423
		return dht.peerstore.PeerInfo(id)
	default:
424
		return peer.AddrInfo{}
Jeromy's avatar
Jeromy committed
425 426
	}
}
427

Jeromy's avatar
Jeromy committed
428
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
429
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
Matt Joiner's avatar
Matt Joiner committed
430
	eip := logger.EventBegin(ctx, "findPeerSingle",
431 432 433 434
		logging.LoggableMap{
			"peer":   p,
			"target": id,
		})
ForrestWeston's avatar
ForrestWeston committed
435
	defer eip.Done()
436

437
	pmes := pb.NewMessage(pb.Message_FIND_NODE, []byte(id), 0)
438 439 440 441 442
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Matt Joiner's avatar
Matt Joiner committed
443
		logger.Warningf("read timeout: %s %s", p.Pretty(), id)
444 445
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
446
		eip.SetError(err)
447 448
		return nil, err
	}
449
}
450

Adin Schmahmann's avatar
Adin Schmahmann committed
451 452
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
453
	defer eip.Done()
454

Adin Schmahmann's avatar
Adin Schmahmann committed
455
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, key, 0)
456 457 458 459 460
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Adin Schmahmann's avatar
Adin Schmahmann committed
461
		logger.Warningf("read timeout: %s %s", p.Pretty(), key)
462 463
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
464
		eip.SetError(err)
465 466
		return nil, err
	}
Jeromy's avatar
Jeromy committed
467 468
}

469
// nearestPeersToQuery returns the routing tables closest peers.
470
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
471
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(string(pmes.GetKey())), count)
472 473 474
	return closer
}

Aarsh Shah's avatar
Aarsh Shah committed
475
// betterPeersToQuery returns nearestPeersToQuery with some additional filtering
476
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
477
	closer := dht.nearestPeersToQuery(pmes, count)
478 479 480

	// no node? nil
	if closer == nil {
Matt Joiner's avatar
Matt Joiner committed
481
		logger.Warning("betterPeersToQuery: no closer peers to send:", p)
482 483 484
		return nil
	}

Steven Allen's avatar
Steven Allen committed
485
	filtered := make([]peer.ID, 0, len(closer))
Jeromy's avatar
Jeromy committed
486 487 488
	for _, clp := range closer {

		// == to self? thats bad
Jeromy's avatar
Jeromy committed
489
		if clp == dht.self {
Matt Joiner's avatar
Matt Joiner committed
490
			logger.Error("BUG betterPeersToQuery: attempted to return self! this shouldn't happen...")
491 492
			return nil
		}
493
		// Dont send a peer back themselves
Jeromy's avatar
Jeromy committed
494
		if clp == p {
495 496 497
			continue
		}

Jeromy's avatar
Jeromy committed
498
		filtered = append(filtered, clp)
499 500
	}

501 502
	// ok seems like closer nodes
	return filtered
503 504
}

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
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
523 524 525
// 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.
526 527
func (dht *IpfsDHT) moveToServerMode() error {
	dht.mode = modeServer
Adin Schmahmann's avatar
Adin Schmahmann committed
528
	for _, p := range dht.serverProtocols {
529 530 531 532 533
		dht.host.SetStreamHandler(p, dht.handleNewStream)
	}
	return nil
}

Adin Schmahmann's avatar
Adin Schmahmann committed
534 535 536 537 538
// 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.
539 540
func (dht *IpfsDHT) moveToClientMode() error {
	dht.mode = modeClient
Adin Schmahmann's avatar
Adin Schmahmann committed
541
	for _, p := range dht.serverProtocols {
542 543 544 545
		dht.host.RemoveStreamHandler(p)
	}

	pset := make(map[protocol.ID]bool)
Adin Schmahmann's avatar
Adin Schmahmann committed
546
	for _, p := range dht.serverProtocols {
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
		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
}

568 569 570 571 572 573 574 575 576 577
// 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
578 579 580 581 582
// RoutingTable return dht's routingTable
func (dht *IpfsDHT) RoutingTable() *kb.RoutingTable {
	return dht.routingTable
}

583 584 585 586
// Close calls Process Close
func (dht *IpfsDHT) Close() error {
	return dht.proc.Close()
}
587 588 589 590

func mkDsKey(s string) ds.Key {
	return ds.NewKey(base32.RawStdEncoding.EncodeToString([]byte(s)))
}
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607

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
608
		return fmt.Errorf("sending request: %w", err)
609 610
	}
	if resp.Type != pb.Message_PING {
Steven Allen's avatar
Steven Allen committed
611
		return fmt.Errorf("got unexpected response type: %v", resp.Type)
612 613 614
	}
	return nil
}
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630

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