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

11 12 13 14 15 16 17
	"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"

18
	"go.opencensus.io/tag"
19 20
	"golang.org/x/xerrors"

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

Aarsh Shah's avatar
Aarsh Shah committed
26 27
	"github.com/gogo/protobuf/proto"
	"github.com/ipfs/go-cid"
28 29
	ds "github.com/ipfs/go-datastore"
	logging "github.com/ipfs/go-log"
Aarsh Shah's avatar
Aarsh Shah committed
30 31
	"github.com/jbenet/goprocess"
	"github.com/jbenet/goprocess/context"
George Antoniadis's avatar
George Antoniadis committed
32
	kb "github.com/libp2p/go-libp2p-kbucket"
Aarsh Shah's avatar
Aarsh Shah committed
33
	"github.com/libp2p/go-libp2p-record"
George Antoniadis's avatar
George Antoniadis committed
34
	recpb "github.com/libp2p/go-libp2p-record/pb"
Aarsh Shah's avatar
Aarsh Shah committed
35
	"github.com/whyrusleeping/base32"
36 37
)

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

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

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

51
	datastore ds.Datastore // Local data
52

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

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

58
	Validator record.Validator
59

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

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

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

68 69
	stripedPutLocks [256]sync.Mutex

70
	protocols []protocol.ID // DHT protocols
71 72

	bucketSize int
73 74
}

Matt Joiner's avatar
Matt Joiner committed
75 76 77 78
// 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)
79
	_ routing.Routing        = (*IpfsDHT)(nil)
Matt Joiner's avatar
Matt Joiner committed
80 81 82 83 84
	_ routing.PeerRouting    = (*IpfsDHT)(nil)
	_ routing.PubKeyFetcher  = (*IpfsDHT)(nil)
	_ routing.ValueStore     = (*IpfsDHT)(nil)
)

85 86 87
// 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
88
	cfg.BucketSize = KValue
89 90 91
	if err := cfg.Apply(append([]opts.Option{opts.Defaults}, options...)...); err != nil {
		return nil, err
	}
92
	dht := makeDHT(ctx, h, cfg.Datastore, cfg.Protocols, cfg.BucketSize)
93 94 95 96 97 98 99 100 101 102 103

	// 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())
104 105 106
	dht.Validator = cfg.Validator

	if !cfg.Client {
107 108 109
		for _, p := range cfg.Protocols {
			h.SetStreamHandler(p, dht.handleNewStream)
		}
110 111 112
	}
	return dht, nil
}
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
// 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)
	}
134 135 136
	return dht
}

137 138
func makeDHT(ctx context.Context, h host.Host, dstore ds.Batching, protocols []protocol.ID, bucketSize int) *IpfsDHT {
	rt := kb.NewRoutingTable(bucketSize, kb.ConvertPeerID(h.ID()), time.Minute, h.Peerstore())
139 140 141 142 143 144 145 146 147

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

148
	dht := &IpfsDHT{
Jeromy's avatar
Jeromy committed
149 150 151 152 153 154 155 156
		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(),
157
		routingTable: rt,
158
		protocols:    protocols,
159
		bucketSize:   bucketSize,
Jeromy's avatar
Jeromy committed
160
	}
161 162 163 164

	dht.ctx = dht.newContextWithLocalTags(ctx)

	return dht
Jeromy's avatar
Jeromy committed
165 166
}

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

170
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, rec.Key, 0)
171
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
174
		logger.Debugf("putValueToPeer: %v. (peer: %s, key: %s)", err, p.Pretty(), loggableKey(string(rec.Key)))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175 176
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
184 185
}

186 187
var errInvalidRecord = errors.New("received invalid record")

188 189
// getValueOrPeers queries a particular peer p for the value for
// key. It returns either the value or a list of closer peers.
190
// NOTE: It will update the dht's peerstore with any new addresses
191
// it finds for the given peer.
192
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.ID, key string) (*recpb.Record, []*peer.AddrInfo, error) {
193

194
	pmes, err := dht.getValueSingle(ctx, p, key)
195
	if err != nil {
196
		return nil, nil, err
197 198
	}

199 200 201
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

202
	if record := pmes.GetRecord(); record != nil {
203
		// Success! We were given the value
Matt Joiner's avatar
Matt Joiner committed
204
		logger.Debug("getValueOrPeers: got value")
205

206
		// make sure record is valid.
207
		err = dht.Validator.Validate(string(record.GetKey()), record.GetValue())
208
		if err != nil {
Matt Joiner's avatar
Matt Joiner committed
209
			logger.Info("Received invalid record! (discarded)")
210 211
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
George Antoniadis's avatar
George Antoniadis committed
212
			record = new(recpb.Record)
213
		}
214
		return record, peers, err
215
	}
216

217
	if len(peers) > 0 {
Matt Joiner's avatar
Matt Joiner committed
218
		logger.Debug("getValueOrPeers: peers")
219 220 221
		return nil, peers, nil
	}

Matt Joiner's avatar
Matt Joiner committed
222
	logger.Warning("getValueOrPeers: routing.ErrNotFound")
223
	return nil, nil, routing.ErrNotFound
224 225
}

226
// getValueSingle simply performs the get value RPC with the given parameters
227 228 229 230 231 232
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
233
	eip := logger.EventBegin(ctx, "getValueSingle", meta)
ForrestWeston's avatar
ForrestWeston committed
234
	defer eip.Done()
235

236
	pmes := pb.NewMessage(pb.Message_GET_VALUE, []byte(key), 0)
237 238 239 240 241
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Matt Joiner's avatar
Matt Joiner committed
242
		logger.Warningf("getValueSingle: read timeout %s %s", p.Pretty(), key)
243 244
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
245
		eip.SetError(err)
246 247
		return nil, err
	}
Jeromy's avatar
Jeromy committed
248 249
}

250
// getLocal attempts to retrieve the value from the datastore
251
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
Matt Joiner's avatar
Matt Joiner committed
252
	logger.Debugf("getLocal %s", key)
253
	rec, err := dht.getRecordFromDatastore(mkDsKey(key))
254
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
255
		logger.Warningf("getLocal: %s", err)
256 257
		return nil, err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
258

259
	// Double check the key. Can't hurt.
260
	if rec != nil && string(rec.GetKey()) != key {
Matt Joiner's avatar
Matt Joiner committed
261
		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
262
		return nil, nil
263 264

	}
265
	return rec, nil
266 267
}

268
// putLocal stores the key value pair in the datastore
269
func (dht *IpfsDHT) putLocal(key string, rec *recpb.Record) error {
Matt Joiner's avatar
Matt Joiner committed
270
	logger.Debugf("putLocal: %v %v", key, rec)
271 272
	data, err := proto.Marshal(rec)
	if err != nil {
Matt Joiner's avatar
Matt Joiner committed
273
		logger.Warningf("putLocal: %s", err)
274 275 276
		return err
	}

277
	return dht.datastore.Put(mkDsKey(key), data)
278
}
279

280
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
281
// on the given peer.
282
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
Matt Joiner's avatar
Matt Joiner committed
283
	logger.Event(ctx, "updatePeer", p)
284
	dht.routingTable.Update(p)
285
}
Jeromy's avatar
Jeromy committed
286

Jeromy's avatar
Jeromy committed
287
// FindLocal looks for a peer with a given ID connected to this dht and returns the peer and the table it was found in.
288
func (dht *IpfsDHT) FindLocal(id peer.ID) peer.AddrInfo {
289
	switch dht.host.Network().Connectedness(id) {
290
	case network.Connected, network.CanConnect:
291 292
		return dht.peerstore.PeerInfo(id)
	default:
293
		return peer.AddrInfo{}
Jeromy's avatar
Jeromy committed
294 295
	}
}
296

Jeromy's avatar
Jeromy committed
297
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
298
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
Matt Joiner's avatar
Matt Joiner committed
299
	eip := logger.EventBegin(ctx, "findPeerSingle",
300 301 302 303
		logging.LoggableMap{
			"peer":   p,
			"target": id,
		})
ForrestWeston's avatar
ForrestWeston committed
304
	defer eip.Done()
305

306
	pmes := pb.NewMessage(pb.Message_FIND_NODE, []byte(id), 0)
307 308 309 310 311
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Matt Joiner's avatar
Matt Joiner committed
312
		logger.Warningf("read timeout: %s %s", p.Pretty(), id)
313 314
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
315
		eip.SetError(err)
316 317
		return nil, err
	}
318
}
319

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

324
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, key.Bytes(), 0)
325 326 327 328 329
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Matt Joiner's avatar
Matt Joiner committed
330
		logger.Warningf("read timeout: %s %s", p.Pretty(), key)
331 332
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
333
		eip.SetError(err)
334 335
		return nil, err
	}
Jeromy's avatar
Jeromy committed
336 337
}

338
// nearestPeersToQuery returns the routing tables closest peers.
339
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
340
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(string(pmes.GetKey())), count)
341 342 343
	return closer
}

344
// betterPeersToQuery returns nearestPeersToQuery, but if and only if closer than self.
345
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
346
	closer := dht.nearestPeersToQuery(pmes, count)
347 348 349

	// no node? nil
	if closer == nil {
Matt Joiner's avatar
Matt Joiner committed
350
		logger.Warning("betterPeersToQuery: no closer peers to send:", p)
351 352 353
		return nil
	}

Steven Allen's avatar
Steven Allen committed
354
	filtered := make([]peer.ID, 0, len(closer))
Jeromy's avatar
Jeromy committed
355 356 357
	for _, clp := range closer {

		// == to self? thats bad
Jeromy's avatar
Jeromy committed
358
		if clp == dht.self {
Matt Joiner's avatar
Matt Joiner committed
359
			logger.Error("BUG betterPeersToQuery: attempted to return self! this shouldn't happen...")
360 361
			return nil
		}
362
		// Dont send a peer back themselves
Jeromy's avatar
Jeromy committed
363
		if clp == p {
364 365 366
			continue
		}

Jeromy's avatar
Jeromy committed
367
		filtered = append(filtered, clp)
368 369
	}

370 371
	// ok seems like closer nodes
	return filtered
372 373
}

374 375 376 377 378 379 380 381 382 383
// 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
384 385 386 387 388
// RoutingTable return dht's routingTable
func (dht *IpfsDHT) RoutingTable() *kb.RoutingTable {
	return dht.routingTable
}

389 390 391 392
// Close calls Process Close
func (dht *IpfsDHT) Close() error {
	return dht.proc.Close()
}
393

394 395
func (dht *IpfsDHT) protocolStrs() []string {
	pstrs := make([]string, len(dht.protocols))
396 397
	for idx, proto := range dht.protocols {
		pstrs[idx] = string(proto)
398 399 400 401 402
	}

	return pstrs
}

403 404 405
func mkDsKey(s string) ds.Key {
	return ds.NewKey(base32.RawStdEncoding.EncodeToString([]byte(s)))
}
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

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
}
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445

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