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

3
import (
4
	"bytes"
5
	"crypto/rand"
6
	"fmt"
7 8
	"sync"
	"time"
9

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

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

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

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

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

31
	network swarm.Network
32
	netChan *swarm.Chan
33

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

	// Local data
	datastore ds.Datastore
39
	dslock    sync.Mutex
40

41
	providers *ProviderManager
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 *swarm.MessageListener
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, dstore ds.Datastore) *IpfsDHT {
58
	dht := new(IpfsDHT)
Jeromy's avatar
Jeromy committed
59
	dht.network = net
60
	dht.netChan = net.GetChannel(swarm.PBWrapper_DHT_MESSAGE)
Jeromy's avatar
Jeromy committed
61
	dht.datastore = dstore
62
	dht.self = p
63
	dht.providers = NewProviderManager()
Jeromy's avatar
Jeromy committed
64
	dht.shutdown = make(chan struct{})
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)
70
	dht.listener = swarm.NewMessageListener()
71
	dht.birth = time.Now()
Jeromy's avatar
Jeromy committed
72
	return dht
73 74
}

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

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

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

96 97
	dht.Update(npeer)

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

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

106
	errs := dht.network.GetErrChan()
107 108
	for {
		select {
109
		case mes, ok := <-dht.netChan.Incoming:
110
			if !ok {
Jeromy's avatar
Jeromy committed
111
				u.DOut("handleMessages closing, bad recv on incoming\n")
112 113
				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
				go dht.handleGetValue(mes.Peer, pmes)
137
			case PBDHTMessage_PUT_VALUE:
138
				go dht.handlePutValue(mes.Peer, pmes)
139
			case PBDHTMessage_FIND_NODE:
140
				go dht.handleFindPeer(mes.Peer, pmes)
141
			case PBDHTMessage_ADD_PROVIDER:
142
				go dht.handleAddProvider(mes.Peer, pmes)
143
			case PBDHTMessage_GET_PROVIDERS:
144
				go dht.handleGetProviders(mes.Peer, pmes)
145
			case PBDHTMessage_PING:
146
				go dht.handlePing(mes.Peer, pmes)
147
			case PBDHTMessage_DIAGNOSTIC:
148
				go dht.handleDiagnostic(mes.Peer, pmes)
149 150
			default:
				u.PErr("Recieved invalid message type")
151 152
			}

153
		case err := <-errs:
154
			u.PErr("dht err: %s\n", err)
155 156
		case <-dht.shutdown:
			return
157 158 159 160
		}
	}
}

Jeromy's avatar
Jeromy committed
161
func (dht *IpfsDHT) putValueToNetwork(p *peer.Peer, key string, value []byte) error {
162
	pmes := Message{
163 164
		Type:  PBDHTMessage_PUT_VALUE,
		Key:   key,
165
		Value: value,
166
		ID:    swarm.GenerateMessageID(),
167 168 169
	}

	mes := swarm.NewMessage(p, pmes.ToProtobuf())
170
	dht.netChan.Outgoing <- mes
171 172 173
	return nil
}

174
func (dht *IpfsDHT) handleGetValue(p *peer.Peer, pmes *PBDHTMessage) {
175
	u.DOut("handleGetValue for key: %s\n", pmes.GetKey())
Jeromy's avatar
Jeromy committed
176
	dskey := ds.NewKey(pmes.GetKey())
177
	resp := &Message{
Jeromy's avatar
Jeromy committed
178
		Response: true,
179
		ID:       pmes.GetId(),
Jeromy's avatar
Jeromy committed
180 181 182
		Key:      pmes.GetKey(),
	}
	iVal, err := dht.datastore.Get(dskey)
Jeromy's avatar
Jeromy committed
183
	if err == nil {
Jeromy's avatar
Jeromy committed
184
		u.DOut("handleGetValue success!\n")
Jeromy's avatar
Jeromy committed
185 186
		resp.Success = true
		resp.Value = iVal.([]byte)
Jeromy's avatar
Jeromy committed
187
	} else if err == ds.ErrNotFound {
Jeromy's avatar
Jeromy committed
188
		// Check if we know any providers for the requested value
189 190
		provs := dht.providers.GetProviders(u.Key(pmes.GetKey()))
		if len(provs) > 0 {
191
			u.DOut("handleGetValue returning %d provider[s]\n", len(provs))
192
			resp.Peers = provs
Jeromy's avatar
Jeromy committed
193 194 195
			resp.Success = true
		} else {
			// No providers?
196 197
			// Find closest peer on given cluster to desired key and reply with that info

198 199 200
			level := 0
			if len(pmes.GetValue()) < 1 {
				// TODO: maybe return an error? Defaulting isnt a good idea IMO
Jeromy's avatar
Jeromy committed
201
				u.PErr("handleGetValue: no routing level specified, assuming 0\n")
202 203 204
			} else {
				level = int(pmes.GetValue()[0]) // Using value field to specify cluster level
			}
205
			u.DOut("handleGetValue searching level %d clusters\n", level)
206

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

Jeromy's avatar
Jeromy committed
209
			if closer.ID.Equal(dht.self.ID) {
Jeromy's avatar
Jeromy committed
210
				u.DOut("Attempted to return self! this shouldnt happen...\n")
Jeromy's avatar
Jeromy committed
211 212 213
				resp.Peers = nil
				goto out
			}
214 215 216
			// 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
217
				u.DOut("handleGetValue could not find a closer node than myself.\n")
218
			} else {
219
				u.DOut("handleGetValue returning a closer peer: '%s'\n", closer.ID.Pretty())
220 221
				resp.Peers = []*peer.Peer{closer}
			}
222
		}
Jeromy's avatar
Jeromy committed
223
	} else {
224
		//temp: what other errors can a datastore return?
Jeromy's avatar
Jeromy committed
225
		panic(err)
226
	}
227

Jeromy's avatar
Jeromy committed
228
out:
229
	mes := swarm.NewMessage(p, resp.ToProtobuf())
230
	dht.netChan.Outgoing <- mes
231 232
}

Jeromy's avatar
Jeromy committed
233
// Store a value in this peer local storage
234
func (dht *IpfsDHT) handlePutValue(p *peer.Peer, pmes *PBDHTMessage) {
235 236
	dht.dslock.Lock()
	defer dht.dslock.Unlock()
Jeromy's avatar
Jeromy committed
237 238 239 240 241 242
	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)
	}
243 244
}

245
func (dht *IpfsDHT) handlePing(p *peer.Peer, pmes *PBDHTMessage) {
246
	u.DOut("[%s] Responding to ping from [%s]!\n", dht.self.ID.Pretty(), p.ID.Pretty())
247
	resp := Message{
248
		Type:     pmes.GetType(),
249
		Response: true,
250
		ID:       pmes.GetId(),
251
	}
252

253
	dht.netChan.Outgoing <- swarm.NewMessage(p, resp.ToProtobuf())
254 255
}

256
func (dht *IpfsDHT) handleFindPeer(p *peer.Peer, pmes *PBDHTMessage) {
257
	resp := Message{
258
		Type:     pmes.GetType(),
259
		ID:       pmes.GetId(),
260 261 262 263
		Response: true,
	}
	defer func() {
		mes := swarm.NewMessage(p, resp.ToProtobuf())
264
		dht.netChan.Outgoing <- mes
265 266
	}()
	level := pmes.GetValue()[0]
267
	u.DOut("handleFindPeer: searching for '%s'\n", peer.ID(pmes.GetKey()).Pretty())
268
	closest := dht.routingTables[level].NearestPeer(kb.ConvertKey(u.Key(pmes.GetKey())))
Jeromy's avatar
Jeromy committed
269
	if closest == nil {
Jeromy's avatar
Jeromy committed
270
		u.PErr("handleFindPeer: could not find anything.\n")
271
		return
Jeromy's avatar
Jeromy committed
272 273 274
	}

	if len(closest.Addresses) == 0 {
Jeromy's avatar
Jeromy committed
275
		u.PErr("handleFindPeer: no addresses for connected peer...\n")
276
		return
Jeromy's avatar
Jeromy committed
277 278
	}

279 280 281
	// 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
282 283
	}

284
	u.DOut("handleFindPeer: sending back '%s'\n", closest.ID.Pretty())
285 286 287 288 289
	resp.Peers = []*peer.Peer{closest}
	resp.Success = true
}

func (dht *IpfsDHT) handleGetProviders(p *peer.Peer, pmes *PBDHTMessage) {
290
	resp := Message{
291 292
		Type:     PBDHTMessage_GET_PROVIDERS,
		Key:      pmes.GetKey(),
293
		ID:       pmes.GetId(),
294
		Response: true,
Jeromy's avatar
Jeromy committed
295 296
	}

297
	providers := dht.providers.GetProviders(u.Key(pmes.GetKey()))
298
	if providers == nil || len(providers) == 0 {
Jeromy's avatar
Jeromy committed
299 300 301 302 303
		level := 0
		if len(pmes.GetValue()) > 0 {
			level = int(pmes.GetValue()[0])
		}

304
		closer := dht.routingTables[level].NearestPeer(kb.ConvertKey(u.Key(pmes.GetKey())))
Jeromy's avatar
Jeromy committed
305 306 307 308 309
		if kb.Closer(dht.self.ID, closer.ID, u.Key(pmes.GetKey())) {
			resp.Peers = nil
		} else {
			resp.Peers = []*peer.Peer{closer}
		}
310
	} else {
311
		resp.Peers = providers
312
		resp.Success = true
313 314 315
	}

	mes := swarm.NewMessage(p, resp.ToProtobuf())
316
	dht.netChan.Outgoing <- mes
317 318
}

319 320
type providerInfo struct {
	Creation time.Time
321
	Value    *peer.Peer
322 323
}

324
func (dht *IpfsDHT) handleAddProvider(p *peer.Peer, pmes *PBDHTMessage) {
325
	key := u.Key(pmes.GetKey())
Jeromy's avatar
Jeromy committed
326
	u.DOut("[%s] Adding [%s] as a provider for '%s'\n", dht.self.ID.Pretty(), p.ID.Pretty(), peer.ID(key).Pretty())
327
	dht.providers.AddProvider(key, p)
328 329
}

330
// Halt stops all communications from this peer and shut down
331 332 333
func (dht *IpfsDHT) Halt() {
	dht.shutdown <- struct{}{}
	dht.network.Close()
334 335
	dht.providers.Halt()
	dht.listener.Halt()
336
}
337

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

343
	for _, ps := range seq {
344
		mes := swarm.NewMessage(ps, pmes)
345
		dht.netChan.Outgoing <- mes
346 347 348
	}

	buf := new(bytes.Buffer)
349 350 351
	di := dht.getDiagInfo()
	buf.Write(di.Marshal())

352 353 354 355 356 357 358 359
	// 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
360 361 362
		case reqResp := <-listenChan:
			pmesOut := new(PBDHTMessage)
			err := proto.Unmarshal(reqResp.Data, pmesOut)
363 364 365 366
			if err != nil {
				// It broke? eh, whatever, keep going
				continue
			}
367
			buf.Write(reqResp.Data)
368 369 370 371 372
			count--
		}
	}

out:
373
	resp := Message{
374
		Type:     PBDHTMessage_DIAGNOSTIC,
375
		ID:       pmes.GetId(),
376
		Value:    buf.Bytes(),
377 378 379 380
		Response: true,
	}

	mes := swarm.NewMessage(p, resp.ToProtobuf())
381
	dht.netChan.Outgoing <- mes
382
}
383

384 385 386
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 {
387
		return nil, nil, err
388 389 390 391 392 393 394 395 396 397 398 399 400
	}

	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
401
	}
402

403 404 405 406 407 408 409 410
	// 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 {
411
			u.PErr("%v\n", err.Error())
412 413
			continue
		}
414

415 416
		np, err := dht.network.GetConnection(peer.ID(pb.GetId()), addr)
		if err != nil {
417
			u.PErr("%v\n", err.Error())
418
			continue
419
		}
420 421

		peers = append(peers, np)
422
	}
423
	return nil, peers, nil
424 425
}

426 427
// 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) {
428
	pmes := Message{
429 430 431
		Type:  PBDHTMessage_GET_VALUE,
		Key:   string(key),
		Value: []byte{byte(level)},
432
		ID:    swarm.GenerateMessageID(),
Jeromy's avatar
Jeromy committed
433
	}
434
	responseChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
Jeromy's avatar
Jeromy committed
435 436

	mes := swarm.NewMessage(p, pmes.ToProtobuf())
437
	t := time.Now()
438
	dht.netChan.Outgoing <- mes
Jeromy's avatar
Jeromy committed
439 440 441 442 443

	// Wait for either the response or a timeout
	timeup := time.After(timeout)
	select {
	case <-timeup:
444
		dht.listener.Unlisten(pmes.ID)
Jeromy's avatar
Jeromy committed
445
		return nil, u.ErrTimeout
446
	case resp, ok := <-responseChan:
Jeromy's avatar
Jeromy committed
447
		if !ok {
Jeromy's avatar
Jeromy committed
448
			u.PErr("response channel closed before timeout, please investigate.\n")
Jeromy's avatar
Jeromy committed
449 450
			return nil, u.ErrTimeout
		}
451 452
		roundtrip := time.Since(t)
		resp.Peer.SetLatency(roundtrip)
453 454
		pmesOut := new(PBDHTMessage)
		err := proto.Unmarshal(resp.Data, pmesOut)
Jeromy's avatar
Jeromy committed
455 456 457
		if err != nil {
			return nil, err
		}
458
		return pmesOut, nil
Jeromy's avatar
Jeromy committed
459 460 461
	}
}

462 463 464 465 466 467 468 469 470 471
// 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
472
			if err != nil {
473
				u.PErr("getValue error: %s\n", err)
Jeromy's avatar
Jeromy committed
474 475
				continue
			}
476

477
			p, err = dht.network.GetConnection(peer.ID(pinfo.GetId()), maddr)
Jeromy's avatar
Jeromy committed
478
			if err != nil {
479
				u.PErr("getValue error: %s\n", err)
Jeromy's avatar
Jeromy committed
480 481 482
				continue
			}
		}
483
		pmes, err := dht.getValueSingle(p, key, timeout, level)
Jeromy's avatar
Jeromy committed
484
		if err != nil {
485
			u.DErr("getFromPeers error: %s\n", err)
Jeromy's avatar
Jeromy committed
486 487
			continue
		}
488
		dht.providers.AddProvider(key, p)
Jeromy's avatar
Jeromy committed
489

490 491 492 493
		// Make sure it was a successful get
		if pmes.GetSuccess() && pmes.Value != nil {
			return pmes.GetValue(), nil
		}
Jeromy's avatar
Jeromy committed
494 495 496 497
	}
	return nil, u.ErrNotFound
}

498
func (dht *IpfsDHT) getLocal(key u.Key) ([]byte, error) {
499 500
	dht.dslock.Lock()
	defer dht.dslock.Unlock()
501
	v, err := dht.datastore.Get(ds.NewKey(string(key)))
502 503 504 505 506 507
	if err != nil {
		return nil, err
	}
	return v.([]byte), nil
}

508
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
509 510
	return dht.datastore.Put(ds.NewKey(string(key)), value)
}
511

512
// Update TODO(chas) Document this function
513
func (dht *IpfsDHT) Update(p *peer.Peer) {
514
	for _, route := range dht.routingTables {
515 516 517 518
		removed := route.Update(p)
		// Only drop the connection if no tables refer to this peer
		if removed != nil {
			found := false
519
			for _, r := range dht.routingTables {
520 521 522 523 524 525 526 527 528
				if r.Find(removed.ID) != nil {
					found = true
					break
				}
			}
			if !found {
				dht.network.Drop(removed)
			}
		}
529 530
	}
}
Jeromy's avatar
Jeromy committed
531

532
// 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
533
func (dht *IpfsDHT) Find(id peer.ID) (*peer.Peer, *kb.RoutingTable) {
534
	for _, table := range dht.routingTables {
Jeromy's avatar
Jeromy committed
535 536 537 538 539 540 541
		p := table.Find(id)
		if p != nil {
			return p, table
		}
	}
	return nil, nil
}
542 543

func (dht *IpfsDHT) findPeerSingle(p *peer.Peer, id peer.ID, timeout time.Duration, level int) (*PBDHTMessage, error) {
544
	pmes := Message{
545 546
		Type:  PBDHTMessage_FIND_NODE,
		Key:   string(id),
547
		ID:    swarm.GenerateMessageID(),
548 549 550 551
		Value: []byte{byte(level)},
	}

	mes := swarm.NewMessage(p, pmes.ToProtobuf())
552
	listenChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
553
	t := time.Now()
554
	dht.netChan.Outgoing <- mes
555 556 557
	after := time.After(timeout)
	select {
	case <-after:
558
		dht.listener.Unlisten(pmes.ID)
559 560
		return nil, u.ErrTimeout
	case resp := <-listenChan:
561 562
		roundtrip := time.Since(t)
		resp.Peer.SetLatency(roundtrip)
563 564
		pmesOut := new(PBDHTMessage)
		err := proto.Unmarshal(resp.Data, pmesOut)
565 566 567 568
		if err != nil {
			return nil, err
		}

569
		return pmesOut, nil
570 571
	}
}
572

573 574
func (dht *IpfsDHT) printTables() {
	for _, route := range dht.routingTables {
575 576 577
		route.Print()
	}
}
Jeromy's avatar
Jeromy committed
578 579

func (dht *IpfsDHT) findProvidersSingle(p *peer.Peer, key u.Key, level int, timeout time.Duration) (*PBDHTMessage, error) {
580
	pmes := Message{
Jeromy's avatar
Jeromy committed
581 582
		Type:  PBDHTMessage_GET_PROVIDERS,
		Key:   string(key),
583
		ID:    swarm.GenerateMessageID(),
Jeromy's avatar
Jeromy committed
584 585 586 587 588
		Value: []byte{byte(level)},
	}

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

589
	listenChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
590
	dht.netChan.Outgoing <- mes
Jeromy's avatar
Jeromy committed
591 592 593
	after := time.After(timeout)
	select {
	case <-after:
594
		dht.listener.Unlisten(pmes.ID)
Jeromy's avatar
Jeromy committed
595 596
		return nil, u.ErrTimeout
	case resp := <-listenChan:
Jeromy's avatar
Jeromy committed
597
		u.DOut("FindProviders: got response.\n")
598 599
		pmesOut := new(PBDHTMessage)
		err := proto.Unmarshal(resp.Data, pmesOut)
Jeromy's avatar
Jeromy committed
600 601 602 603
		if err != nil {
			return nil, err
		}

604
		return pmesOut, nil
Jeromy's avatar
Jeromy committed
605 606 607
	}
}

608
// TODO: Could be done async
Jeromy's avatar
Jeromy committed
609
func (dht *IpfsDHT) addPeerList(key u.Key, peers []*PBDHTMessage_PBPeer) []*peer.Peer {
610
	var provArr []*peer.Peer
Jeromy's avatar
Jeromy committed
611 612 613 614 615 616 617 618
	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 {
619
			u.DOut("given provider %s was not in our network already.\n", peer.ID(prov.GetId()).Pretty())
Jeromy's avatar
Jeromy committed
620 621
			var err error
			p, err = dht.peerFromInfo(prov)
Jeromy's avatar
Jeromy committed
622
			if err != nil {
623
				u.PErr("error connecting to new peer: %s\n", err)
Jeromy's avatar
Jeromy committed
624 625 626
				continue
			}
		}
627
		dht.providers.AddProvider(key, p)
628
		provArr = append(provArr, p)
Jeromy's avatar
Jeromy committed
629
	}
630
	return provArr
Jeromy's avatar
Jeromy committed
631
}
Jeromy's avatar
Jeromy committed
632 633 634 635 636 637 638 639 640

func (dht *IpfsDHT) peerFromInfo(pbp *PBDHTMessage_PBPeer) (*peer.Peer, error) {
	maddr, err := ma.NewMultiaddr(pbp.GetAddr())
	if err != nil {
		return nil, err
	}

	return dht.network.GetConnection(peer.ID(pbp.GetId()), maddr)
}
641 642 643 644 645 646 647

// Builds up list of peers by requesting random peer IDs
func (dht *IpfsDHT) Bootstrap() {
	id := make([]byte, 16)
	rand.Read(id)
	dht.FindPeer(peer.ID(id), time.Second*10)
}