dht.go 15.8 KB
Newer Older
1 2
// package dht implements a distributed hash table that satisfies the ipfs routing
// 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
	msg "github.com/jbenet/go-ipfs/net/message"
15
	peer "github.com/jbenet/go-ipfs/peer"
16
	routing "github.com/jbenet/go-ipfs/routing"
17
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
Jeromy's avatar
Jeromy committed
18
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
19
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
	ctxc "github.com/jbenet/go-ipfs/util/ctxcloser"
21
	"github.com/jbenet/go-ipfs/util/elog"
22

23
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
24
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
Jeromy's avatar
Jeromy committed
25

26
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
27 28
)

29
var log = eventlog.Logger("dht")
30

31
const doPinging = false
32

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
33 34 35 36 37
// 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 {
38 39
	// Array of routing tables for differently distanced nodes
	// NOTE: (currently, only a single table is used)
40
	routingTables []*kb.RoutingTable
41

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42 43 44
	// the network services we need
	dialer inet.Dialer
	sender inet.Sender
45

Jeromy's avatar
Jeromy committed
46
	// Local peer (yourself)
47
	self peer.Peer
Jeromy's avatar
Jeromy committed
48

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
49 50 51
	// Other peers
	peerstore peer.Peerstore

Jeromy's avatar
Jeromy committed
52 53
	// Local data
	datastore ds.Datastore
54
	dslock    sync.Mutex
55

56
	providers *ProviderManager
57

58 59
	// When this peer started up
	birth time.Time
60 61 62

	//lock to make diagnostics work better
	diaglock sync.Mutex
63

64 65 66
	// record validator funcs
	Validators map[string]ValidatorFunc

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
67
	ctxc.ContextCloser
68 69
}

Jeromy's avatar
Jeromy committed
70
// NewDHT creates a new DHT object with the given peer as the 'local' host
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71
func NewDHT(ctx context.Context, p peer.Peer, ps peer.Peerstore, dialer inet.Dialer, sender inet.Sender, dstore ds.Datastore) *IpfsDHT {
72
	dht := new(IpfsDHT)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
73
	dht.dialer = dialer
74
	dht.sender = sender
Jeromy's avatar
Jeromy committed
75
	dht.datastore = dstore
76
	dht.self = p
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
77
	dht.peerstore = ps
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78
	dht.ContextCloser = ctxc.NewContextCloser(ctx, nil)
79

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
80 81
	dht.providers = NewProviderManager(dht.Context(), p.ID())
	dht.AddCloserChild(dht.providers)
82

83
	dht.routingTables = make([]*kb.RoutingTable, 3)
84 85 86
	dht.routingTables[0] = kb.NewRoutingTable(20, kb.ConvertPeerID(p.ID()), time.Millisecond*1000)
	dht.routingTables[1] = kb.NewRoutingTable(20, kb.ConvertPeerID(p.ID()), time.Millisecond*1000)
	dht.routingTables[2] = kb.NewRoutingTable(20, kb.ConvertPeerID(p.ID()), time.Hour)
87
	dht.birth = time.Now()
88

89
	dht.Validators = make(map[string]ValidatorFunc)
90
	dht.Validators["pk"] = ValidatePublicKeyRecord
91

92
	if doPinging {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93
		dht.Children().Add(1)
94 95
		go dht.PingRoutine(time.Second * 10)
	}
Jeromy's avatar
Jeromy committed
96
	return dht
97 98
}

99
// Connect to a new peer at the given address, ping and add to the routing table
100
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.Peer) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101
	log.Debugf("Connect to new peer: %s", npeer)
102 103 104 105 106 107 108 109 110 111

	// TODO(jbenet,whyrusleeping)
	//
	// Connect should take in a Peer (with ID). In a sense, we shouldn't be
	// allowing connections to random multiaddrs without knowing who we're
	// speaking to (i.e. peer.ID). In terms of moving around simple addresses
	// -- instead of an (ID, Addr) pair -- we can use:
	//
	//   /ip4/10.20.30.40/tcp/1234/ipfs/Qxhxxchxzcncxnzcnxzcxzm
	//
112
	err := dht.dialer.DialPeer(ctx, npeer)
113
	if err != nil {
114
		return nil, err
115 116
	}

Jeromy's avatar
Jeromy committed
117 118
	// Ping new peer to register in their routing table
	// NOTE: this should be done better...
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
119
	err = dht.Ping(ctx, npeer)
Jeromy's avatar
Jeromy committed
120
	if err != nil {
121
		return nil, fmt.Errorf("failed to ping newly connected peer: %s\n", err)
Jeromy's avatar
Jeromy committed
122 123
	}

124 125
	dht.Update(npeer)

126
	return npeer, nil
Jeromy's avatar
Jeromy committed
127 128
}

129
// HandleMessage implements the inet.Handler interface.
130
func (dht *IpfsDHT) HandleMessage(ctx context.Context, mes msg.NetMessage) msg.NetMessage {
131 132 133

	mData := mes.Data()
	if mData == nil {
134
		log.Error("Message contained nil data.")
135
		return nil
136 137 138 139
	}

	mPeer := mes.Peer()
	if mPeer == nil {
140
		log.Error("Message contained nil peer.")
141
		return nil
142 143 144
	}

	// deserialize msg
145
	pmes := new(pb.Message)
146 147
	err := proto.Unmarshal(mData, pmes)
	if err != nil {
148
		log.Error("Error unmarshaling data")
149
		return nil
150 151 152 153 154 155
	}

	// update the peer (on valid msgs only)
	dht.Update(mPeer)

	// Print out diagnostic
156
	log.Event(ctx, "foo", dht.self, mPeer, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
157
	log.Debugf("%s got message type: '%s' from %s",
158
		dht.self, pb.Message_MessageType_name[int32(pmes.GetType())], mPeer)
159 160 161 162

	// get handler for this msg type.
	handler := dht.handlerForMsgType(pmes.GetType())
	if handler == nil {
163
		log.Error("got back nil handler from handlerForMsgType")
164
		return nil
165 166 167 168 169
	}

	// dispatch handler.
	rpmes, err := handler(mPeer, pmes)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170
		log.Errorf("handle message error: %s", err)
171
		return nil
172 173
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
174 175
	// if nil response, return it before serializing
	if rpmes == nil {
176
		log.Warning("Got back nil response from request.")
177
		return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
178 179
	}

180 181 182
	// serialize response msg
	rmes, err := msg.FromObject(mPeer, rpmes)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183
		log.Errorf("serialze response error: %s", err)
184
		return nil
185 186
	}

187
	return rmes
188 189
}

190 191
// sendRequest sends out a request using dht.sender, but also makes sure to
// measure the RTT for latency measurements.
192
func (dht *IpfsDHT) sendRequest(ctx context.Context, p peer.Peer, pmes *pb.Message) (*pb.Message, error) {
193 194 195 196 197 198 199 200

	mes, err := msg.FromObject(p, pmes)
	if err != nil {
		return nil, err
	}

	start := time.Now()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201
	// Print out diagnostic
202
	log.Event(ctx, "sentMessage", dht.self, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203
	log.Debugf("Sent message type: '%s' to %s",
204
		pb.Message_MessageType_name[int32(pmes.GetType())], p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205

206 207 208 209
	rmes, err := dht.sender.SendRequest(ctx, mes)
	if err != nil {
		return nil, err
	}
210 211 212
	if rmes == nil {
		return nil, errors.New("no response to request")
	}
213 214 215 216

	rtt := time.Since(start)
	rmes.Peer().SetLatency(rtt)

217
	rpmes := new(pb.Message)
218 219 220 221 222 223 224
	if err := proto.Unmarshal(rmes.Data(), rpmes); err != nil {
		return nil, err
	}

	return rpmes, nil
}

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

229
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
230
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232 233 234
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235

236
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237 238 239
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
240 241
}

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

246
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
247 248

	// add self as the provider
249
	pmes.ProviderPeers = pb.PeersToPBPeers([]peer.Peer{dht.self})
250

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252 253 254
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
255

256
	log.Debugf("%s putProvider: %s for %s", dht.self, p, u.Key(key))
257
	if rpmes.GetKey() != pmes.GetKey() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
258 259 260 261
		return errors.New("provider not added correctly")
	}

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
262 263
}

264 265
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.Peer,
	key u.Key, level int) ([]byte, []peer.Peer, error) {
266 267

	pmes, err := dht.getValueSingle(ctx, p, key, level)
268
	if err != nil {
269
		return nil, nil, err
270 271
	}

272
	if record := pmes.GetRecord(); record != nil {
273
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
274
		log.Debug("getValueOrPeers: got value")
275 276 277 278

		// make sure record is still valid
		err = dht.verifyRecord(record)
		if err != nil {
Jeromy's avatar
Jeromy committed
279
			log.Error("Received invalid record!")
280 281 282
			return nil, nil, err
		}
		return record.GetValue(), nil, nil
283
	}
284

285
	// TODO decide on providers. This probably shouldn't be happening.
286 287 288 289 290
	if prv := pmes.GetProviderPeers(); prv != nil && len(prv) > 0 {
		val, err := dht.getFromPeerList(ctx, key, prv, level)
		if err != nil {
			return nil, nil, err
		}
Jeromy's avatar
Jeromy committed
291
		log.Debug("getValueOrPeers: get from providers")
292 293
		return val, nil, nil
	}
294 295

	// Perhaps we were given closer peers
296
	var peers []peer.Peer
297
	for _, pb := range pmes.GetCloserPeers() {
298
		pr, err := dht.peerFromInfo(pb)
299
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
300
			log.Error(err)
301 302
			continue
		}
303
		peers = append(peers, pr)
304
	}
305 306

	if len(peers) > 0 {
307
		log.Debug("getValueOrPeers: peers")
308 309 310
		return nil, peers, nil
	}

311 312
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
313 314
}

315
// getValueSingle simply performs the get value RPC with the given parameters
316
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.Peer,
317
	key u.Key, level int) (*pb.Message, error) {
318

319
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), level)
320
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
321 322
}

323 324 325 326
// 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?
327
func (dht *IpfsDHT) getFromPeerList(ctx context.Context, key u.Key,
328
	peerlist []*pb.Message_Peer, level int) ([]byte, error) {
329

330
	for _, pinfo := range peerlist {
331
		p, err := dht.ensureConnectedToPeer(ctx, pinfo)
332
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
333
			log.Errorf("getFromPeers error: %s", err)
334
			continue
Jeromy's avatar
Jeromy committed
335
		}
336 337

		pmes, err := dht.getValueSingle(ctx, p, key, level)
Jeromy's avatar
Jeromy committed
338
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
339
			log.Errorf("getFromPeers error: %s\n", err)
Jeromy's avatar
Jeromy committed
340 341 342
			continue
		}

343
		if record := pmes.GetRecord(); record != nil {
344
			// Success! We were given the value
345 346 347 348 349

			err := dht.verifyRecord(record)
			if err != nil {
				return nil, err
			}
350
			dht.providers.AddProvider(key, p)
351
			return record.GetValue(), nil
352
		}
Jeromy's avatar
Jeromy committed
353
	}
354
	return nil, routing.ErrNotFound
Jeromy's avatar
Jeromy committed
355 356
}

357
// getLocal attempts to retrieve the value from the datastore
358
func (dht *IpfsDHT) getLocal(key u.Key) ([]byte, error) {
359 360
	dht.dslock.Lock()
	defer dht.dslock.Unlock()
Jeromy's avatar
Jeromy committed
361
	log.Debug("getLocal %s", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
362
	v, err := dht.datastore.Get(key.DsKey())
363 364 365
	if err != nil {
		return nil, err
	}
Jeromy's avatar
Jeromy committed
366
	log.Debug("found in db")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
367 368 369

	byt, ok := v.([]byte)
	if !ok {
370
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
371
	}
372 373 374 375 376 377 378 379 380 381
	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
382
			log.Errorf("local record verify failed: %s", err)
383 384 385 386 387
			return nil, err
		}
	}

	return rec.GetValue(), nil
388 389
}

390
// putLocal stores the key value pair in the datastore
391
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
392 393 394 395 396 397 398 399 400 401
	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)
402
}
403

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
404 405
// Update signals to all routingTables to Update their last-seen status
// on the given peer.
406
func (dht *IpfsDHT) Update(p peer.Peer) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
407
	log.Debugf("updating peer: %s latency = %f\n", p, p.GetLatency().Seconds())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
408
	removedCount := 0
409
	for _, route := range dht.routingTables {
410
		removed := route.Update(p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
411
		// Only close the connection if no tables refer to this peer
412
		if removed != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
413
			removedCount++
414
		}
415
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
416 417 418 419 420 421 422 423

	// Only close the connection if no tables refer to this peer
	// if removedCount == len(dht.routingTables) {
	// 	dht.network.ClosePeer(p)
	// }
	// ACTUALLY, no, let's not just close the connection. it may be connected
	// due to other things. it seems that we just need connection timeouts
	// after some deadline of inactivity.
424
}
Jeromy's avatar
Jeromy committed
425

Jeromy's avatar
Jeromy committed
426
// FindLocal looks for a peer with a given ID connected to this dht and returns the peer and the table it was found in.
427
func (dht *IpfsDHT) FindLocal(id peer.ID) (peer.Peer, *kb.RoutingTable) {
428
	for _, table := range dht.routingTables {
Jeromy's avatar
Jeromy committed
429 430 431 432 433 434 435
		p := table.Find(id)
		if p != nil {
			return p, table
		}
	}
	return nil, nil
}
436

Jeromy's avatar
Jeromy committed
437
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
438 439
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.Peer, id peer.ID, level int) (*pb.Message, error) {
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), level)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
440
	return dht.sendRequest(ctx, p, pmes)
441
}
442

443 444
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.Peer, key u.Key, level int) (*pb.Message, error) {
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), level)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
445
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
446 447
}

448
func (dht *IpfsDHT) addProviders(key u.Key, peers []*pb.Message_Peer) []peer.Peer {
449
	var provArr []peer.Peer
Jeromy's avatar
Jeromy committed
450
	for _, prov := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
451 452
		p, err := dht.peerFromInfo(prov)
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
453
			log.Errorf("error getting peer from info: %v", err)
Jeromy's avatar
Jeromy committed
454 455
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
456

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
457
		log.Debugf("%s adding provider: %s for %s", dht.self, p, key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
458

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
459
		// Dont add outselves to the list
460
		if p.ID().Equal(dht.self.ID()) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
461
			continue
Jeromy's avatar
Jeromy committed
462
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
463 464

		// TODO(jbenet) ensure providers is idempotent
465
		dht.providers.AddProvider(key, p)
466
		provArr = append(provArr, p)
Jeromy's avatar
Jeromy committed
467
	}
468
	return provArr
Jeromy's avatar
Jeromy committed
469
}
Jeromy's avatar
Jeromy committed
470

471
// nearestPeersToQuery returns the routing tables closest peers.
472
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.Peer {
473 474 475 476
	level := pmes.GetClusterLevel()
	cluster := dht.routingTables[level]

	key := u.Key(pmes.GetKey())
477
	closer := cluster.NearestPeers(kb.ConvertKey(key), count)
478 479 480
	return closer
}

481
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
482
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, count int) []peer.Peer {
483
	closer := dht.nearestPeersToQuery(pmes, count)
484 485 486 487 488 489

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

490 491
	// == to self? thats bad
	for _, p := range closer {
492
		if p.ID().Equal(dht.self.ID()) {
493 494 495
			log.Error("Attempted to return self! this shouldnt happen...")
			return nil
		}
496 497
	}

498
	var filtered []peer.Peer
499 500 501
	for _, p := range closer {
		// must all be closer than self
		key := u.Key(pmes.GetKey())
502
		if !kb.Closer(dht.self.ID(), p.ID(), key) {
503 504
			filtered = append(filtered, p)
		}
505 506
	}

507 508
	// ok seems like closer nodes
	return filtered
509 510
}

Jeromy's avatar
Jeromy committed
511
// getPeer searches the peerstore for a peer with the given peer ID
512
func (dht *IpfsDHT) getPeer(id peer.ID) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
513 514 515
	p, err := dht.peerstore.Get(id)
	if err != nil {
		err = fmt.Errorf("Failed to get peer from peerstore: %s", err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
516
		log.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
517 518 519 520 521
		return nil, err
	}
	return p, nil
}

Jeromy's avatar
Jeromy committed
522 523
// peerFromInfo returns a peer using info in the protobuf peer struct
// to lookup or create a peer
524
func (dht *IpfsDHT) peerFromInfo(pbp *pb.Message_Peer) (peer.Peer, error) {
525 526

	id := peer.ID(pbp.GetId())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
527

528 529
	// bail out if it's ourselves
	//TODO(jbenet) not sure this should be an error _here_
530
	if id.Equal(dht.self.ID()) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
531 532 533
		return nil, errors.New("found self")
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
534 535 536
	p, err := dht.getPeer(id)
	if err != nil {
		return nil, err
537 538
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
539 540 541
	maddr, err := pbp.Address()
	if err != nil {
		return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
542
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
543
	p.AddAddress(maddr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
544 545 546
	return p, nil
}

547
func (dht *IpfsDHT) ensureConnectedToPeer(ctx context.Context, pbp *pb.Message_Peer) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
548 549 550
	p, err := dht.peerFromInfo(pbp)
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
551 552
	}

553
	// dial connection
554
	err = dht.dialer.DialPeer(ctx, p)
555
	return p, err
Jeromy's avatar
Jeromy committed
556
}
557

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
558
//TODO: this should be smarter about which keys it selects.
559
func (dht *IpfsDHT) loadProvidableKeys() error {
560 561 562 563
	kl, err := dht.datastore.KeyList()
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
564 565 566
	for _, dsk := range kl {
		k := u.KeyFromDsKey(dsk)
		if len(k) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
567
			log.Errorf("loadProvidableKeys error: %v", dsk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
568 569 570
		}

		dht.providers.AddProvider(k, dht.self)
571 572 573 574
	}
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
575
// PingRoutine periodically pings nearest neighbors.
576
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
577 578
	defer dht.Children().Done()

579 580 581 582 583 584 585 586
	tick := time.Tick(t)
	for {
		select {
		case <-tick:
			id := make([]byte, 16)
			rand.Read(id)
			peers := dht.routingTables[0].NearestPeers(kb.ConvertKey(u.Key(id)), 5)
			for _, p := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
587
				ctx, _ := context.WithTimeout(dht.Context(), time.Second*5)
588 589
				err := dht.Ping(ctx, p)
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
590
					log.Errorf("Ping error: %s", err)
591 592
				}
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
593
		case <-dht.Closing():
594 595 596 597 598
			return
		}
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
599
// Bootstrap builds up list of peers by requesting random peer IDs
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
600
func (dht *IpfsDHT) Bootstrap(ctx context.Context) {
601 602
	id := make([]byte, 16)
	rand.Read(id)
Jeromy's avatar
Jeromy committed
603 604 605 606
	p, err := dht.FindPeer(ctx, peer.ID(id))
	if err != nil {
		log.Error("Bootstrap peer error: %s", err)
	}
607
	err = dht.dialer.DialPeer(ctx, p)
608
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
609
		log.Errorf("Bootstrap peer error: %s", err)
610
	}
611
}