dht.go 16.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
	providers *ProviderManager
40

41 42
	// Signal to shutdown dht
	shutdown chan struct{}
43 44 45

	// When this peer started up
	birth time.Time
46 47 48

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

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

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

63 64 65 66 67
	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()
68
	dht.birth = time.Now()
Jeromy's avatar
Jeromy committed
69
	return dht
70 71
}

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

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

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

93 94
	dht.Update(npeer)

95
	return npeer, nil
Jeromy's avatar
Jeromy committed
96 97
}

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

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

118
			dht.Update(mes.Peer)
119

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

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

150
		case err := <-ch.Errors:
151
			u.PErr("dht err: %s\n", err)
152 153
		case <-dht.shutdown:
			return
154 155 156 157
		}
	}
}

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

	mes := swarm.NewMessage(p, pmes.ToProtobuf())
167
	dht.network.Send(mes)
168 169 170
	return nil
}

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

195 196 197 198 199 200 201
			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
			}
202
			u.DOut("handleGetValue searching level %d clusters\n", level)
203

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

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

Jeromy's avatar
Jeromy committed
225
out:
226
	mes := swarm.NewMessage(p, resp.ToProtobuf())
227
	dht.network.Send(mes)
228 229
}

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

242
func (dht *IpfsDHT) handlePing(p *peer.Peer, pmes *PBDHTMessage) {
243
	resp := Message{
244
		Type:     pmes.GetType(),
245
		Response: true,
246
		ID:       pmes.GetId(),
247
	}
248

249
	dht.network.Send(swarm.NewMessage(p, resp.ToProtobuf()))
250 251
}

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

	if len(closest.Addresses) == 0 {
271
		u.PErr("handleFindPeer: no addresses for connected peer...")
272
		return
Jeromy's avatar
Jeromy committed
273 274
	}

275 276 277
	// 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
278 279
	}

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

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

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

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

	mes := swarm.NewMessage(p, resp.ToProtobuf())
312
	dht.network.Send(mes)
313 314
}

315 316
type providerInfo struct {
	Creation time.Time
317
	Value    *peer.Peer
318 319
}

320
func (dht *IpfsDHT) handleAddProvider(p *peer.Peer, pmes *PBDHTMessage) {
321
	key := u.Key(pmes.GetKey())
322
	dht.providers.AddProvider(key, p)
323 324
}

325
// Halt stops all communications from this peer and shut down
326 327 328 329
func (dht *IpfsDHT) Halt() {
	dht.shutdown <- struct{}{}
	dht.network.Close()
}
330

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

336
	for _, ps := range seq {
337
		mes := swarm.NewMessage(ps, pmes)
338
		dht.network.Send(mes)
339 340 341
	}

	buf := new(bytes.Buffer)
342 343 344
	di := dht.getDiagInfo()
	buf.Write(di.Marshal())

345 346 347 348 349 350 351 352
	// 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
353 354 355
		case reqResp := <-listenChan:
			pmesOut := new(PBDHTMessage)
			err := proto.Unmarshal(reqResp.Data, pmesOut)
356 357 358 359
			if err != nil {
				// It broke? eh, whatever, keep going
				continue
			}
360
			buf.Write(reqResp.Data)
361 362 363 364 365
			count--
		}
	}

out:
366
	resp := Message{
367
		Type:     PBDHTMessage_DIAGNOSTIC,
368
		ID:       pmes.GetId(),
369
		Value:    buf.Bytes(),
370 371 372 373
		Response: true,
	}

	mes := swarm.NewMessage(p, resp.ToProtobuf())
374
	dht.network.Send(mes)
375
}
376

377 378 379
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 {
380
		return nil, nil, err
381 382 383 384 385 386 387 388 389 390 391 392 393
	}

	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
394
	}
395

396 397 398 399 400 401 402 403
	// 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 {
404
			u.PErr("%v\n", err.Error())
405 406
			continue
		}
407

408 409
		np, err := dht.network.GetConnection(peer.ID(pb.GetId()), addr)
		if err != nil {
410
			u.PErr("%v\n", err.Error())
411
			continue
412
		}
413 414

		peers = append(peers, np)
415
	}
416
	return nil, peers, nil
417 418
}

419 420
// 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) {
421
	pmes := Message{
422 423 424
		Type:  PBDHTMessage_GET_VALUE,
		Key:   string(key),
		Value: []byte{byte(level)},
425
		ID:    GenerateMessageID(),
Jeromy's avatar
Jeromy committed
426
	}
427
	responseChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
Jeromy's avatar
Jeromy committed
428 429

	mes := swarm.NewMessage(p, pmes.ToProtobuf())
430
	t := time.Now()
431
	dht.network.Send(mes)
Jeromy's avatar
Jeromy committed
432 433 434 435 436

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

455 456 457 458 459 460 461 462 463 464
// 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
465
			if err != nil {
466
				u.PErr("getValue error: %s\n", err)
Jeromy's avatar
Jeromy committed
467 468
				continue
			}
469

470
			p, err = dht.network.GetConnection(peer.ID(pinfo.GetId()), maddr)
Jeromy's avatar
Jeromy committed
471
			if err != nil {
472
				u.PErr("getValue error: %s\n", err)
Jeromy's avatar
Jeromy committed
473 474 475
				continue
			}
		}
476
		pmes, err := dht.getValueSingle(p, key, timeout, level)
Jeromy's avatar
Jeromy committed
477
		if err != nil {
478
			u.DErr("getFromPeers error: %s\n", err)
Jeromy's avatar
Jeromy committed
479 480
			continue
		}
481
		dht.providers.AddProvider(key, p)
Jeromy's avatar
Jeromy committed
482

483 484 485 486
		// Make sure it was a successful get
		if pmes.GetSuccess() && pmes.Value != nil {
			return pmes.GetValue(), nil
		}
Jeromy's avatar
Jeromy committed
487 488 489 490
	}
	return nil, u.ErrNotFound
}

491
func (dht *IpfsDHT) getLocal(key u.Key) ([]byte, error) {
492 493
	dht.dslock.Lock()
	defer dht.dslock.Unlock()
494
	v, err := dht.datastore.Get(ds.NewKey(string(key)))
495 496 497 498 499 500
	if err != nil {
		return nil, err
	}
	return v.([]byte), nil
}

501
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
502 503
	return dht.datastore.Put(ds.NewKey(string(key)), value)
}
504

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

525
// 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
526
func (dht *IpfsDHT) Find(id peer.ID) (*peer.Peer, *kb.RoutingTable) {
527
	for _, table := range dht.routingTables {
Jeromy's avatar
Jeromy committed
528 529 530 531 532 533 534
		p := table.Find(id)
		if p != nil {
			return p, table
		}
	}
	return nil, nil
}
535 536

func (dht *IpfsDHT) findPeerSingle(p *peer.Peer, id peer.ID, timeout time.Duration, level int) (*PBDHTMessage, error) {
537
	pmes := Message{
538 539
		Type:  PBDHTMessage_FIND_NODE,
		Key:   string(id),
540
		ID:    GenerateMessageID(),
541 542 543 544
		Value: []byte{byte(level)},
	}

	mes := swarm.NewMessage(p, pmes.ToProtobuf())
545
	listenChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
546
	t := time.Now()
547 548 549 550
	dht.network.Send(mes)
	after := time.After(timeout)
	select {
	case <-after:
551
		dht.listener.Unlisten(pmes.ID)
552 553
		return nil, u.ErrTimeout
	case resp := <-listenChan:
554 555
		roundtrip := time.Since(t)
		resp.Peer.SetLatency(roundtrip)
556 557
		pmesOut := new(PBDHTMessage)
		err := proto.Unmarshal(resp.Data, pmesOut)
558 559 560 561
		if err != nil {
			return nil, err
		}

562
		return pmesOut, nil
563 564
	}
}
565

566 567
func (dht *IpfsDHT) printTables() {
	for _, route := range dht.routingTables {
568 569 570
		route.Print()
	}
}
Jeromy's avatar
Jeromy committed
571 572

func (dht *IpfsDHT) findProvidersSingle(p *peer.Peer, key u.Key, level int, timeout time.Duration) (*PBDHTMessage, error) {
573
	pmes := Message{
Jeromy's avatar
Jeromy committed
574 575
		Type:  PBDHTMessage_GET_PROVIDERS,
		Key:   string(key),
576
		ID:    GenerateMessageID(),
Jeromy's avatar
Jeromy committed
577 578 579 580 581
		Value: []byte{byte(level)},
	}

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

582
	listenChan := dht.listener.Listen(pmes.ID, 1, time.Minute)
Jeromy's avatar
Jeromy committed
583 584 585 586
	dht.network.Send(mes)
	after := time.After(timeout)
	select {
	case <-after:
587
		dht.listener.Unlisten(pmes.ID)
Jeromy's avatar
Jeromy committed
588 589 590
		return nil, u.ErrTimeout
	case resp := <-listenChan:
		u.DOut("FindProviders: got response.")
591 592
		pmesOut := new(PBDHTMessage)
		err := proto.Unmarshal(resp.Data, pmesOut)
Jeromy's avatar
Jeromy committed
593 594 595 596
		if err != nil {
			return nil, err
		}

597
		return pmesOut, nil
Jeromy's avatar
Jeromy committed
598 599 600 601
	}
}

func (dht *IpfsDHT) addPeerList(key u.Key, peers []*PBDHTMessage_PBPeer) []*peer.Peer {
602
	var provArr []*peer.Peer
Jeromy's avatar
Jeromy committed
603 604 605 606 607 608 609 610
	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 {
611
			u.DOut("given provider %s was not in our network already.\n", peer.ID(prov.GetId()).Pretty())
Jeromy's avatar
Jeromy committed
612 613
			maddr, err := ma.NewMultiaddr(prov.GetAddr())
			if err != nil {
614
				u.PErr("error connecting to new peer: %s\n", err)
Jeromy's avatar
Jeromy committed
615 616 617 618
				continue
			}
			p, err = dht.network.GetConnection(peer.ID(prov.GetId()), maddr)
			if err != nil {
619
				u.PErr("error connecting to new peer: %s\n", err)
Jeromy's avatar
Jeromy committed
620 621 622
				continue
			}
		}
623
		dht.providers.AddProvider(key, p)
624
		provArr = append(provArr, p)
Jeromy's avatar
Jeromy committed
625
	}
626
	return provArr
Jeromy's avatar
Jeromy committed
627
}