dht.go 11.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
	opts "github.com/libp2p/go-libp2p-kad-dht/opts"
12 13 14
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
	providers "github.com/libp2p/go-libp2p-kad-dht/providers"

15
	proto "github.com/gogo/protobuf/proto"
16
	cid "github.com/ipfs/go-cid"
17 18 19 20
	ds "github.com/ipfs/go-datastore"
	logging "github.com/ipfs/go-log"
	goprocess "github.com/jbenet/goprocess"
	goprocessctx "github.com/jbenet/goprocess/context"
21 22
	ci "github.com/libp2p/go-libp2p-crypto"
	host "github.com/libp2p/go-libp2p-host"
George Antoniadis's avatar
George Antoniadis committed
23
	kb "github.com/libp2p/go-libp2p-kbucket"
24
	inet "github.com/libp2p/go-libp2p-net"
25 26 27
	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
28
	record "github.com/libp2p/go-libp2p-record"
George Antoniadis's avatar
George Antoniadis committed
29
	recpb "github.com/libp2p/go-libp2p-record/pb"
30
	routing "github.com/libp2p/go-libp2p-routing"
31
	base32 "github.com/whyrusleeping/base32"
32 33
)

Jeromy's avatar
Jeromy committed
34
var log = logging.Logger("dht")
35

36 37 38 39
// NumBootstrapQueries defines the number of random dht queries to do to
// collect members of the routing table.
const NumBootstrapQueries = 5

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

47
	datastore ds.Datastore // Local data
48

49
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
50
	providers    *providers.ProviderManager
51

Jeromy's avatar
Jeromy committed
52
	birth time.Time // When this peer started up
53

54
	Validator record.Validator
55

56 57
	ctx  context.Context
	proc goprocess.Process
58 59 60

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

Steven Allen's avatar
Steven Allen committed
62
	plk sync.Mutex
63 64

	protocols []protocol.ID // DHT protocols
65 66
}

Matt Joiner's avatar
Matt Joiner committed
67 68 69 70 71 72 73 74 75 76
// 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)
)

77 78 79 80 81 82
// 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
	}
83
	dht := makeDHT(ctx, h, cfg.Datastore, cfg.Protocols)
84 85 86 87 88 89 90 91 92 93 94

	// 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())
95 96 97
	dht.Validator = cfg.Validator

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

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
// 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)
	}
125 126 127
	return dht
}

128
func makeDHT(ctx context.Context, h host.Host, dstore ds.Batching, protocols []protocol.ID) *IpfsDHT {
129 130 131 132 133 134 135 136 137 138
	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")
	}

Jeromy's avatar
Jeromy committed
139 140 141 142 143 144 145 146 147
	return &IpfsDHT{
		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(),
148
		routingTable: rt,
149
		protocols:    protocols,
Jeromy's avatar
Jeromy committed
150 151 152
	}
}

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

156
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, rec.Key, 0)
157
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159
	if err != nil {
160
		log.Debugf("putValueToPeer: %v. (peer: %s, key: %s)", err, p.Pretty(), loggableKey(string(rec.Key)))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161 162
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163

164
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
gpestana's avatar
gpestana committed
165
		log.Warningf("putValueToPeer: value not put correctly. (%v != %v)", pmes, rpmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166 167
		return errors.New("value not put correctly")
	}
gpestana's avatar
gpestana committed
168

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170 171
}

172 173
var errInvalidRecord = errors.New("received invalid record")

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

180
	pmes, err := dht.getValueSingle(ctx, p, key)
181
	if err != nil {
182
		return nil, nil, err
183 184
	}

185 186 187
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

188
	if record := pmes.GetRecord(); record != nil {
189
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
190
		log.Debug("getValueOrPeers: got value")
191

192
		// make sure record is valid.
193
		err = dht.Validator.Validate(string(record.GetKey()), record.GetValue())
194
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
195
			log.Info("Received invalid record! (discarded)")
196 197
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
George Antoniadis's avatar
George Antoniadis committed
198
			record = new(recpb.Record)
199
		}
200
		return record, peers, err
201
	}
202

203
	if len(peers) > 0 {
204
		log.Debug("getValueOrPeers: peers")
205 206 207
		return nil, peers, nil
	}

208 209
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
210 211
}

212
// getValueSingle simply performs the get value RPC with the given parameters
213 214 215 216 217 218
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID, key string) (*pb.Message, error) {
	meta := logging.LoggableMap{
		"key":  key,
		"peer": p,
	}

ForrestWeston's avatar
ForrestWeston committed
219 220
	eip := log.EventBegin(ctx, "getValueSingle", meta)
	defer eip.Done()
221

222
	pmes := pb.NewMessage(pb.Message_GET_VALUE, []byte(key), 0)
223 224 225 226 227
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
gpestana's avatar
gpestana committed
228
		log.Warningf("getValueSingle: read timeout %s %s", p.Pretty(), key)
229 230
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
231
		eip.SetError(err)
232 233
		return nil, err
	}
Jeromy's avatar
Jeromy committed
234 235
}

236
// getLocal attempts to retrieve the value from the datastore
237 238
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
	log.Debugf("getLocal %s", key)
239
	rec, err := dht.getRecordFromDatastore(mkDsKey(key))
240
	if err != nil {
gpestana's avatar
gpestana committed
241
		log.Warningf("getLocal: %s", err)
242 243
		return nil, err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244

245
	// Double check the key. Can't hurt.
246
	if rec != nil && string(rec.GetKey()) != key {
gpestana's avatar
gpestana committed
247
		log.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
248
		return nil, nil
249 250

	}
251
	return rec, nil
252 253
}

Jeromy's avatar
Jeromy committed
254 255
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
Jeromy's avatar
Jeromy committed
256 257 258
func (dht *IpfsDHT) getOwnPrivateKey() (ci.PrivKey, error) {
	sk := dht.peerstore.PrivKey(dht.self)
	if sk == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
259
		log.Warningf("%s dht cannot get own private key!", dht.self)
Jeromy's avatar
Jeromy committed
260 261 262 263 264
		return nil, fmt.Errorf("cannot get private key to sign record!")
	}
	return sk, nil
}

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

274
	return dht.datastore.Put(mkDsKey(key), data)
275
}
276

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

Jeromy's avatar
Jeromy committed
284
// 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
285
func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
286 287 288 289 290
	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
291 292
	}
}
293

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

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

317
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.ID, key cid.Cid) (*pb.Message, error) {
ForrestWeston's avatar
ForrestWeston committed
318 319
	eip := log.EventBegin(ctx, "findProvidersSingle", p, key)
	defer eip.Done()
320

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

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

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

	// no node? nil
	if closer == nil {
gpestana's avatar
gpestana committed
347
		log.Warning("betterPeersToQuery: no closer peers to send:", p)
348 349 350
		return nil
	}

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

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

Jeromy's avatar
Jeromy committed
364
		filtered = append(filtered, clp)
365 366
	}

367 368
	// ok seems like closer nodes
	return filtered
369 370
}

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

386 387 388 389
// Close calls Process Close
func (dht *IpfsDHT) Close() error {
	return dht.proc.Close()
}
390

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

	return pstrs
}

400 401 402
func mkDsKey(s string) ds.Key {
	return ds.NewKey(base32.RawStdEncoding.EncodeToString([]byte(s)))
}