dht.go 12.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"
8 9
	"sync"
	"time"
10

11
	"go.opencensus.io/tag"
12 13
	"golang.org/x/xerrors"

14
	"github.com/libp2p/go-libp2p-kad-dht/metrics"
15 16 17
	opts "github.com/libp2p/go-libp2p-kad-dht/opts"
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
	providers "github.com/libp2p/go-libp2p-kad-dht/providers"
18

19
	proto "github.com/gogo/protobuf/proto"
20
	cid "github.com/ipfs/go-cid"
21 22 23 24
	ds "github.com/ipfs/go-datastore"
	logging "github.com/ipfs/go-log"
	goprocess "github.com/jbenet/goprocess"
	goprocessctx "github.com/jbenet/goprocess/context"
25
	host "github.com/libp2p/go-libp2p-host"
George Antoniadis's avatar
George Antoniadis committed
26
	kb "github.com/libp2p/go-libp2p-kbucket"
27
	inet "github.com/libp2p/go-libp2p-net"
28 29 30
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
	protocol "github.com/libp2p/go-libp2p-protocol"
George Antoniadis's avatar
George Antoniadis 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"
33
	routing "github.com/libp2p/go-libp2p-routing"
34
	base32 "github.com/whyrusleeping/base32"
35 36
)

Matt Joiner's avatar
Matt Joiner committed
37
var logger = logging.Logger("dht")
38

39 40 41 42
// NumBootstrapQueries defines the number of random dht queries to do to
// collect members of the routing table.
const NumBootstrapQueries = 5

43
// IpfsDHT is an implementation of Kademlia with S/Kademlia modifications.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44 45
// It is used to implement the base IpfsRouting module.
type IpfsDHT struct {
Jeromy's avatar
Jeromy committed
46 47 48
	host      host.Host        // the network services we need
	self      peer.ID          // Local peer (yourself)
	peerstore pstore.Peerstore // Peer Registry
49

50
	datastore ds.Datastore // Local data
51

52
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
53
	providers    *providers.ProviderManager
54

Jeromy's avatar
Jeromy committed
55
	birth time.Time // When this peer started up
56

57
	Validator record.Validator
58

59 60
	ctx  context.Context
	proc goprocess.Process
61 62 63

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

Steven Allen's avatar
Steven Allen committed
65
	plk sync.Mutex
66 67

	protocols []protocol.ID // DHT protocols
68 69
}

Matt Joiner's avatar
Matt Joiner committed
70 71 72 73 74 75 76 77 78 79
// 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)
	_ routing.IpfsRouting    = (*IpfsDHT)(nil)
	_ routing.PeerRouting    = (*IpfsDHT)(nil)
	_ routing.PubKeyFetcher  = (*IpfsDHT)(nil)
	_ routing.ValueStore     = (*IpfsDHT)(nil)
)

80 81 82 83 84 85
// New creates a new DHT with the specified host and options.
func New(ctx context.Context, h host.Host, options ...opts.Option) (*IpfsDHT, error) {
	var cfg opts.Options
	if err := cfg.Apply(append([]opts.Option{opts.Defaults}, options...)...); err != nil {
		return nil, err
	}
86
	dht := makeDHT(ctx, h, cfg.Datastore, cfg.Protocols)
87 88 89 90 91 92 93 94 95 96 97

	// register for network notifs.
	dht.host.Network().Notify((*netNotifiee)(dht))

	dht.proc = goprocessctx.WithContextAndTeardown(ctx, func() error {
		// remove ourselves from network notifs.
		dht.host.Network().StopNotify((*netNotifiee)(dht))
		return nil
	})

	dht.proc.AddChild(dht.providers.Process())
98 99 100
	dht.Validator = cfg.Validator

	if !cfg.Client {
101 102 103
		for _, p := range cfg.Protocols {
			h.SetStreamHandler(p, dht.handleNewStream)
		}
104 105 106
	}
	return dht, nil
}
107

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
// 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 {
	dht, err := New(ctx, h, opts.Datastore(dstore))
	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 {
	dht, err := New(ctx, h, opts.Datastore(dstore), opts.Client(true))
	if err != nil {
		panic(err)
	}
128 129 130
	return dht
}

131
func makeDHT(ctx context.Context, h host.Host, dstore ds.Batching, protocols []protocol.ID) *IpfsDHT {
132 133 134 135 136 137 138 139 140 141
	rt := kb.NewRoutingTable(KValue, kb.ConvertPeerID(h.ID()), time.Minute, h.Peerstore())

	cmgr := h.ConnManager()
	rt.PeerAdded = func(p peer.ID) {
		cmgr.TagPeer(p, "kbucket", 5)
	}
	rt.PeerRemoved = func(p peer.ID) {
		cmgr.UntagPeer(p, "kbucket")
	}

142
	dht := &IpfsDHT{
Jeromy's avatar
Jeromy committed
143 144 145 146 147 148 149 150
		datastore:    dstore,
		self:         h.ID(),
		peerstore:    h.Peerstore(),
		host:         h,
		strmap:       make(map[peer.ID]*messageSender),
		ctx:          ctx,
		providers:    providers.NewProviderManager(ctx, h.ID(), dstore),
		birth:        time.Now(),
151
		routingTable: rt,
152
		protocols:    protocols,
Jeromy's avatar
Jeromy committed
153
	}
154 155 156 157

	dht.ctx = dht.newContextWithLocalTags(ctx)

	return dht
Jeromy's avatar
Jeromy committed
158 159
}

Jeromy's avatar
Jeromy committed
160
// putValueToPeer stores the given key/value pair at the peer 'p'
161
func (dht *IpfsDHT) putValueToPeer(ctx context.Context, p peer.ID, rec *recpb.Record) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162

163
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, rec.Key, 0)
164
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
167
		logger.Debugf("putValueToPeer: %v. (peer: %s, key: %s)", err, p.Pretty(), loggableKey(string(rec.Key)))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168 169
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177 178
}

179 180
var errInvalidRecord = errors.New("received invalid record")

181 182
// getValueOrPeers queries a particular peer p for the value for
// key. It returns either the value or a list of closer peers.
183
// NOTE: It will update the dht's peerstore with any new addresses
184
// it finds for the given peer.
Jeromy's avatar
Jeromy committed
185
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.ID, key string) (*recpb.Record, []*pstore.PeerInfo, error) {
186

187
	pmes, err := dht.getValueSingle(ctx, p, key)
188
	if err != nil {
189
		return nil, nil, err
190 191
	}

192 193 194
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

195
	if record := pmes.GetRecord(); record != nil {
196
		// Success! We were given the value
Matt Joiner's avatar
Matt Joiner committed
197
		logger.Debug("getValueOrPeers: got value")
198

199
		// make sure record is valid.
200
		err = dht.Validator.Validate(string(record.GetKey()), record.GetValue())
201
		if err != nil {
Matt Joiner's avatar
Matt Joiner committed
202
			logger.Info("Received invalid record! (discarded)")
203 204
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
George Antoniadis's avatar
George Antoniadis committed
205
			record = new(recpb.Record)
206
		}
207
		return record, peers, err
208
	}
209

210
	if len(peers) > 0 {
Matt Joiner's avatar
Matt Joiner committed
211
		logger.Debug("getValueOrPeers: peers")
212 213 214
		return nil, peers, nil
	}

Matt Joiner's avatar
Matt Joiner committed
215
	logger.Warning("getValueOrPeers: routing.ErrNotFound")
216
	return nil, nil, routing.ErrNotFound
217 218
}

219
// getValueSingle simply performs the get value RPC with the given parameters
220 221 222 223 224 225
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
226
	eip := logger.EventBegin(ctx, "getValueSingle", meta)
ForrestWeston's avatar
ForrestWeston committed
227
	defer eip.Done()
228

229
	pmes := pb.NewMessage(pb.Message_GET_VALUE, []byte(key), 0)
230 231 232 233 234
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Matt Joiner's avatar
Matt Joiner committed
235
		logger.Warningf("getValueSingle: read timeout %s %s", p.Pretty(), key)
236 237
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
238
		eip.SetError(err)
239 240
		return nil, err
	}
Jeromy's avatar
Jeromy committed
241 242
}

243
// getLocal attempts to retrieve the value from the datastore
244
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
Matt Joiner's avatar
Matt Joiner committed
245
	logger.Debugf("getLocal %s", key)
246
	rec, err := dht.getRecordFromDatastore(mkDsKey(key))
247
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
248
		logger.Warningf("getLocal: %s", err)
249 250
		return nil, err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251

252
	// Double check the key. Can't hurt.
253
	if rec != nil && string(rec.GetKey()) != key {
Matt Joiner's avatar
Matt Joiner committed
254
		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
255
		return nil, nil
256 257

	}
258
	return rec, nil
259 260
}

261
// putLocal stores the key value pair in the datastore
262
func (dht *IpfsDHT) putLocal(key string, rec *recpb.Record) error {
Matt Joiner's avatar
Matt Joiner committed
263
	logger.Debugf("putLocal: %v %v", key, rec)
264 265
	data, err := proto.Marshal(rec)
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
266
		logger.Warningf("putLocal: %s", err)
267 268 269
		return err
	}

270
	return dht.datastore.Put(mkDsKey(key), data)
271
}
272

273
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
274
// on the given peer.
275
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
Matt Joiner's avatar
Matt Joiner committed
276
	logger.Event(ctx, "updatePeer", p)
277
	dht.routingTable.Update(p)
278
}
Jeromy's avatar
Jeromy committed
279

Jeromy's avatar
Jeromy committed
280
// FindLocal looks for a peer with a given ID connected to this dht and returns the peer and the table it was found in.
Jeromy's avatar
Jeromy committed
281
func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
282 283 284 285 286
	switch dht.host.Network().Connectedness(id) {
	case inet.Connected, inet.CanConnect:
		return dht.peerstore.PeerInfo(id)
	default:
		return pstore.PeerInfo{}
Jeromy's avatar
Jeromy committed
287 288
	}
}
289

Jeromy's avatar
Jeromy committed
290
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
291
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
Matt Joiner's avatar
Matt Joiner committed
292
	eip := logger.EventBegin(ctx, "findPeerSingle",
293 294 295 296
		logging.LoggableMap{
			"peer":   p,
			"target": id,
		})
ForrestWeston's avatar
ForrestWeston committed
297
	defer eip.Done()
298

299
	pmes := pb.NewMessage(pb.Message_FIND_NODE, []byte(id), 0)
300 301 302 303 304
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Matt Joiner's avatar
Matt Joiner committed
305
		logger.Warningf("read timeout: %s %s", p.Pretty(), id)
306 307
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
308
		eip.SetError(err)
309 310
		return nil, err
	}
311
}
312

313
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.ID, key cid.Cid) (*pb.Message, error) {
Matt Joiner's avatar
Matt Joiner committed
314
	eip := logger.EventBegin(ctx, "findProvidersSingle", p, key)
ForrestWeston's avatar
ForrestWeston committed
315
	defer eip.Done()
316

317
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, key.Bytes(), 0)
318 319 320 321 322
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Matt Joiner's avatar
Matt Joiner committed
323
		logger.Warningf("read timeout: %s %s", p.Pretty(), key)
324 325
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
326
		eip.SetError(err)
327 328
		return nil, err
	}
Jeromy's avatar
Jeromy committed
329 330
}

331
// nearestPeersToQuery returns the routing tables closest peers.
332
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
333
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(string(pmes.GetKey())), count)
334 335 336
	return closer
}

337
// betterPeersToQuery returns nearestPeersToQuery, but if and only if closer than self.
338
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
339
	closer := dht.nearestPeersToQuery(pmes, count)
340 341 342

	// no node? nil
	if closer == nil {
Matt Joiner's avatar
Matt Joiner committed
343
		logger.Warning("betterPeersToQuery: no closer peers to send:", p)
344 345 346
		return nil
	}

Steven Allen's avatar
Steven Allen committed
347
	filtered := make([]peer.ID, 0, len(closer))
Jeromy's avatar
Jeromy committed
348 349 350
	for _, clp := range closer {

		// == to self? thats bad
Jeromy's avatar
Jeromy committed
351
		if clp == dht.self {
Matt Joiner's avatar
Matt Joiner committed
352
			logger.Error("BUG betterPeersToQuery: attempted to return self! this shouldn't happen...")
353 354
			return nil
		}
355
		// Dont send a peer back themselves
Jeromy's avatar
Jeromy committed
356
		if clp == p {
357 358 359
			continue
		}

Jeromy's avatar
Jeromy committed
360
		filtered = append(filtered, clp)
361 362
	}

363 364
	// ok seems like closer nodes
	return filtered
365 366
}

367 368 369 370 371 372 373 374 375 376
// 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
377 378 379 380 381
// RoutingTable return dht's routingTable
func (dht *IpfsDHT) RoutingTable() *kb.RoutingTable {
	return dht.routingTable
}

382 383 384 385
// Close calls Process Close
func (dht *IpfsDHT) Close() error {
	return dht.proc.Close()
}
386

387 388
func (dht *IpfsDHT) protocolStrs() []string {
	pstrs := make([]string, len(dht.protocols))
389 390
	for idx, proto := range dht.protocols {
		pstrs[idx] = string(proto)
391 392 393 394 395
	}

	return pstrs
}

396 397 398
func mkDsKey(s string) ds.Key {
	return ds.NewKey(base32.RawStdEncoding.EncodeToString([]byte(s)))
}
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422

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 {
		return xerrors.Errorf("sending request: %w", err)
	}
	if resp.Type != pb.Message_PING {
		return xerrors.Errorf("got unexpected response type: %v", resp.Type)
	}
	return nil
}
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438

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