dht.go 9.8 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 102 103 104 105 106 107 108 109 110 111
func makeDHT(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
	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(),
		routingTable: kb.NewRoutingTable(KValue, kb.ConvertPeerID(h.ID()), time.Minute, h.Peerstore()),
112
		peers:        make(map[peer.ID]*peerTracker),
Jeromy's avatar
Jeromy committed
113 114 115 116 117 118

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

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

123
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, key, 0)
124
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125
	rpmes, err := dht.sendRequest(ctx, p, pmes)
126 127
	switch err {
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
128
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
129 130 131 132 133 134 135
		fallthrough
	default:
		return err
	case nil:
		break
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136 137 138
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139

140
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141 142 143
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144 145
}

146 147
var errInvalidRecord = errors.New("received invalid record")

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

154
	pmes, err := dht.getValueSingle(ctx, p, key)
155
	if err != nil {
156
		return nil, nil, err
157 158
	}

159 160 161
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

162
	if record := pmes.GetRecord(); record != nil {
163
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
164
		log.Debug("getValueOrPeers: got value")
165

166 167
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
168
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169
			log.Info("Received invalid record! (discarded)")
170 171
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
George Antoniadis's avatar
George Antoniadis committed
172
			record = new(recpb.Record)
173
		}
174
		return record, peers, err
175
	}
176

177
	if len(peers) > 0 {
178
		log.Debug("getValueOrPeers: peers")
179 180 181
		return nil, peers, nil
	}

182 183
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
184 185
}

186
// getValueSingle simply performs the get value RPC with the given parameters
187 188 189 190 191 192 193
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()
194

195
	pmes := pb.NewMessage(pb.Message_GET_VALUE, key, 0)
196 197 198 199 200
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
201
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
202 203 204 205
		fallthrough
	default:
		return nil, err
	}
Jeromy's avatar
Jeromy committed
206 207
}

208
// getLocal attempts to retrieve the value from the datastore
209 210
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
	log.Debugf("getLocal %s", key)
211

212
	v, err := dht.datastore.Get(mkDsKey(key))
213 214 215
	if err != nil {
		return nil, err
	}
216
	log.Debugf("found %s in local datastore")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217 218 219

	byt, ok := v.([]byte)
	if !ok {
220
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221
	}
George Antoniadis's avatar
George Antoniadis committed
222
	rec := new(recpb.Record)
223 224 225 226 227
	err = proto.Unmarshal(byt, rec)
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
228 229 230 231
	err = dht.verifyRecordLocally(rec)
	if err != nil {
		log.Debugf("local record verify failed: %s (discarded)", err)
		return nil, err
232 233
	}

234
	return rec, nil
235 236
}

Jeromy's avatar
Jeromy committed
237 238
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
Jeromy's avatar
Jeromy committed
239 240 241
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
242
		log.Warningf("%s dht cannot get own private key!", dht.self)
Jeromy's avatar
Jeromy committed
243 244 245 246 247
		return nil, fmt.Errorf("cannot get private key to sign record!")
	}
	return sk, nil
}

248
// putLocal stores the key value pair in the datastore
249
func (dht *IpfsDHT) putLocal(key string, rec *recpb.Record) error {
250 251 252 253 254
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

255
	return dht.datastore.Put(mkDsKey(key), data)
256
}
257

258
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
259
// on the given peer.
260
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
261
	log.Event(ctx, "updatePeer", p)
262
	dht.routingTable.Update(p)
263
}
Jeromy's avatar
Jeromy committed
264

Jeromy's avatar
Jeromy committed
265
// 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
266
func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
267
	p := dht.routingTable.Find(id)
268
	if p != "" {
Jeromy's avatar
Jeromy committed
269
		return dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
270
	}
Jeromy's avatar
Jeromy committed
271
	return pstore.PeerInfo{}
Jeromy's avatar
Jeromy committed
272
}
273

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

278
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
279 280 281 282 283
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
284
		log.Warningf("read timeout: %s %s", p.Pretty(), id)
285 286 287 288
		fallthrough
	default:
		return nil, err
	}
289
}
290

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

294
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, key.KeyString(), 0)
295 296 297 298 299
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
300
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
301 302 303 304
		fallthrough
	default:
		return nil, err
	}
Jeromy's avatar
Jeromy committed
305 306
}

307
// nearestPeersToQuery returns the routing tables closest peers.
308
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
309
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(pmes.GetKey()), count)
310 311 312
	return closer
}

313
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
314
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
315
	closer := dht.nearestPeersToQuery(pmes, count)
316 317 318

	// no node? nil
	if closer == nil {
Jeromy's avatar
Jeromy committed
319
		log.Warning("no closer peers to send:", p)
320 321 322
		return nil
	}

Jeromy's avatar
Jeromy committed
323 324 325 326
	var filtered []peer.ID
	for _, clp := range closer {

		// == to self? thats bad
Jeromy's avatar
Jeromy committed
327
		if clp == dht.self {
Jeromy's avatar
Jeromy committed
328
			log.Warning("attempted to return self! this shouldn't happen...")
329 330
			return nil
		}
331
		// Dont send a peer back themselves
Jeromy's avatar
Jeromy committed
332
		if clp == p {
333 334 335
			continue
		}

Jeromy's avatar
Jeromy committed
336
		filtered = append(filtered, clp)
337 338
	}

339 340
	// ok seems like closer nodes
	return filtered
341 342
}

343 344 345 346 347 348 349 350 351 352 353 354 355 356
// 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()
}
357 358 359 360

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