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

3
import (
4
	"bytes"
5 6 7
	"errors"
	"sync"
	"time"
8

9
	peer "github.com/jbenet/go-ipfs/peer"
Jeromy's avatar
Jeromy committed
10
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
11 12
	swarm "github.com/jbenet/go-ipfs/swarm"
	u "github.com/jbenet/go-ipfs/util"
13 14

	ma "github.com/jbenet/go-multiaddr"
Jeromy's avatar
Jeromy committed
15 16 17

	ds "github.com/jbenet/datastore.go"

18
	"code.google.com/p/goprotobuf/proto"
19 20
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21 22 23 24 25
// 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 {
26 27
	// Array of routing tables for differently distanced nodes
	// NOTE: (currently, only a single table is used)
28
	routingTables []*kb.RoutingTable
29

30
	network swarm.Network
31

Jeromy's avatar
Jeromy committed
32 33 34 35 36
	// Local peer (yourself)
	self *peer.Peer

	// Local data
	datastore ds.Datastore
37
	dslock    sync.Mutex
38

39
	// Map keys to peers that can provide their value
40
	providers    map[u.Key][]*providerInfo
41
	providerLock sync.RWMutex
42

43 44
	// Signal to shutdown dht
	shutdown chan struct{}
45 46 47

	// When this peer started up
	birth time.Time
48 49 50

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

52
	// listener is a server to register to listen for responses to messages
53
	listener *mesListener
54 55
}

Jeromy's avatar
Jeromy committed
56
// NewDHT creates a new DHT object with the given peer as the 'local' host
Jeromy's avatar
Jeromy committed
57
func NewDHT(p *peer.Peer, net swarm.Network) *IpfsDHT {
58
	dht := new(IpfsDHT)
Jeromy's avatar
Jeromy committed
59
	dht.network = net
60 61
	dht.datastore = ds.NewMapDatastore()
	dht.self = p
62
	dht.providers = make(map[u.Key][]*providerInfo)
Jeromy's avatar
Jeromy committed
63
	dht.shutdown = make(chan struct{})
64

65 66 67 68 69
	dht.routingTables = make([]*kb.RoutingTable, 3)
	dht.routingTables[0] = kb.NewRoutingTable(20, kb.ConvertPeerID(p.ID), time.Millisecond*30)
	dht.routingTables[1] = kb.NewRoutingTable(20, kb.ConvertPeerID(p.ID), time.Millisecond*100)
	dht.routingTables[2] = kb.NewRoutingTable(20, kb.ConvertPeerID(p.ID), time.Hour)
	dht.listener = newMesListener()
70
	dht.birth = time.Now()
Jeromy's avatar
Jeromy committed
71
	return dht
72 73
}

74
// Start up background goroutines needed by the DHT
75 76 77 78
func (dht *IpfsDHT) Start() {
	go dht.handleMessages()
}

79
// Connect to a new peer at the given address, ping and add to the routing table
80
func (dht *IpfsDHT) Connect(addr *ma.Multiaddr) (*peer.Peer, error) {
81
	maddrstr, _ := addr.String()
82
	u.DOut("Connect to new peer: %s\n", maddrstr)
83
	npeer, err := dht.network.ConnectNew(addr)
84
	if err != nil {
85
		return nil, err
86 87
	}

Jeromy's avatar
Jeromy committed
88 89
	// Ping new peer to register in their routing table
	// NOTE: this should be done better...
90
	err = dht.Ping(npeer, time.Second*2)
Jeromy's avatar
Jeromy committed
91
	if err != nil {
Jeromy's avatar
Jeromy committed
92
		return nil, errors.New("failed to ping newly connected peer")
Jeromy's avatar
Jeromy committed
93 94
	}

95 96
	dht.Update(npeer)

97
	return npeer, nil
Jeromy's avatar
Jeromy committed
98 99
}

100 101
// Read in all messages from swarm and handle them appropriately
// NOTE: this function is just a quick sketch
102
func (dht *IpfsDHT) handleMessages() {
103
	u.DOut("Begin message handling routine")
104 105

	checkTimeouts := time.NewTicker(time.Minute * 5)
106
	ch := dht.network.GetChan()
107 108
	for {
		select {
109
		case mes, ok := <-ch.Incoming:
110 111 112 113
			if !ok {
				u.DOut("handleMessages closing, bad recv on incoming")
				return
			}
114
			pmes := new(PBDHTMessage)
115 116
			err := proto.Unmarshal(mes.Data, pmes)
			if err != nil {
117
				u.PErr("Failed to decode protobuf message: %s\n", err)
118 119 120
				continue
			}

121
			dht.Update(mes.Peer)
122

123
			// Note: not sure if this is the correct place for this
124
			if pmes.GetResponse() {
125
				dht.listener.Respond(pmes.GetId(), mes)
126
				continue
127
			}
128 129
			//

130
			u.DOut("[peer: %s]\nGot message type: '%s' [id = %x, from = %s]\n",
Jeromy's avatar
Jeromy committed
131
				dht.self.ID.Pretty(),
132
				PBDHTMessage_MessageType_name[int32(pmes.GetType())],
133
				pmes.GetId(), mes.Peer.ID.Pretty())
134
			switch pmes.GetType() {
135
			case PBDHTMessage_GET_VALUE:
136
				dht.handleGetValue(mes.Peer, pmes)
137
			case PBDHTMessage_PUT_VALUE:
Jeromy's avatar
Jeromy committed
138
				dht.handlePutValue(mes.Peer, pmes)
139
			case PBDHTMessage_FIND_NODE:
Jeromy's avatar
Jeromy committed
140
				dht.handleFindPeer(mes.Peer, pmes)
141
			case PBDHTMessage_ADD_PROVIDER:
142
				dht.handleAddProvider(mes.Peer, pmes)
143
			case PBDHTMessage_GET_PROVIDERS:
144
				dht.handleGetProviders(mes.Peer, pmes)
145
			case PBDHTMessage_PING:
146
				dht.handlePing(mes.Peer, pmes)
147
			case PBDHTMessage_DIAGNOSTIC:
148
				dht.handleDiagnostic(mes.Peer, pmes)
149 150
			}

151
		case err := <-ch.Errors:
152
			u.PErr("dht err: %s\n", err)
153
		case <-dht.shutdown:
154
			checkTimeouts.Stop()
155
			return
156
		case <-checkTimeouts.C:
157 158 159 160 161 162 163 164 165 166 167 168 169
			// Time to collect some garbage!
			dht.cleanExpiredProviders()
		}
	}
}

func (dht *IpfsDHT) cleanExpiredProviders() {
	dht.providerLock.Lock()
	for k, parr := range dht.providers {
		var cleaned []*providerInfo
		for _, v := range parr {
			if time.Since(v.Creation) < time.Hour {
				cleaned = append(cleaned, v)
170
			}
171
		}
172
		dht.providers[k] = cleaned
173
	}
174 175 176
	dht.providerLock.Unlock()
}

Jeromy's avatar
Jeromy committed
177
func (dht *IpfsDHT) putValueToNetwork(p *peer.Peer, key string, value []byte) error {
178
	pmes := Message{
179 180
		Type:  PBDHTMessage_PUT_VALUE,
		Key:   key,
181
		Value: value,
182
		ID:    GenerateMessageID(),
183 184 185
	}

	mes := swarm.NewMessage(p, pmes.ToProtobuf())
186
	dht.network.Send(mes)
187 188 189
	return nil
}

190
func (dht *IpfsDHT) handleGetValue(p *peer.Peer, pmes *PBDHTMessage) {
191
	u.DOut("handleGetValue for key: %s\n", pmes.GetKey())
Jeromy's avatar
Jeromy committed
192
	dskey := ds.NewKey(pmes.GetKey())
193
	resp := &Message{
Jeromy's avatar
Jeromy committed
194
		Response: true,
195
		ID:       pmes.GetId(),
Jeromy's avatar
Jeromy committed
196 197 198
		Key:      pmes.GetKey(),
	}
	iVal, err := dht.datastore.Get(dskey)
Jeromy's avatar
Jeromy committed
199
	if err == nil {
Jeromy's avatar
Jeromy committed
200
		u.DOut("handleGetValue success!")
Jeromy's avatar
Jeromy committed
201 202
		resp.Success = true
		resp.Value = iVal.([]byte)
Jeromy's avatar
Jeromy committed
203
	} else if err == ds.ErrNotFound {
Jeromy's avatar
Jeromy committed
204
		// Check if we know any providers for the requested value
205
		dht.providerLock.RLock()
Jeromy's avatar
Jeromy committed
206
		provs, ok := dht.providers[u.Key(pmes.GetKey())]
207
		dht.providerLock.RUnlock()
Jeromy's avatar
Jeromy committed
208
		if ok && len(provs) > 0 {
209
			u.DOut("handleGetValue returning %d provider[s]\n", len(provs))
Jeromy's avatar
Jeromy committed
210 211 212 213 214 215
			for _, prov := range provs {
				resp.Peers = append(resp.Peers, prov.Value)
			}
			resp.Success = true
		} else {
			// No providers?
216 217
			// Find closest peer on given cluster to desired key and reply with that info

218 219 220 221 222 223 224
			level := 0
			if len(pmes.GetValue()) < 1 {
				// TODO: maybe return an error? Defaulting isnt a good idea IMO
				u.PErr("handleGetValue: no routing level specified, assuming 0")
			} else {
				level = int(pmes.GetValue()[0]) // Using value field to specify cluster level
			}
225
			u.DOut("handleGetValue searching level %d clusters\n", level)
226

227
			closer := dht.routingTables[level].NearestPeer(kb.ConvertKey(u.Key(pmes.GetKey())))
228

Jeromy's avatar
Jeromy committed
229 230 231 232 233
			if closer.ID.Equal(dht.self.ID) {
				u.DOut("Attempted to return self! this shouldnt happen...")
				resp.Peers = nil
				goto out
			}
234 235 236
			// If this peer is closer than the one from the table, return nil
			if kb.Closer(dht.self.ID, closer.ID, u.Key(pmes.GetKey())) {
				resp.Peers = nil
Jeromy's avatar
Jeromy committed
237
				u.DOut("handleGetValue could not find a closer node than myself.")
238
			} else {
239
				u.DOut("handleGetValue returning a closer peer: '%s'\n", closer.ID.Pretty())
240 241
				resp.Peers = []*peer.Peer{closer}
			}
242
		}
Jeromy's avatar
Jeromy committed
243
	} else {
244
		//temp: what other errors can a datastore return?
Jeromy's avatar
Jeromy committed
245
		panic(err)
246
	}
247

Jeromy's avatar
Jeromy committed
248
out:
249
	mes := swarm.NewMessage(p, resp.ToProtobuf())
250
	dht.network.Send(mes)
251 252
}

Jeromy's avatar
Jeromy committed
253
// Store a value in this peer local storage
254
func (dht *IpfsDHT) handlePutValue(p *peer.Peer, pmes *PBDHTMessage) {
255 256
	dht.dslock.Lock()
	defer dht.dslock.Unlock()
Jeromy's avatar
Jeromy committed
257 258 259 260 261 262
	dskey := ds.NewKey(pmes.GetKey())
	err := dht.datastore.Put(dskey, pmes.GetValue())
	if err != nil {
		// For now, just panic, handle this better later maybe
		panic(err)
	}
263 264
}

265
func (dht *IpfsDHT) handlePing(p *peer.Peer, pmes *PBDHTMessage) {
266
	resp := Message{
267
		Type:     pmes.GetType(),
268
		Response: true,
269
		ID:       pmes.GetId(),
270
	}
271

272
	dht.network.Send(swarm.NewMessage(p, resp.ToProtobuf()))
273 274
}

275
func (dht *IpfsDHT) handleFindPeer(p *peer.Peer, pmes *PBDHTMessage) {
276
	resp := Message{
277
		Type:     pmes.GetType(),
278
		ID:       pmes.GetId(),
279 280 281 282 283 284 285
		Response: true,
	}
	defer func() {
		mes := swarm.NewMessage(p, resp.ToProtobuf())
		dht.network.Send(mes)
	}()
	level := pmes.GetValue()[0]
286
	u.DOut("handleFindPeer: searching for '%s'\n", peer.ID(pmes.GetKey()).Pretty())
287
	closest := dht.routingTables[level].NearestPeer(kb.ConvertKey(u.Key(pmes.GetKey())))
Jeromy's avatar
Jeromy committed
288
	if closest == nil {
289
		u.PErr("handleFindPeer: could not find anything.")
290
		return
Jeromy's avatar
Jeromy committed
291 292 293
	}

	if len(closest.Addresses) == 0 {
294
		u.PErr("handleFindPeer: no addresses for connected peer...")
295
		return
Jeromy's avatar
Jeromy committed
296 297
	}

298 299 300
	// If the found peer further away than this peer...
	if kb.Closer(dht.self.ID, closest.ID, u.Key(pmes.GetKey())) {
		return
Jeromy's avatar
Jeromy committed
301 302
	}

303
	u.DOut("handleFindPeer: sending back '%s'\n", closest.ID.Pretty())
304 305 306 307 308
	resp.Peers = []*peer.Peer{closest}
	resp.Success = true
}

func (dht *IpfsDHT) handleGetProviders(p *peer.Peer, pmes *PBDHTMessage) {
309
	resp := Message{
310 311
		Type:     PBDHTMessage_GET_PROVIDERS,
		Key:      pmes.GetKey(),
312
		ID:       pmes.GetId(),
313
		Response: true,
Jeromy's avatar
Jeromy committed
314 315
	}

316
	dht.providerLock.RLock()
317
	providers := dht.providers[u.Key(pmes.GetKey())]
318
	dht.providerLock.RUnlock()
319
	if providers == nil || len(providers) == 0 {
Jeromy's avatar
Jeromy committed
320 321 322 323 324
		level := 0
		if len(pmes.GetValue()) > 0 {
			level = int(pmes.GetValue()[0])
		}

325
		closer := dht.routingTables[level].NearestPeer(kb.ConvertKey(u.Key(pmes.GetKey())))
Jeromy's avatar
Jeromy committed
326 327 328 329 330
		if kb.Closer(dht.self.ID, closer.ID, u.Key(pmes.GetKey())) {
			resp.Peers = nil
		} else {
			resp.Peers = []*peer.Peer{closer}
		}
331 332 333
	} else {
		for _, prov := range providers {
			resp.Peers = append(resp.Peers, prov.Value)
334
		}
335
		resp.Success = true
336 337 338
	}

	mes := swarm.NewMessage(p, resp.ToProtobuf())
339
	dht.network.Send(mes)
340 341
}

342 343
type providerInfo struct {
	Creation time.Time
344
	Value    *peer.Peer
345 346
}

347
func (dht *IpfsDHT) handleAddProvider(p *peer.Peer, pmes *PBDHTMessage) {
348 349
	//TODO: need to implement TTLs on providers
	key := u.Key(pmes.GetKey())
350
	dht.addProviderEntry(key, p)
351 352
}

353
// Halt stops all communications from this peer and shut down
354 355 356 357
func (dht *IpfsDHT) Halt() {
	dht.shutdown <- struct{}{}
	dht.network.Close()
}
358

359
func (dht *IpfsDHT) addProviderEntry(key u.Key, p *peer.Peer) {
360
	u.DOut("Adding %s as provider for '%s'\n", p.Key().Pretty(), key)
361 362
	dht.providerLock.Lock()
	provs := dht.providers[key]
363
	dht.providers[key] = append(provs, &providerInfo{time.Now(), p})
364 365
	dht.providerLock.Unlock()
}
366

Jeromy's avatar
Jeromy committed
367
// NOTE: not yet finished, low priority
368
func (dht *IpfsDHT) handleDiagnostic(p *peer.Peer, pmes *PBDHTMessage) {
369
	seq := dht.routingTables[0].NearestPeers(kb.ConvertPeerID(dht.self.ID), 10)
370
	listenChan := dht.listener.Listen(pmes.GetId(), len(seq), time.Second*30)
371

372
	for _, ps := range seq {
373
		mes := swarm.NewMessage(ps, pmes)
374
		dht.network.Send(mes)
375 376 377
	}

	buf := new(bytes.Buffer)
378 379 380
	di := dht.getDiagInfo()
	buf.Write(di.Marshal())

381 382 383 384 385 386 387 388
	// NOTE: this shouldnt be a hardcoded value
	after := time.After(time.Second * 20)
	count := len(seq)
	for count > 0 {
		select {
		case <-after:
			//Timeout, return what we have
			goto out
389 390 391
		case reqResp := <-listenChan:
			pmesOut := new(PBDHTMessage)
			err := proto.Unmarshal(reqResp.Data, pmesOut)
392 393 394 395
			if err != nil {
				// It broke? eh, whatever, keep going
				continue
			}
396
			buf.Write(reqResp.Data)
397 398 399 400 401
			count--
		}
	}

out:
402
	resp := Message{
403
		Type:     PBDHTMessage_DIAGNOSTIC,
404
		ID:       pmes.GetId(),
405
		Value:    buf.Bytes(),
406 407 408 409
		Response: true,
	}

	mes := swarm.NewMessage(p, resp.ToProtobuf())
410
	dht.network.Send(mes)
411
}
412

413 414 415
func (dht *IpfsDHT) getValueOrPeers(p *peer.Peer, key u.Key, timeout time.Duration, level int) ([]byte, []*peer.Peer, error) {
	pmes, err := dht.getValueSingle(p, key, timeout, level)
	if err != nil {
416
		return nil, nil, err
417 418 419 420 421 422 423 424 425 426 427 428 429
	}

	if pmes.GetSuccess() {
		if pmes.Value == nil { // We were given provider[s]
			val, err := dht.getFromPeerList(key, timeout, pmes.GetPeers(), level)
			if err != nil {
				return nil, nil, err
			}
			return val, nil, nil
		}

		// Success! We were given the value
		return pmes.GetValue(), nil, nil
430
	}
431

432 433 434 435 436 437 438 439
	// We were given a closer node
	var peers []*peer.Peer
	for _, pb := range pmes.GetPeers() {
		if peer.ID(pb.GetId()).Equal(dht.self.ID) {
			continue
		}
		addr, err := ma.NewMultiaddr(pb.GetAddr())
		if err != nil {
440
			u.PErr("%v\n", err.Error())
441 442
			continue
		}
443

444 445
		np, err := dht.network.GetConnection(peer.ID(pb.GetId()), addr)
		if err != nil {
446
			u.PErr("%v\n", err.Error())
447
			continue
448
		}
449 450

		peers = append(peers, np)
451
	}
452
	return nil, peers, nil
453 454
}

455 456
// getValueSingle simply performs the get value RPC with the given parameters
func (dht *IpfsDHT) getValueSingle(p *peer.Peer, key u.Key, timeout time.Duration, level int) (*PBDHTMessage, error) {
457
	pmes := Message{
458 459 460
		Type:  PBDHTMessage_GET_VALUE,
		Key:   string(key),
		Value: []byte{byte(level)},
461
		ID:    GenerateMessageID(),
Jeromy's avatar
Jeromy committed
462
	}
463
	responseChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
Jeromy's avatar
Jeromy committed
464 465

	mes := swarm.NewMessage(p, pmes.ToProtobuf())
466
	t := time.Now()
467
	dht.network.Send(mes)
Jeromy's avatar
Jeromy committed
468 469 470 471 472

	// Wait for either the response or a timeout
	timeup := time.After(timeout)
	select {
	case <-timeup:
473
		dht.listener.Unlisten(pmes.ID)
Jeromy's avatar
Jeromy committed
474
		return nil, u.ErrTimeout
475
	case resp, ok := <-responseChan:
Jeromy's avatar
Jeromy committed
476 477 478 479
		if !ok {
			u.PErr("response channel closed before timeout, please investigate.")
			return nil, u.ErrTimeout
		}
480 481
		roundtrip := time.Since(t)
		resp.Peer.SetLatency(roundtrip)
482 483
		pmesOut := new(PBDHTMessage)
		err := proto.Unmarshal(resp.Data, pmesOut)
Jeromy's avatar
Jeromy committed
484 485 486
		if err != nil {
			return nil, err
		}
487
		return pmesOut, nil
Jeromy's avatar
Jeromy committed
488 489 490
	}
}

491 492 493 494 495 496 497 498 499 500
// 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?
func (dht *IpfsDHT) getFromPeerList(key u.Key, timeout time.Duration,
	peerlist []*PBDHTMessage_PBPeer, level int) ([]byte, error) {
	for _, pinfo := range peerlist {
		p, _ := dht.Find(peer.ID(pinfo.GetId()))
		if p == nil {
			maddr, err := ma.NewMultiaddr(pinfo.GetAddr())
Jeromy's avatar
Jeromy committed
501
			if err != nil {
502
				u.PErr("getValue error: %s\n", err)
Jeromy's avatar
Jeromy committed
503 504
				continue
			}
505

506
			p, err = dht.network.GetConnection(peer.ID(pinfo.GetId()), maddr)
Jeromy's avatar
Jeromy committed
507
			if err != nil {
508
				u.PErr("getValue error: %s\n", err)
Jeromy's avatar
Jeromy committed
509 510 511
				continue
			}
		}
512
		pmes, err := dht.getValueSingle(p, key, timeout, level)
Jeromy's avatar
Jeromy committed
513
		if err != nil {
514
			u.DErr("getFromPeers error: %s\n", err)
Jeromy's avatar
Jeromy committed
515 516
			continue
		}
517
		dht.addProviderEntry(key, p)
Jeromy's avatar
Jeromy committed
518

519 520 521 522
		// Make sure it was a successful get
		if pmes.GetSuccess() && pmes.Value != nil {
			return pmes.GetValue(), nil
		}
Jeromy's avatar
Jeromy committed
523 524 525 526
	}
	return nil, u.ErrNotFound
}

527
func (dht *IpfsDHT) getLocal(key u.Key) ([]byte, error) {
528 529
	dht.dslock.Lock()
	defer dht.dslock.Unlock()
530
	v, err := dht.datastore.Get(ds.NewKey(string(key)))
531 532 533 534 535 536
	if err != nil {
		return nil, err
	}
	return v.([]byte), nil
}

537
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
538 539
	return dht.datastore.Put(ds.NewKey(string(key)), value)
}
540

541
// Update TODO(chas) Document this function
542
func (dht *IpfsDHT) Update(p *peer.Peer) {
543
	for _, route := range dht.routingTables {
544 545 546 547
		removed := route.Update(p)
		// Only drop the connection if no tables refer to this peer
		if removed != nil {
			found := false
548
			for _, r := range dht.routingTables {
549 550 551 552 553 554 555 556 557
				if r.Find(removed.ID) != nil {
					found = true
					break
				}
			}
			if !found {
				dht.network.Drop(removed)
			}
		}
558 559
	}
}
Jeromy's avatar
Jeromy committed
560

561
// Find looks for a peer with a given ID connected to this dht and returns the peer and the table it was found in.
Jeromy's avatar
Jeromy committed
562
func (dht *IpfsDHT) Find(id peer.ID) (*peer.Peer, *kb.RoutingTable) {
563
	for _, table := range dht.routingTables {
Jeromy's avatar
Jeromy committed
564 565 566 567 568 569 570
		p := table.Find(id)
		if p != nil {
			return p, table
		}
	}
	return nil, nil
}
571 572

func (dht *IpfsDHT) findPeerSingle(p *peer.Peer, id peer.ID, timeout time.Duration, level int) (*PBDHTMessage, error) {
573
	pmes := Message{
574 575
		Type:  PBDHTMessage_FIND_NODE,
		Key:   string(id),
576
		ID:    GenerateMessageID(),
577 578 579 580
		Value: []byte{byte(level)},
	}

	mes := swarm.NewMessage(p, pmes.ToProtobuf())
581
	listenChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
582
	t := time.Now()
583 584 585 586
	dht.network.Send(mes)
	after := time.After(timeout)
	select {
	case <-after:
587
		dht.listener.Unlisten(pmes.ID)
588 589
		return nil, u.ErrTimeout
	case resp := <-listenChan:
590 591
		roundtrip := time.Since(t)
		resp.Peer.SetLatency(roundtrip)
592 593
		pmesOut := new(PBDHTMessage)
		err := proto.Unmarshal(resp.Data, pmesOut)
594 595 596 597
		if err != nil {
			return nil, err
		}

598
		return pmesOut, nil
599 600
	}
}
601

602 603
func (dht *IpfsDHT) printTables() {
	for _, route := range dht.routingTables {
604 605 606
		route.Print()
	}
}
Jeromy's avatar
Jeromy committed
607 608

func (dht *IpfsDHT) findProvidersSingle(p *peer.Peer, key u.Key, level int, timeout time.Duration) (*PBDHTMessage, error) {
609
	pmes := Message{
Jeromy's avatar
Jeromy committed
610 611
		Type:  PBDHTMessage_GET_PROVIDERS,
		Key:   string(key),
612
		ID:    GenerateMessageID(),
Jeromy's avatar
Jeromy committed
613 614 615 616 617
		Value: []byte{byte(level)},
	}

	mes := swarm.NewMessage(p, pmes.ToProtobuf())

618
	listenChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
Jeromy's avatar
Jeromy committed
619 620 621 622
	dht.network.Send(mes)
	after := time.After(timeout)
	select {
	case <-after:
623
		dht.listener.Unlisten(pmes.ID)
Jeromy's avatar
Jeromy committed
624 625 626
		return nil, u.ErrTimeout
	case resp := <-listenChan:
		u.DOut("FindProviders: got response.")
627 628
		pmesOut := new(PBDHTMessage)
		err := proto.Unmarshal(resp.Data, pmesOut)
Jeromy's avatar
Jeromy committed
629 630 631 632
		if err != nil {
			return nil, err
		}

633
		return pmesOut, nil
Jeromy's avatar
Jeromy committed
634 635 636 637
	}
}

func (dht *IpfsDHT) addPeerList(key u.Key, peers []*PBDHTMessage_PBPeer) []*peer.Peer {
638
	var provArr []*peer.Peer
Jeromy's avatar
Jeromy committed
639 640 641 642 643 644 645 646
	for _, prov := range peers {
		// Dont add outselves to the list
		if peer.ID(prov.GetId()).Equal(dht.self.ID) {
			continue
		}
		// Dont add someone who is already on the list
		p := dht.network.Find(u.Key(prov.GetId()))
		if p == nil {
647
			u.DOut("given provider %s was not in our network already.\n", peer.ID(prov.GetId()).Pretty())
Jeromy's avatar
Jeromy committed
648 649
			maddr, err := ma.NewMultiaddr(prov.GetAddr())
			if err != nil {
650
				u.PErr("error connecting to new peer: %s\n", err)
Jeromy's avatar
Jeromy committed
651 652 653 654
				continue
			}
			p, err = dht.network.GetConnection(peer.ID(prov.GetId()), maddr)
			if err != nil {
655
				u.PErr("error connecting to new peer: %s\n", err)
Jeromy's avatar
Jeromy committed
656 657 658 659
				continue
			}
		}
		dht.addProviderEntry(key, p)
660
		provArr = append(provArr, p)
Jeromy's avatar
Jeromy committed
661
	}
662
	return provArr
Jeromy's avatar
Jeromy committed
663
}