dht.go 15.7 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

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

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

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

30
const doPinging = false
31

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

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

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

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

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

55
	providers *ProviderManager
56

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

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

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

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

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

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

82
	dht.routingTables = make([]*kb.RoutingTable, 3)
83 84 85
	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)
86
	dht.birth = time.Now()
87

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

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

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

	// 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
	//
111
	err := dht.dialer.DialPeer(ctx, npeer)
112
	if err != nil {
113
		return nil, err
114 115
	}

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

123 124
	dht.Update(npeer)

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

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

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

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

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

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

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

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

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

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

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

185
	return rmes
186 187
}

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

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

	start := time.Now()

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

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

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

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

	return rpmes, nil
}

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

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

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

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

243
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
244 245

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

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

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

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
259 260
}

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

	pmes, err := dht.getValueSingle(ctx, p, key, level)
265
	if err != nil {
266
		return nil, nil, err
267 268
	}

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

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

282
	// TODO decide on providers. This probably shouldn't be happening.
283 284 285 286 287
	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
288
		log.Debug("getValueOrPeers: get from providers")
289 290
		return val, nil, nil
	}
291 292

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

	if len(peers) > 0 {
304
		log.Debug("getValueOrPeers: peers")
305 306 307
		return nil, peers, nil
	}

308 309
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
310 311
}

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

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

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

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

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

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

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

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

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

	return rec.GetValue(), nil
385 386
}

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

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

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

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

Jeromy's avatar
Jeromy committed
434
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
435 436
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
437
	return dht.sendRequest(ctx, p, pmes)
438
}
439

440 441
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
442
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
443 444
}

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

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

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

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

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

	key := u.Key(pmes.GetKey())
474
	closer := cluster.NearestPeers(kb.ConvertKey(key), count)
475 476 477
	return closer
}

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

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

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

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

504 505
	// ok seems like closer nodes
	return filtered
506 507
}

Jeromy's avatar
Jeromy committed
508
// getPeer searches the peerstore for a peer with the given peer ID
509
func (dht *IpfsDHT) getPeer(id peer.ID) (peer.Peer, error) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
510 511 512
	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
513
		log.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
514 515 516 517 518
		return nil, err
	}
	return p, nil
}

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

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

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

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

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

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

550
	// dial connection
551
	err = dht.dialer.DialPeer(ctx, p)
552
	return p, err
Jeromy's avatar
Jeromy committed
553
}
554

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

		dht.providers.AddProvider(k, dht.self)
568 569 570 571
	}
	return nil
}

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

576 577 578 579 580 581 582 583
	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
584
				ctx, _ := context.WithTimeout(dht.Context(), time.Second*5)
585 586
				err := dht.Ping(ctx, p)
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
587
					log.Errorf("Ping error: %s", err)
588 589
				}
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
590
		case <-dht.Closing():
591 592 593 594 595
			return
		}
	}
}

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