dht.go 11.7 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
	"crypto/rand"
8
	"errors"
9
	"fmt"
10 11
	"sync"
	"time"
12

13
	inet "github.com/jbenet/go-ipfs/net"
14
	peer "github.com/jbenet/go-ipfs/peer"
15
	routing "github.com/jbenet/go-ipfs/routing"
16
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
Jeromy's avatar
Jeromy committed
17
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
18
	u "github.com/jbenet/go-ipfs/util"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
19
	"github.com/jbenet/go-ipfs/util/eventlog"
20

21
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
22
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
23 24
	ctxgroup "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-ctxgroup"
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
25 26
)

27
var log = eventlog.Logger("dht")
28

29
const doPinging = false
30

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31 32 33 34 35
// 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 {
36 37 38
	network   inet.Network   // the network services we need
	self      peer.Peer      // Local peer (yourself)
	peerstore peer.Peerstore // Other peers
39

40
	datastore ds.Datastore // Local data
41
	dslock    sync.Mutex
42

43 44
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
	providers    *ProviderManager
45

46 47
	birth    time.Time  // When this peer started up
	diaglock sync.Mutex // lock to make diagnostics work better
48

49 50 51
	// record validator funcs
	Validators map[string]ValidatorFunc

52
	ctxgroup.ContextGroup
53 54
}

Jeromy's avatar
Jeromy committed
55
// NewDHT creates a new DHT object with the given peer as the 'local' host
56
func NewDHT(ctx context.Context, p peer.Peer, ps peer.Peerstore, n inet.Network, dstore ds.Datastore) *IpfsDHT {
57
	dht := new(IpfsDHT)
Jeromy's avatar
Jeromy committed
58
	dht.datastore = dstore
59
	dht.self = p
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60
	dht.peerstore = ps
61 62 63
	dht.ContextGroup = ctxgroup.WithContext(ctx)
	dht.network = n
	n.SetHandler(inet.ProtocolDHT, dht.handleNewStream)
64

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
65
	dht.providers = NewProviderManager(dht.Context(), p.ID())
66
	dht.AddChildGroup(dht.providers)
67

68
	dht.routingTable = kb.NewRoutingTable(20, kb.ConvertPeerID(p.ID()), time.Minute)
69
	dht.birth = time.Now()
70

71
	dht.Validators = make(map[string]ValidatorFunc)
72
	dht.Validators["pk"] = ValidatePublicKeyRecord
73

74
	if doPinging {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75
		dht.Children().Add(1)
76 77
		go dht.PingRoutine(time.Second * 10)
	}
Jeromy's avatar
Jeromy committed
78
	return dht
79 80
}

81
// Connect to a new peer at the given address, ping and add to the routing table
82
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.Peer) error {
83
	if err := dht.network.DialPeer(ctx, npeer); err != nil {
84
		return err
85 86
	}

Jeromy's avatar
Jeromy committed
87 88
	// Ping new peer to register in their routing table
	// NOTE: this should be done better...
89
	if err := dht.Ping(ctx, npeer); err != nil {
90
		return fmt.Errorf("failed to ping newly connected peer: %s\n", err)
Jeromy's avatar
Jeromy committed
91
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
92
	log.Event(ctx, "connect", dht.self, npeer)
93
	dht.Update(ctx, npeer)
94
	return nil
Jeromy's avatar
Jeromy committed
95 96
}

97
// putValueToNetwork stores the given key/value pair at the peer 'p'
98
func (dht *IpfsDHT) putValueToNetwork(ctx context.Context, p peer.Peer,
99
	key string, rec *pb.Record) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
100

101
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
102
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104 105 106
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107

108
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109 110 111
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112 113
}

Jeromy's avatar
Jeromy committed
114 115
// putProvider sends a message to peer 'p' saying that the local node
// can provide the value of 'key'
116
func (dht *IpfsDHT) putProvider(ctx context.Context, p peer.Peer, key string) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117

118
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
119 120

	// add self as the provider
121
	pmes.ProviderPeers = pb.PeersToPBPeers(dht.network, []peer.Peer{dht.self})
122

123
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124 125 126
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127

128
	log.Debugf("%s putProvider: %s for %s", dht.self, p, u.Key(key))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129 130

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131 132
}

133
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.Peer,
134
	key u.Key) ([]byte, []peer.Peer, error) {
135

136
	pmes, err := dht.getValueSingle(ctx, p, key)
137
	if err != nil {
138
		return nil, nil, err
139 140
	}

141
	if record := pmes.GetRecord(); record != nil {
142
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
143
		log.Debug("getValueOrPeers: got value")
144 145 146 147

		// make sure record is still valid
		err = dht.verifyRecord(record)
		if err != nil {
Jeromy's avatar
Jeromy committed
148
			log.Error("Received invalid record!")
149 150 151
			return nil, nil, err
		}
		return record.GetValue(), nil, nil
152
	}
153

154
	// TODO decide on providers. This probably shouldn't be happening.
155
	if prv := pmes.GetProviderPeers(); prv != nil && len(prv) > 0 {
156
		val, err := dht.getFromPeerList(ctx, key, prv)
157 158 159
		if err != nil {
			return nil, nil, err
		}
Jeromy's avatar
Jeromy committed
160
		log.Debug("getValueOrPeers: get from providers")
161 162
		return val, nil, nil
	}
163 164

	// Perhaps we were given closer peers
165 166
	peers, errs := pb.PBPeersToPeers(dht.peerstore, pmes.GetCloserPeers())
	for _, err := range errs {
167
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168
			log.Error(err)
169
		}
170
	}
171 172

	if len(peers) > 0 {
173
		log.Debug("getValueOrPeers: peers")
174 175 176
		return nil, peers, nil
	}

177 178
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
179 180
}

181
// getValueSingle simply performs the get value RPC with the given parameters
182
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.Peer,
183
	key u.Key) (*pb.Message, error) {
184

185
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
186
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
187 188
}

189 190 191 192
// TODO: Im not certain on this implementation, we get a list of peers/providers
// from someone what do we do with it? Connect to each of them? randomly pick
// one to get the value from? Or just connect to one at a time until we get a
// successful connection and request the value from it?
193
func (dht *IpfsDHT) getFromPeerList(ctx context.Context, key u.Key,
194
	peerlist []*pb.Message_Peer) ([]byte, error) {
195

196
	for _, pinfo := range peerlist {
197
		p, err := dht.ensureConnectedToPeer(ctx, pinfo)
198
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
199
			log.Errorf("getFromPeers error: %s", err)
200
			continue
Jeromy's avatar
Jeromy committed
201
		}
202

203
		pmes, err := dht.getValueSingle(ctx, p, key)
Jeromy's avatar
Jeromy committed
204
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205
			log.Errorf("getFromPeers error: %s\n", err)
Jeromy's avatar
Jeromy committed
206 207 208
			continue
		}

209
		if record := pmes.GetRecord(); record != nil {
210
			// Success! We were given the value
211 212 213 214 215

			err := dht.verifyRecord(record)
			if err != nil {
				return nil, err
			}
216
			dht.providers.AddProvider(key, p)
217
			return record.GetValue(), nil
218
		}
Jeromy's avatar
Jeromy committed
219
	}
220
	return nil, routing.ErrNotFound
Jeromy's avatar
Jeromy committed
221 222
}

223
// getLocal attempts to retrieve the value from the datastore
224
func (dht *IpfsDHT) getLocal(key u.Key) ([]byte, error) {
225 226
	dht.dslock.Lock()
	defer dht.dslock.Unlock()
Jeromy's avatar
Jeromy committed
227
	log.Debug("getLocal %s", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
228
	v, err := dht.datastore.Get(key.DsKey())
229 230 231
	if err != nil {
		return nil, err
	}
Jeromy's avatar
Jeromy committed
232
	log.Debug("found in db")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
233 234 235

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

	// TODO: 'if paranoid'
	if u.Debug {
		err = dht.verifyRecord(rec)
		if err != nil {
Jeromy's avatar
Jeromy committed
248
			log.Errorf("local record verify failed: %s", err)
249 250 251 252 253
			return nil, err
		}
	}

	return rec.GetValue(), nil
254 255
}

256
// putLocal stores the key value pair in the datastore
257
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
258 259 260 261 262 263 264 265 266 267
	rec, err := dht.makePutRecord(key, value)
	if err != nil {
		return err
	}
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

	return dht.datastore.Put(key.DsKey(), 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 273
func (dht *IpfsDHT) Update(ctx context.Context, p peer.Peer) {
	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.
278
func (dht *IpfsDHT) FindLocal(id peer.ID) (peer.Peer, *kb.RoutingTable) {
279 280 281
	p := dht.routingTable.Find(id)
	if p != nil {
		return p, dht.routingTable
Jeromy's avatar
Jeromy committed
282 283 284
	}
	return nil, nil
}
285

Jeromy's avatar
Jeromy committed
286
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
287 288
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.Peer, id peer.ID) (*pb.Message, error) {
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
289
	return dht.sendRequest(ctx, p, pmes)
290
}
291

292 293
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.Peer, key u.Key) (*pb.Message, error) {
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
295 296
}

297 298 299 300 301
func (dht *IpfsDHT) addProviders(key u.Key, pbps []*pb.Message_Peer) []peer.Peer {
	peers, errs := pb.PBPeersToPeers(dht.peerstore, pbps)
	for _, err := range errs {
		log.Errorf("error converting peer: %v", err)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
302

303 304
	var provArr []peer.Peer
	for _, p := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
305
		// Dont add outselves to the list
306
		if p.ID().Equal(dht.self.ID()) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
307
			continue
Jeromy's avatar
Jeromy committed
308
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
309

310
		log.Debugf("%s adding provider: %s for %s", dht.self, p, key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
311
		// TODO(jbenet) ensure providers is idempotent
312
		dht.providers.AddProvider(key, p)
313
		provArr = append(provArr, p)
Jeromy's avatar
Jeromy committed
314
	}
315
	return provArr
Jeromy's avatar
Jeromy committed
316
}
Jeromy's avatar
Jeromy committed
317

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

325
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
326
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, count int) []peer.Peer {
327
	closer := dht.nearestPeersToQuery(pmes, count)
328 329 330 331 332 333

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

334 335
	// == to self? thats bad
	for _, p := range closer {
336
		if p.ID().Equal(dht.self.ID()) {
337 338 339
			log.Error("Attempted to return self! this shouldnt happen...")
			return nil
		}
340 341
	}

342
	var filtered []peer.Peer
343 344 345
	for _, p := range closer {
		// must all be closer than self
		key := u.Key(pmes.GetKey())
346
		if !kb.Closer(dht.self.ID(), p.ID(), key) {
347 348
			filtered = append(filtered, p)
		}
349 350
	}

351 352
	// ok seems like closer nodes
	return filtered
353 354
}

Jeromy's avatar
Jeromy committed
355
// getPeer searches the peerstore for a peer with the given peer ID
356
func (dht *IpfsDHT) getPeer(id peer.ID) (peer.Peer, error) {
357
	p, err := dht.peerstore.FindOrCreate(id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
358 359
	if err != nil {
		err = fmt.Errorf("Failed to get peer from peerstore: %s", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
360
		log.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
361 362 363 364 365
		return nil, err
	}
	return p, nil
}

366 367
func (dht *IpfsDHT) ensureConnectedToPeer(ctx context.Context, pbp *pb.Message_Peer) (peer.Peer, error) {
	p, err := pb.PBPeerToPeer(dht.peerstore, pbp)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
368 369
	if err != nil {
		return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
370 371
	}

372
	if dht.self.ID().Equal(p.ID()) {
373
		return nil, errors.New("attempting to ensure connection to self")
Jeromy's avatar
Jeromy committed
374 375
	}

376
	// dial connection
377
	err = dht.network.DialPeer(ctx, p)
378
	return p, err
Jeromy's avatar
Jeromy committed
379
}
380

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
381
//TODO: this should be smarter about which keys it selects.
382
func (dht *IpfsDHT) loadProvidableKeys() error {
383 384 385 386
	kl, err := dht.datastore.KeyList()
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
387 388 389
	for _, dsk := range kl {
		k := u.KeyFromDsKey(dsk)
		if len(k) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
390
			log.Errorf("loadProvidableKeys error: %v", dsk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
391 392 393
		}

		dht.providers.AddProvider(k, dht.self)
394 395 396 397
	}
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
398
// PingRoutine periodically pings nearest neighbors.
399
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
400 401
	defer dht.Children().Done()

402 403 404 405 406 407
	tick := time.Tick(t)
	for {
		select {
		case <-tick:
			id := make([]byte, 16)
			rand.Read(id)
408
			peers := dht.routingTable.NearestPeers(kb.ConvertKey(u.Key(id)), 5)
409
			for _, p := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
410
				ctx, _ := context.WithTimeout(dht.Context(), time.Second*5)
411 412
				err := dht.Ping(ctx, p)
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
413
					log.Errorf("Ping error: %s", err)
414 415
				}
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
416
		case <-dht.Closing():
417 418 419 420 421
			return
		}
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
422
// Bootstrap builds up list of peers by requesting random peer IDs
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
423
func (dht *IpfsDHT) Bootstrap(ctx context.Context) {
424 425
	id := make([]byte, 16)
	rand.Read(id)
Jeromy's avatar
Jeromy committed
426 427
	p, err := dht.FindPeer(ctx, peer.ID(id))
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
428
		log.Errorf("Bootstrap peer error: %s", err)
Jeromy's avatar
Jeromy committed
429
	}
430
	err = dht.network.DialPeer(ctx, p)
431
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
432
		log.Errorf("Bootstrap peer error: %s", err)
433
	}
434
}