dht.go 10.9 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
// Package dht implements a distributed hash table that satisfies the ipfs routing
2
// interface. This DHT is modeled after kademlia with S/Kademlia modifications.
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
3 4
package dht

5
import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"bytes"
Jeromy's avatar
Jeromy committed
7
	"context"
8
	"errors"
9
	"fmt"
10 11
	"sync"
	"time"
12

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

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

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

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

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

48
	datastore ds.Datastore // Local data
49

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

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

55
	Validator record.Validator
56

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

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

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

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

68 69 70 71 72 73
// 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
	}
74
	dht := makeDHT(ctx, h, cfg.Datastore, cfg.Protocols)
75 76 77 78 79 80 81 82 83 84 85

	// 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())
86 87 88
	dht.Validator = cfg.Validator

	if !cfg.Client {
89 90 91
		for _, p := range cfg.Protocols {
			h.SetStreamHandler(p, dht.handleNewStream)
		}
92 93 94
	}
	return dht, nil
}
95

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
// 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)
	}
116 117 118
	return dht
}

119
func makeDHT(ctx context.Context, h host.Host, dstore ds.Batching, protocols []protocol.ID) *IpfsDHT {
120 121 122 123 124 125 126 127 128 129
	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
130 131 132 133 134 135 136 137 138
	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(),
139
		routingTable: rt,
140
		protocols:    protocols,
Jeromy's avatar
Jeromy committed
141 142 143
	}
}

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

148
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, key, 0)
149
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150
	rpmes, err := dht.sendRequest(ctx, p, pmes)
151 152
	switch err {
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
153
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
154 155 156 157 158 159 160
		fallthrough
	default:
		return err
	case nil:
		break
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
161 162 163
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164

165
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166 167 168
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169 170
}

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

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

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

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

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

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

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

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

211
// getValueSingle simply performs the get value RPC with the given parameters
212 213 214 215 216 217
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
218 219
	eip := log.EventBegin(ctx, "getValueSingle", meta)
	defer eip.Done()
220

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

235
// getLocal attempts to retrieve the value from the datastore
236 237
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
	log.Debugf("getLocal %s", key)
238

239
	v, err := dht.datastore.Get(mkDsKey(key))
240 241 242
	if err != nil {
		return nil, err
	}
243
	log.Debugf("found %s in local datastore")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244 245 246

	byt, ok := v.([]byte)
	if !ok {
247
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
248
	}
George Antoniadis's avatar
George Antoniadis committed
249
	rec := new(recpb.Record)
250 251 252 253 254
	err = proto.Unmarshal(byt, rec)
	if err != nil {
		return nil, err
	}

255
	err = dht.Validator.Validate(rec.GetKey(), rec.GetValue())
Jeromy's avatar
Jeromy committed
256 257 258
	if err != nil {
		log.Debugf("local record verify failed: %s (discarded)", err)
		return nil, err
259 260
	}

261
	return rec, nil
262 263
}

Jeromy's avatar
Jeromy committed
264 265
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
Jeromy's avatar
Jeromy committed
266 267 268
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
269
		log.Warningf("%s dht cannot get own private key!", dht.self)
Jeromy's avatar
Jeromy committed
270 271 272 273 274
		return nil, fmt.Errorf("cannot get private key to sign record!")
	}
	return sk, nil
}

275
// putLocal stores the key value pair in the datastore
276
func (dht *IpfsDHT) putLocal(key string, rec *recpb.Record) error {
277 278 279 280 281
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

282
	return dht.datastore.Put(mkDsKey(key), data)
283
}
284

285
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
286
// on the given peer.
287
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
288
	log.Event(ctx, "updatePeer", p)
289
	dht.routingTable.Update(p)
290
}
Jeromy's avatar
Jeromy committed
291

Jeromy's avatar
Jeromy committed
292
// 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
293
func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
294
	p := dht.routingTable.Find(id)
295
	if p != "" {
Jeromy's avatar
Jeromy committed
296
		return dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
297
	}
Jeromy's avatar
Jeromy committed
298
	return pstore.PeerInfo{}
Jeromy's avatar
Jeromy committed
299
}
300

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

310
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
311 312 313 314 315
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
316
		log.Warningf("read timeout: %s %s", p.Pretty(), id)
317 318
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
319
		eip.SetError(err)
320 321
		return nil, err
	}
322
}
323

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

328
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, key.KeyString(), 0)
329 330 331 332 333
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
334
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
335 336
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
337
		eip.SetError(err)
338 339
		return nil, err
	}
Jeromy's avatar
Jeromy committed
340 341
}

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

348
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
349
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
350
	closer := dht.nearestPeersToQuery(pmes, count)
351 352 353

	// no node? nil
	if closer == nil {
Jeromy's avatar
Jeromy committed
354
		log.Warning("no closer peers to send:", p)
355 356 357
		return nil
	}

Steven Allen's avatar
Steven Allen committed
358
	filtered := make([]peer.ID, 0, len(closer))
Jeromy's avatar
Jeromy committed
359 360 361
	for _, clp := range closer {

		// == to self? thats bad
Jeromy's avatar
Jeromy committed
362
		if clp == dht.self {
Jeromy's avatar
Jeromy committed
363
			log.Warning("attempted to return self! this shouldn't happen...")
364 365
			return nil
		}
366
		// Dont send a peer back themselves
Jeromy's avatar
Jeromy committed
367
		if clp == p {
368 369 370
			continue
		}

Jeromy's avatar
Jeromy committed
371
		filtered = append(filtered, clp)
372 373
	}

374 375
	// ok seems like closer nodes
	return filtered
376 377
}

378 379 380 381 382 383 384 385 386 387 388 389 390 391
// 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
}

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

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

	return pstrs
}

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