dht.go 11 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
	inet "github.com/libp2p/go-libp2p-net"
27 28 29
	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
30
	record "github.com/libp2p/go-libp2p-record"
George Antoniadis's avatar
George Antoniadis committed
31
	recpb "github.com/libp2p/go-libp2p-record/pb"
32
	routing "github.com/libp2p/go-libp2p-routing"
33
	base32 "github.com/whyrusleeping/base32"
34 35
)

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

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

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

49
	datastore ds.Datastore // Local data
50

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

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

56
	Validator record.Validator
57

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

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

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

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

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

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

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

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

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

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

149
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, key, 0)
150
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
151
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
152
	if err != nil {
gpestana's avatar
gpestana committed
153
		log.Warningf("putValueToPeer: %s. (peer: %s, key: %s)", err.Error(), p.Pretty(), key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154 155
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156

157
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
gpestana's avatar
gpestana committed
158
		log.Warningf("putValueToPeer: value not put correctly. (%v != %v)", pmes, rpmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159 160
		return errors.New("value not put correctly")
	}
gpestana's avatar
gpestana committed
161

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163 164
}

165 166
var errInvalidRecord = errors.New("received invalid record")

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

173
	pmes, err := dht.getValueSingle(ctx, p, key)
174
	if err != nil {
175
		return nil, nil, err
176 177
	}

178 179 180
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

181
	if record := pmes.GetRecord(); record != nil {
182
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
183
		log.Debug("getValueOrPeers: got value")
184

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

196
	if len(peers) > 0 {
197
		log.Debug("getValueOrPeers: peers")
198 199 200
		return nil, peers, nil
	}

201 202
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
203 204
}

205
// getValueSingle simply performs the get value RPC with the given parameters
206 207 208 209 210 211
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
212 213
	eip := log.EventBegin(ctx, "getValueSingle", meta)
	defer eip.Done()
214

215
	pmes := pb.NewMessage(pb.Message_GET_VALUE, key, 0)
216 217 218 219 220
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
gpestana's avatar
gpestana committed
221
		log.Warningf("getValueSingle: read timeout %s %s", p.Pretty(), key)
222 223
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
224
		eip.SetError(err)
225 226
		return nil, err
	}
Jeromy's avatar
Jeromy committed
227 228
}

229
// getLocal attempts to retrieve the value from the datastore
230 231
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
	log.Debugf("getLocal %s", key)
232
	rec, err := dht.getRecordFromDatastore(mkDsKey(key))
233
	if err != nil {
gpestana's avatar
gpestana committed
234
		log.Warningf("getLocal: %v", err.Error())
235 236
		return nil, err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237

238 239
	// Double check the key. Can't hurt.
	if rec != nil && rec.GetKey() != key {
gpestana's avatar
gpestana committed
240
		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
241
		return nil, nil
242 243

	}
244
	return rec, nil
245 246
}

Jeromy's avatar
Jeromy committed
247 248
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
Jeromy's avatar
Jeromy committed
249 250 251
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
252
		log.Warningf("%s dht cannot get own private key!", dht.self)
Jeromy's avatar
Jeromy committed
253 254 255 256 257
		return nil, fmt.Errorf("cannot get private key to sign record!")
	}
	return sk, nil
}

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

267
	return dht.datastore.Put(mkDsKey(key), data)
268
}
269

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

Jeromy's avatar
Jeromy committed
277
// 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
278
func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
279 280 281 282 283
	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
284 285
	}
}
286

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

296
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
297 298 299 300 301
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
302
		log.Warningf("read timeout: %s %s", p.Pretty(), id)
303 304
		fallthrough
	default:
ForrestWeston's avatar
ForrestWeston committed
305
		eip.SetError(err)
306 307
		return nil, err
	}
308
}
309

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

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

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

334
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
335
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
336
	closer := dht.nearestPeersToQuery(pmes, count)
337 338 339

	// no node? nil
	if closer == nil {
gpestana's avatar
gpestana committed
340
		log.Warning("betterPeersToQuery: no closer peers to send:", p)
341 342 343
		return nil
	}

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

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

Jeromy's avatar
Jeromy committed
357
		filtered = append(filtered, clp)
358 359
	}

360 361
	// ok seems like closer nodes
	return filtered
362 363
}

364 365 366 367 368 369 370 371 372 373 374 375 376 377
// 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()
}
378

379 380
func (dht *IpfsDHT) protocolStrs() []string {
	pstrs := make([]string, len(dht.protocols))
381 382
	for idx, proto := range dht.protocols {
		pstrs[idx] = string(proto)
383 384 385 386 387
	}

	return pstrs
}

388 389 390
func mkDsKey(s string) ds.Key {
	return ds.NewKey(base32.RawStdEncoding.EncodeToString([]byte(s)))
}