dht.go 10.3 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"
7
	"errors"
8
	"fmt"
9 10
	"sync"
	"time"
11

12 13 14 15
	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"

16
	proto "github.com/gogo/protobuf/proto"
17
	cid "github.com/ipfs/go-cid"
18 19 20 21 22 23 24
	ds "github.com/ipfs/go-datastore"
	ci "github.com/ipfs/go-libp2p-crypto"
	peer "github.com/ipfs/go-libp2p-peer"
	pstore "github.com/ipfs/go-libp2p-peerstore"
	logging "github.com/ipfs/go-log"
	goprocess "github.com/jbenet/goprocess"
	goprocessctx "github.com/jbenet/goprocess/context"
George Antoniadis's avatar
George Antoniadis committed
25 26
	kb "github.com/libp2p/go-libp2p-kbucket"
	record "github.com/libp2p/go-libp2p-record"
George Antoniadis's avatar
George Antoniadis committed
27
	recpb "github.com/libp2p/go-libp2p-record/pb"
George Antoniadis's avatar
George Antoniadis committed
28 29
	host "github.com/libp2p/go-libp2p/p2p/host"
	protocol "github.com/libp2p/go-libp2p/p2p/protocol"
30
	base32 "github.com/whyrusleeping/base32"
31
	context "golang.org/x/net/context"
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 46 47
// TODO. SEE https://github.com/jbenet/node-ipfs/blob/master/submodules/ipfs-dht/index.js

// 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
48 49 50
	host      host.Host        // the network services we need
	self      peer.ID          // Local peer (yourself)
	peerstore pstore.Peerstore // Peer Registry
51

52
	datastore ds.Datastore // Local data
53

54
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
55
	providers    *providers.ProviderManager
56

57 58
	birth    time.Time  // When this peer started up
	diaglock sync.Mutex // lock to make diagnostics work better
59

60
	Validator record.Validator // record validator funcs
61
	Selector  record.Selector  // record selection funcs
62

63 64
	ctx  context.Context
	proc goprocess.Process
65

66 67
	clientOnly bool

68 69
	strmap map[peer.ID]*messageSender
	smlk   sync.Mutex
70 71
}

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

76 77 78
	// register for network notifs.
	dht.host.Network().Notify((*netNotifiee)(dht))

Jeromy's avatar
Jeromy committed
79
	dht.proc = goprocessctx.WithContextAndTeardown(ctx, func() error {
80 81 82 83
		// remove ourselves from network notifs.
		dht.host.Network().StopNotify((*netNotifiee)(dht))
		return nil
	})
84

Jeromy's avatar
Jeromy committed
85
	dht.proc.AddChild(dht.providers.Process())
86

87
	h.SetStreamHandler(ProtocolDHT, dht.handleNewStream)
Jeromy's avatar
Jeromy committed
88 89
	h.SetStreamHandler(ProtocolDHTOld, dht.handleNewStream)

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

Jeromy's avatar
Jeromy committed
93
	return dht
94 95
}

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
// 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
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
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()),

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
151 152 153
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154

155
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156 157 158
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
159 160
}

161 162
var errInvalidRecord = errors.New("received invalid record")

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

169
	pmes, err := dht.getValueSingle(ctx, p, key)
170
	if err != nil {
171
		return nil, nil, err
172 173
	}

174 175 176
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

177
	if record := pmes.GetRecord(); record != nil {
178
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
179
		log.Debug("getValueOrPeers: got value")
180

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

192
	if len(peers) > 0 {
193
		log.Debug("getValueOrPeers: peers")
194 195 196
		return nil, peers, nil
	}

197 198
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
199 200
}

201
// getValueSingle simply performs the get value RPC with the given parameters
202 203 204 205 206 207 208
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()
209

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

223
// getLocal attempts to retrieve the value from the datastore
224 225
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
	log.Debugf("getLocal %s", key)
226

227
	v, err := dht.datastore.Get(mkDsKey(key))
228 229 230
	if err != nil {
		return nil, err
	}
231
	log.Debugf("found %s in local datastore")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232 233 234

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

Jeromy's avatar
Jeromy committed
243 244 245 246
	err = dht.verifyRecordLocally(rec)
	if err != nil {
		log.Debugf("local record verify failed: %s (discarded)", err)
		return nil, err
247 248
	}

249
	return rec, nil
250 251
}

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

263
// putLocal stores the key value pair in the datastore
264
func (dht *IpfsDHT) putLocal(key string, rec *recpb.Record) error {
265 266 267 268 269
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

270
	return dht.datastore.Put(mkDsKey(key), data)
271
}
272

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

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

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

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

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

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

322
// nearestPeersToQuery returns the routing tables closest peers.
323
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
324
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(pmes.GetKey()), count)
325 326 327
	return closer
}

328
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
329
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
330
	closer := dht.nearestPeersToQuery(pmes, count)
331 332 333 334 335 336

	// no node? nil
	if closer == nil {
		return nil
	}

337 338
	// == to self? thats bad
	for _, p := range closer {
339
		if p == dht.self {
340
			log.Debug("attempted to return self! this shouldn't happen...")
341 342
			return nil
		}
343 344
	}

345
	var filtered []peer.ID
346 347 348 349 350 351
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

Jeromy's avatar
Jeromy committed
352
		filtered = append(filtered, clp)
353 354
	}

355 356
	// ok seems like closer nodes
	return filtered
357 358
}

359 360 361 362 363 364 365 366 367 368 369 370 371 372
// 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()
}
373 374 375 376

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