dht.go 14.6 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2
package dht

3
import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4
	"bytes"
5
	"crypto/rand"
6
	"errors"
7
	"fmt"
8 9
	"sync"
	"time"
10

11
	inet "github.com/jbenet/go-ipfs/net"
12
	msg "github.com/jbenet/go-ipfs/net/message"
13
	peer "github.com/jbenet/go-ipfs/peer"
14
	routing "github.com/jbenet/go-ipfs/routing"
15
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
Jeromy's avatar
Jeromy committed
16
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
17
	u "github.com/jbenet/go-ipfs/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18
	ctxc "github.com/jbenet/go-ipfs/util/ctxcloser"
19

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

23
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
24 25
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26
var log = u.Logger("dht")
27

28
const doPinging = false
29

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39 40 41
	// the network services we need
	dialer inet.Dialer
	sender inet.Sender
42

Jeromy's avatar
Jeromy committed
43
	// Local peer (yourself)
44
	self peer.Peer
Jeromy's avatar
Jeromy committed
45

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47 48
	// Other peers
	peerstore peer.Peerstore

Jeromy's avatar
Jeromy committed
49 50
	// Local data
	datastore ds.Datastore
51
	dslock    sync.Mutex
52

53
	providers *ProviderManager
54

55 56
	// When this peer started up
	birth time.Time
57 58 59

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
61
	ctxc.ContextCloser
62 63
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74 75
	dht.providers = NewProviderManager(dht.Context(), p.ID())
	dht.AddCloserChild(dht.providers)
76

77
	dht.routingTables = make([]*kb.RoutingTable, 3)
78 79 80
	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)
81
	dht.birth = time.Now()
82

83
	if doPinging {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84
		dht.Children().Add(1)
85 86
		go dht.PingRoutine(time.Second * 10)
	}
Jeromy's avatar
Jeromy committed
87
	return dht
88 89
}

90
// Connect to a new peer at the given address, ping and add to the routing table
91
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.Peer) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92
	log.Debugf("Connect to new peer: %s", npeer)
93 94 95 96 97 98 99 100 101 102

	// 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
	//
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103
	err := dht.dialer.DialPeer(npeer)
104
	if err != nil {
105
		return nil, err
106 107
	}

Jeromy's avatar
Jeromy committed
108 109
	// Ping new peer to register in their routing table
	// NOTE: this should be done better...
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110
	err = dht.Ping(ctx, npeer)
Jeromy's avatar
Jeromy committed
111
	if err != nil {
112
		return nil, fmt.Errorf("failed to ping newly connected peer: %s\n", err)
Jeromy's avatar
Jeromy committed
113 114
	}

115 116
	dht.Update(npeer)

117
	return npeer, nil
Jeromy's avatar
Jeromy committed
118 119
}

120
// HandleMessage implements the inet.Handler interface.
121
func (dht *IpfsDHT) HandleMessage(ctx context.Context, mes msg.NetMessage) msg.NetMessage {
122 123 124

	mData := mes.Data()
	if mData == nil {
125
		log.Error("Message contained nil data.")
126
		return nil
127 128 129 130
	}

	mPeer := mes.Peer()
	if mPeer == nil {
131
		log.Error("Message contained nil peer.")
132
		return nil
133 134 135
	}

	// deserialize msg
136
	pmes := new(pb.Message)
137 138
	err := proto.Unmarshal(mData, pmes)
	if err != nil {
139
		log.Error("Error unmarshaling data")
140
		return nil
141 142 143 144 145 146
	}

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

	// Print out diagnostic
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
147
	log.Debugf("%s got message type: '%s' from %s",
148
		dht.self, pb.Message_MessageType_name[int32(pmes.GetType())], mPeer)
149 150 151 152

	// get handler for this msg type.
	handler := dht.handlerForMsgType(pmes.GetType())
	if handler == nil {
153
		log.Error("got back nil handler from handlerForMsgType")
154
		return nil
155 156 157 158 159
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164 165
	// if nil response, return it before serializing
	if rpmes == nil {
166
		log.Warning("Got back nil response from request.")
167
		return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168 169
	}

170 171 172
	// serialize response msg
	rmes, err := msg.FromObject(mPeer, rpmes)
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173
		log.Errorf("serialze response error: %s", err)
174
		return nil
175 176
	}

177
	return rmes
178 179
}

180 181
// sendRequest sends out a request using dht.sender, but also makes sure to
// measure the RTT for latency measurements.
182
func (dht *IpfsDHT) sendRequest(ctx context.Context, p peer.Peer, pmes *pb.Message) (*pb.Message, error) {
183 184 185 186 187 188 189 190

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

	start := time.Now()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
191
	// Print out diagnostic
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192
	log.Debugf("Sent message type: '%s' to %s",
193
		pb.Message_MessageType_name[int32(pmes.GetType())], p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194

195 196 197 198
	rmes, err := dht.sender.SendRequest(ctx, mes)
	if err != nil {
		return nil, err
	}
199 200 201
	if rmes == nil {
		return nil, errors.New("no response to request")
	}
202 203 204 205

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

206
	rpmes := new(pb.Message)
207 208 209 210 211 212 213
	if err := proto.Unmarshal(rmes.Data(), rpmes); err != nil {
		return nil, err
	}

	return rpmes, nil
}

214
// putValueToNetwork stores the given key/value pair at the peer 'p'
215
func (dht *IpfsDHT) putValueToNetwork(ctx context.Context, p peer.Peer,
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
216 217
	key string, value []byte) error {

218
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219
	pmes.Value = value
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221 222 223
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224 225 226 227 228

	if !bytes.Equal(rpmes.Value, pmes.Value) {
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
229 230
}

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

235
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
236 237

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
240
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241 242 243
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244

245
	log.Debugf("%s putProvider: %s for %s", dht.self, p, u.Key(key))
246
	if rpmes.GetKey() != pmes.GetKey() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247 248 249 250
		return errors.New("provider not added correctly")
	}

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
251 252
}

253 254
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.Peer,
	key u.Key, level int) ([]byte, []peer.Peer, error) {
255 256

	pmes, err := dht.getValueSingle(ctx, p, key, level)
257
	if err != nil {
258
		return nil, nil, err
259 260
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261
	log.Debugf("pmes.GetValue() %v", pmes.GetValue())
262
	if value := pmes.GetValue(); value != nil {
263
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
264
		log.Debug("getValueOrPeers: got value")
265
		return value, nil, nil
266
	}
267

268
	// TODO decide on providers. This probably shouldn't be happening.
269 270 271 272 273
	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
274
		log.Debug("getValueOrPeers: get from providers")
275 276
		return val, nil, nil
	}
277 278

	// Perhaps we were given closer peers
279
	var peers []peer.Peer
280
	for _, pb := range pmes.GetCloserPeers() {
281
		pr, err := dht.peerFromInfo(pb)
282
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283
			log.Error(err)
284 285
			continue
		}
286
		peers = append(peers, pr)
287
	}
288 289

	if len(peers) > 0 {
290
		log.Debug("getValueOrPeers: peers")
291 292 293
		return nil, peers, nil
	}

294 295
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
296 297
}

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

302
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), level)
303
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
304 305
}

306 307 308 309
// 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?
310
func (dht *IpfsDHT) getFromPeerList(ctx context.Context, key u.Key,
311
	peerlist []*pb.Message_Peer, level int) ([]byte, error) {
312

313
	for _, pinfo := range peerlist {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
314
		p, err := dht.ensureConnectedToPeer(pinfo)
315
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
316
			log.Errorf("getFromPeers error: %s", err)
317
			continue
Jeromy's avatar
Jeromy committed
318
		}
319 320

		pmes, err := dht.getValueSingle(ctx, p, key, level)
Jeromy's avatar
Jeromy committed
321
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
322
			log.Errorf("getFromPeers error: %s\n", err)
Jeromy's avatar
Jeromy committed
323 324 325
			continue
		}

326 327 328 329
		if value := pmes.GetValue(); value != nil {
			// Success! We were given the value
			dht.providers.AddProvider(key, p)
			return value, nil
330
		}
Jeromy's avatar
Jeromy committed
331
	}
332
	return nil, routing.ErrNotFound
Jeromy's avatar
Jeromy committed
333 334
}

335
// getLocal attempts to retrieve the value from the datastore
336
func (dht *IpfsDHT) getLocal(key u.Key) ([]byte, error) {
337 338
	dht.dslock.Lock()
	defer dht.dslock.Unlock()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
339
	v, err := dht.datastore.Get(key.DsKey())
340 341 342
	if err != nil {
		return nil, err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
343 344 345

	byt, ok := v.([]byte)
	if !ok {
346
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
347 348
	}
	return byt, nil
349 350
}

351
// putLocal stores the key value pair in the datastore
352
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
353
	return dht.datastore.Put(key.DsKey(), value)
354
}
355

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
356 357
// Update signals to all routingTables to Update their last-seen status
// on the given peer.
358
func (dht *IpfsDHT) Update(p peer.Peer) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
359
	log.Debugf("updating peer: %s latency = %f\n", p, p.GetLatency().Seconds())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
360
	removedCount := 0
361
	for _, route := range dht.routingTables {
362
		removed := route.Update(p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
363
		// Only close the connection if no tables refer to this peer
364
		if removed != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
365
			removedCount++
366
		}
367
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
368 369 370 371 372 373 374 375

	// 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.
376
}
Jeromy's avatar
Jeromy committed
377

Jeromy's avatar
Jeromy committed
378
// FindLocal looks for a peer with a given ID connected to this dht and returns the peer and the table it was found in.
379
func (dht *IpfsDHT) FindLocal(id peer.ID) (peer.Peer, *kb.RoutingTable) {
380
	for _, table := range dht.routingTables {
Jeromy's avatar
Jeromy committed
381 382 383 384 385 386 387
		p := table.Find(id)
		if p != nil {
			return p, table
		}
	}
	return nil, nil
}
388

Jeromy's avatar
Jeromy committed
389
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
390 391
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
392
	return dht.sendRequest(ctx, p, pmes)
393
}
394

395 396
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
397
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
398 399
}

400
func (dht *IpfsDHT) addProviders(key u.Key, peers []*pb.Message_Peer) []peer.Peer {
401
	var provArr []peer.Peer
Jeromy's avatar
Jeromy committed
402
	for _, prov := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
403 404
		p, err := dht.peerFromInfo(prov)
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
405
			log.Errorf("error getting peer from info: %v", err)
Jeromy's avatar
Jeromy committed
406 407
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
408

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
411
		// Dont add outselves to the list
412
		if p.ID().Equal(dht.self.ID()) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
413
			continue
Jeromy's avatar
Jeromy committed
414
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
415 416

		// TODO(jbenet) ensure providers is idempotent
417
		dht.providers.AddProvider(key, p)
418
		provArr = append(provArr, p)
Jeromy's avatar
Jeromy committed
419
	}
420
	return provArr
Jeromy's avatar
Jeromy committed
421
}
Jeromy's avatar
Jeromy committed
422

423
// nearestPeersToQuery returns the routing tables closest peers.
424
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.Peer {
425 426 427 428
	level := pmes.GetClusterLevel()
	cluster := dht.routingTables[level]

	key := u.Key(pmes.GetKey())
429
	closer := cluster.NearestPeers(kb.ConvertKey(key), count)
430 431 432
	return closer
}

433
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
434
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, count int) []peer.Peer {
435
	closer := dht.nearestPeersToQuery(pmes, count)
436 437 438 439 440 441

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

442 443
	// == to self? thats bad
	for _, p := range closer {
444
		if p.ID().Equal(dht.self.ID()) {
445 446 447
			log.Error("Attempted to return self! this shouldnt happen...")
			return nil
		}
448 449
	}

450
	var filtered []peer.Peer
451 452 453
	for _, p := range closer {
		// must all be closer than self
		key := u.Key(pmes.GetKey())
454
		if !kb.Closer(dht.self.ID(), p.ID(), key) {
455 456
			filtered = append(filtered, p)
		}
457 458
	}

459 460
	// ok seems like closer nodes
	return filtered
461 462
}

Jeromy's avatar
Jeromy committed
463
// getPeer searches the peerstore for a peer with the given peer ID
464
func (dht *IpfsDHT) getPeer(id peer.ID) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
465 466 467
	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
468
		log.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
469 470 471 472 473
		return nil, err
	}
	return p, nil
}

Jeromy's avatar
Jeromy committed
474 475
// peerFromInfo returns a peer using info in the protobuf peer struct
// to lookup or create a peer
476
func (dht *IpfsDHT) peerFromInfo(pbp *pb.Message_Peer) (peer.Peer, error) {
477 478

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

480 481
	// bail out if it's ourselves
	//TODO(jbenet) not sure this should be an error _here_
482
	if id.Equal(dht.self.ID()) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
483 484 485
		return nil, errors.New("found self")
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
486 487 488
	p, err := dht.getPeer(id)
	if err != nil {
		return nil, err
489 490
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
491 492 493
	maddr, err := pbp.Address()
	if err != nil {
		return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
494
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
495
	p.AddAddress(maddr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
496 497 498
	return p, nil
}

499
func (dht *IpfsDHT) ensureConnectedToPeer(pbp *pb.Message_Peer) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
500 501 502
	p, err := dht.peerFromInfo(pbp)
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
503 504
	}

505
	// dial connection
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
506
	err = dht.dialer.DialPeer(p)
507
	return p, err
Jeromy's avatar
Jeromy committed
508
}
509

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
510
//TODO: this should be smarter about which keys it selects.
511
func (dht *IpfsDHT) loadProvidableKeys() error {
512 513 514 515
	kl, err := dht.datastore.KeyList()
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
516 517 518
	for _, dsk := range kl {
		k := u.KeyFromDsKey(dsk)
		if len(k) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
519
			log.Errorf("loadProvidableKeys error: %v", dsk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
520 521 522
		}

		dht.providers.AddProvider(k, dht.self)
523 524 525 526
	}
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
527
// PingRoutine periodically pings nearest neighbors.
528
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
529 530
	defer dht.Children().Done()

531 532 533 534 535 536 537 538
	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
539
				ctx, _ := context.WithTimeout(dht.Context(), time.Second*5)
540 541
				err := dht.Ping(ctx, p)
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
542
					log.Errorf("Ping error: %s", err)
543 544
				}
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
545
		case <-dht.Closing():
546 547 548 549 550
			return
		}
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
551
// Bootstrap builds up list of peers by requesting random peer IDs
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
552
func (dht *IpfsDHT) Bootstrap(ctx context.Context) {
553 554
	id := make([]byte, 16)
	rand.Read(id)
Jeromy's avatar
Jeromy committed
555 556 557 558 559
	p, err := dht.FindPeer(ctx, peer.ID(id))
	if err != nil {
		log.Error("Bootstrap peer error: %s", err)
	}
	err = dht.dialer.DialPeer(p)
560
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
561
		log.Errorf("Bootstrap peer error: %s", err)
562
	}
563
}