dht.go 14 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
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
Jeromy's avatar
Jeromy committed
15
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
16
	u "github.com/jbenet/go-ipfs/util"
17

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

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

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

26
const doPinging = false
27

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

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

Jeromy's avatar
Jeromy committed
41
	// Local peer (yourself)
42
	self peer.Peer
Jeromy's avatar
Jeromy committed
43

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

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

51
	providers *ProviderManager
52

53 54
	// When this peer started up
	birth time.Time
55 56 57

	//lock to make diagnostics work better
	diaglock sync.Mutex
58 59

	ctx context.Context
60 61
}

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

72
	dht.providers = NewProviderManager(p.ID())
73

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

80 81 82
	if doPinging {
		go dht.PingRoutine(time.Second * 10)
	}
Jeromy's avatar
Jeromy committed
83
	return dht
84 85
}

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

	// 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
99
	err := dht.dialer.DialPeer(npeer)
100
	if err != nil {
101
		return nil, err
102 103
	}

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

111 112
	dht.Update(npeer)

113
	return npeer, nil
Jeromy's avatar
Jeromy committed
114 115
}

116
// HandleMessage implements the inet.Handler interface.
117
func (dht *IpfsDHT) HandleMessage(ctx context.Context, mes msg.NetMessage) msg.NetMessage {
118 119 120

	mData := mes.Data()
	if mData == nil {
121
		log.Error("Message contained nil data.")
122
		return nil
123 124 125 126
	}

	mPeer := mes.Peer()
	if mPeer == nil {
127
		log.Error("Message contained nil peer.")
128
		return nil
129 130 131
	}

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

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

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

	// get handler for this msg type.
	handler := dht.handlerForMsgType(pmes.GetType())
	if handler == nil {
149
		log.Error("got back nil handler from handlerForMsgType")
150
		return nil
151 152 153 154 155
	}

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

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

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

173
	return rmes
174 175
}

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

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

	start := time.Now()

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

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

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

202
	rpmes := new(pb.Message)
203 204 205 206 207 208 209
	if err := proto.Unmarshal(rmes.Data(), rpmes); err != nil {
		return nil, err
	}

	return rpmes, nil
}

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

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

	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
225 226
}

227
func (dht *IpfsDHT) putProvider(ctx context.Context, p peer.Peer, key string) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
228

229
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
230 231

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235 236 237
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239
	log.Debugf("%s putProvider: %s for %s", dht.self, p, key)
240
	if rpmes.GetKey() != pmes.GetKey() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241 242 243 244
		return errors.New("provider not added correctly")
	}

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245 246
}

247 248
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.Peer,
	key u.Key, level int) ([]byte, []peer.Peer, error) {
249 250

	pmes, err := dht.getValueSingle(ctx, p, key, level)
251
	if err != nil {
252
		return nil, nil, err
253 254
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
255
	log.Debugf("pmes.GetValue() %v", pmes.GetValue())
256
	if value := pmes.GetValue(); value != nil {
257
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
258
		log.Debug("getValueOrPeers: got value")
259
		return value, nil, nil
260
	}
261

262
	// TODO decide on providers. This probably shouldn't be happening.
263 264 265 266 267
	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
268
		log.Debug("getValueOrPeers: get from providers")
269 270
		return val, nil, nil
	}
271 272

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

	if len(peers) > 0 {
284
		log.Debug("getValueOrPeers: peers")
285 286 287
		return nil, peers, nil
	}

Jeromy's avatar
Jeromy committed
288
	log.Warning("getValueOrPeers: u.ErrNotFound")
289
	return nil, nil, u.ErrNotFound
290 291
}

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

296
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), level)
297
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
298 299
}

300 301 302 303
// 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?
304
func (dht *IpfsDHT) getFromPeerList(ctx context.Context, key u.Key,
305
	peerlist []*pb.Message_Peer, level int) ([]byte, error) {
306

307
	for _, pinfo := range peerlist {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
308
		p, err := dht.ensureConnectedToPeer(pinfo)
309
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
310
			log.Errorf("getFromPeers error: %s", err)
311
			continue
Jeromy's avatar
Jeromy committed
312
		}
313 314

		pmes, err := dht.getValueSingle(ctx, p, key, level)
Jeromy's avatar
Jeromy committed
315
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
316
			log.Errorf("getFromPeers error: %s\n", err)
Jeromy's avatar
Jeromy committed
317 318 319
			continue
		}

320 321 322 323
		if value := pmes.GetValue(); value != nil {
			// Success! We were given the value
			dht.providers.AddProvider(key, p)
			return value, nil
324
		}
Jeromy's avatar
Jeromy committed
325 326 327 328
	}
	return nil, u.ErrNotFound
}

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

	byt, ok := v.([]byte)
	if !ok {
340
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
341 342
	}
	return byt, nil
343 344
}

345
// putLocal stores the key value pair in the datastore
346
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
347
	return dht.datastore.Put(key.DsKey(), value)
348
}
349

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

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

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

383 384
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
385
	return dht.sendRequest(ctx, p, pmes)
386
}
387

388 389
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
390
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
391 392
}

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
404
		// Dont add outselves to the list
405
		if p.ID().Equal(dht.self.ID()) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
406
			continue
Jeromy's avatar
Jeromy committed
407
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
408 409

		// TODO(jbenet) ensure providers is idempotent
410
		dht.providers.AddProvider(key, p)
411
		provArr = append(provArr, p)
Jeromy's avatar
Jeromy committed
412
	}
413
	return provArr
Jeromy's avatar
Jeromy committed
414
}
Jeromy's avatar
Jeromy committed
415

416
// nearestPeersToQuery returns the routing tables closest peers.
417
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.Peer {
418 419 420 421
	level := pmes.GetClusterLevel()
	cluster := dht.routingTables[level]

	key := u.Key(pmes.GetKey())
422
	closer := cluster.NearestPeers(kb.ConvertKey(key), count)
423 424 425
	return closer
}

426
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
427
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, count int) []peer.Peer {
428
	closer := dht.nearestPeersToQuery(pmes, count)
429 430 431 432 433 434

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

435 436
	// == to self? thats bad
	for _, p := range closer {
437
		if p.ID().Equal(dht.self.ID()) {
438 439 440
			log.Error("Attempted to return self! this shouldnt happen...")
			return nil
		}
441 442
	}

443
	var filtered []peer.Peer
444 445 446
	for _, p := range closer {
		// must all be closer than self
		key := u.Key(pmes.GetKey())
447
		if !kb.Closer(dht.self.ID(), p.ID(), key) {
448 449
			filtered = append(filtered, p)
		}
450 451
	}

452 453
	// ok seems like closer nodes
	return filtered
454 455
}

456
func (dht *IpfsDHT) getPeer(id peer.ID) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
457 458 459
	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
460
		log.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
461 462 463 464 465
		return nil, err
	}
	return p, nil
}

466
func (dht *IpfsDHT) peerFromInfo(pbp *pb.Message_Peer) (peer.Peer, error) {
467 468

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

470 471
	// bail out if it's ourselves
	//TODO(jbenet) not sure this should be an error _here_
472
	if id.Equal(dht.self.ID()) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
473 474 475
		return nil, errors.New("found self")
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
476 477 478
	p, err := dht.getPeer(id)
	if err != nil {
		return nil, err
479 480
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
481 482 483
	maddr, err := pbp.Address()
	if err != nil {
		return nil, err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
484
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
485
	p.AddAddress(maddr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
486 487 488
	return p, nil
}

489
func (dht *IpfsDHT) ensureConnectedToPeer(pbp *pb.Message_Peer) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
490 491 492
	p, err := dht.peerFromInfo(pbp)
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
493 494
	}

495
	// dial connection
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
496
	err = dht.dialer.DialPeer(p)
497
	return p, err
Jeromy's avatar
Jeromy committed
498
}
499

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
500
//TODO: this should be smarter about which keys it selects.
501
func (dht *IpfsDHT) loadProvidableKeys() error {
502 503 504 505
	kl, err := dht.datastore.KeyList()
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
506 507 508
	for _, dsk := range kl {
		k := u.KeyFromDsKey(dsk)
		if len(k) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
509
			log.Errorf("loadProvidableKeys error: %v", dsk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
510 511 512
		}

		dht.providers.AddProvider(k, dht.self)
513 514 515 516
	}
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
517
// PingRoutine periodically pings nearest neighbors.
518 519 520 521 522 523 524 525 526 527 528 529
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
	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 {
				ctx, _ := context.WithTimeout(dht.ctx, time.Second*5)
				err := dht.Ping(ctx, p)
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
530
					log.Errorf("Ping error: %s", err)
531 532 533 534 535 536 537 538
				}
			}
		case <-dht.ctx.Done():
			return
		}
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
539
// Bootstrap builds up list of peers by requesting random peer IDs
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
540
func (dht *IpfsDHT) Bootstrap(ctx context.Context) {
541 542
	id := make([]byte, 16)
	rand.Read(id)
Jeromy's avatar
Jeromy committed
543 544 545 546 547
	p, err := dht.FindPeer(ctx, peer.ID(id))
	if err != nil {
		log.Error("Bootstrap peer error: %s", err)
	}
	err = dht.dialer.DialPeer(p)
548
	if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
549
		log.Errorf("Bootstrap peer error: %s", err)
550
	}
551
}