dht.go 9.99 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 Coral and 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 14 15 16
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
	providers "github.com/libp2p/go-libp2p-kad-dht/providers"
	routing "github.com/libp2p/go-libp2p-routing"

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
	base32 "github.com/whyrusleeping/base32"
32 33
)

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

Jeromy's avatar
Jeromy committed
36 37
var ProtocolDHT protocol.ID = "/ipfs/kad/1.0.0"
var ProtocolDHTOld protocol.ID = "/ipfs/dht"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44 45
// IpfsDHT is an implementation of Kademlia with Coral and S/Kademlia modifications.
// 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 // record validator funcs
58
	Selector  record.Selector  // record selection funcs
59

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

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

	plk   sync.Mutex
	peers map[peer.ID]*peerTracker
68 69
}

Jeromy's avatar
Jeromy committed
70
// NewDHT creates a new DHT object with the given peer as the 'local' host
71
func NewDHT(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
Justin Drake's avatar
Justin Drake committed
72
	dht := NewDHTClient(ctx, h, dstore)
73

74
	h.SetStreamHandler(ProtocolDHT, dht.handleNewStream)
Jeromy's avatar
Jeromy committed
75
	h.SetStreamHandler(ProtocolDHTOld, dht.handleNewStream)
Jeromy's avatar
Jeromy committed
76

Jeromy's avatar
Jeromy committed
77
	return dht
78 79
}

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
// 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 := makeDHT(ctx, h, dstore)

	// 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())

	dht.Validator["pk"] = record.PublicKeyValidator
	dht.Selector["pk"] = record.PublicKeySelector

	return dht
}

Jeromy's avatar
Jeromy committed
101
func makeDHT(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
102 103 104 105 106 107 108 109 110 111
	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
112 113 114 115 116 117 118 119 120
	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(),
121
		routingTable: rt,
122
		peers:        make(map[peer.ID]*peerTracker),
Jeromy's avatar
Jeromy committed
123 124 125 126 127 128

		Validator: make(record.Validator),
		Selector:  make(record.Selector),
	}
}

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

133
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, key, 0)
134
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135
	rpmes, err := dht.sendRequest(ctx, p, pmes)
136 137
	switch err {
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
138
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
139 140 141 142 143 144 145
		fallthrough
	default:
		return err
	case nil:
		break
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146 147 148
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149

150
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
151 152 153
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154 155
}

156 157
var errInvalidRecord = errors.New("received invalid record")

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

164
	pmes, err := dht.getValueSingle(ctx, p, key)
165
	if err != nil {
166
		return nil, nil, err
167 168
	}

169 170 171
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

172
	if record := pmes.GetRecord(); record != nil {
173
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
174
		log.Debug("getValueOrPeers: got value")
175

176 177
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
178
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179
			log.Info("Received invalid record! (discarded)")
180 181
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
George Antoniadis's avatar
George Antoniadis committed
182
			record = new(recpb.Record)
183
		}
184
		return record, peers, err
185
	}
186

187
	if len(peers) > 0 {
188
		log.Debug("getValueOrPeers: peers")
189 190 191
		return nil, peers, nil
	}

192 193
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
194 195
}

196
// getValueSingle simply performs the get value RPC with the given parameters
197 198 199 200 201 202 203
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID, key string) (*pb.Message, error) {
	meta := logging.LoggableMap{
		"key":  key,
		"peer": p,
	}

	defer log.EventBegin(ctx, "getValueSingle", meta).Done()
204

205
	pmes := pb.NewMessage(pb.Message_GET_VALUE, key, 0)
206 207 208 209 210
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
211
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
212 213 214 215
		fallthrough
	default:
		return nil, err
	}
Jeromy's avatar
Jeromy committed
216 217
}

218
// getLocal attempts to retrieve the value from the datastore
219 220
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
	log.Debugf("getLocal %s", key)
221

222
	v, err := dht.datastore.Get(mkDsKey(key))
223 224 225
	if err != nil {
		return nil, err
	}
226
	log.Debugf("found %s in local datastore")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227 228 229

	byt, ok := v.([]byte)
	if !ok {
230
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
	}
George Antoniadis's avatar
George Antoniadis committed
232
	rec := new(recpb.Record)
233 234 235 236 237
	err = proto.Unmarshal(byt, rec)
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
238 239 240 241
	err = dht.verifyRecordLocally(rec)
	if err != nil {
		log.Debugf("local record verify failed: %s (discarded)", err)
		return nil, err
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 {
260 261 262 263 264
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

265
	return dht.datastore.Put(mkDsKey(key), data)
266
}
267

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

Jeromy's avatar
Jeromy committed
275
// 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
276
func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
277
	p := dht.routingTable.Find(id)
278
	if p != "" {
Jeromy's avatar
Jeromy committed
279
		return dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
280
	}
Jeromy's avatar
Jeromy committed
281
	return pstore.PeerInfo{}
Jeromy's avatar
Jeromy committed
282
}
283

Jeromy's avatar
Jeromy committed
284
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
285
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
Jeromy's avatar
Jeromy committed
286
	defer log.EventBegin(ctx, "findPeerSingle", p, id).Done()
287

288
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
289 290 291 292 293
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
294
		log.Warningf("read timeout: %s %s", p.Pretty(), id)
295 296 297 298
		fallthrough
	default:
		return nil, err
	}
299
}
300

301 302
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.ID, key *cid.Cid) (*pb.Message, error) {
	defer log.EventBegin(ctx, "findProvidersSingle", p, key).Done()
303

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

317
// nearestPeersToQuery returns the routing tables closest peers.
318
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
319
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(pmes.GetKey()), count)
320 321 322
	return closer
}

323
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
324
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
325
	closer := dht.nearestPeersToQuery(pmes, count)
326 327 328

	// no node? nil
	if closer == nil {
Jeromy's avatar
Jeromy committed
329
		log.Warning("no closer peers to send:", p)
330 331 332
		return nil
	}

Steven Allen's avatar
Steven Allen committed
333
	filtered := make([]peer.ID, 0, len(closer))
Jeromy's avatar
Jeromy committed
334 335 336
	for _, clp := range closer {

		// == to self? thats bad
Jeromy's avatar
Jeromy committed
337
		if clp == dht.self {
Jeromy's avatar
Jeromy committed
338
			log.Warning("attempted to return self! this shouldn't happen...")
339 340
			return nil
		}
341
		// Dont send a peer back themselves
Jeromy's avatar
Jeromy committed
342
		if clp == p {
343 344 345
			continue
		}

Jeromy's avatar
Jeromy committed
346
		filtered = append(filtered, clp)
347 348
	}

349 350
	// ok seems like closer nodes
	return filtered
351 352
}

353 354 355 356 357 358 359 360 361 362 363 364 365 366
// 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()
}
367 368 369 370

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