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

17
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
18
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/datastore.go"
19
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
	logging "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/op/go-logging"
Jeromy's avatar
Jeromy committed
21

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25
var log = u.Logger("dht", logging.ERROR)
26

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

36
	// the network interface. service
37
	network inet.Network
38
	sender  inet.Sender
39

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

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

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

50
	providers *ProviderManager
51

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

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

Jeromy's avatar
Jeromy committed
59
// NewDHT creates a new DHT object with the given peer as the 'local' host
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60
func NewDHT(p *peer.Peer, ps peer.Peerstore, net inet.Network, sender inet.Sender, dstore ds.Datastore) *IpfsDHT {
61
	dht := new(IpfsDHT)
Jeromy's avatar
Jeromy committed
62
	dht.network = net
63
	dht.sender = sender
Jeromy's avatar
Jeromy committed
64
	dht.datastore = dstore
65
	dht.self = p
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
66
	dht.peerstore = ps
67

68
	dht.providers = NewProviderManager(p.ID)
69

70 71 72 73
	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)
74
	dht.birth = time.Now()
Jeromy's avatar
Jeromy committed
75
	return dht
76 77
}

78
// Connect to a new peer at the given address, ping and add to the routing table
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
79
func (dht *IpfsDHT) Connect(ctx context.Context, npeer *peer.Peer) (*peer.Peer, error) {
Jeromy's avatar
Jeromy committed
80
	log.Debug("Connect to new peer: %s\n", npeer.ID.Pretty())
81 82 83 84 85 86 87 88 89 90 91

	// 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
	//
	err := dht.network.DialPeer(npeer)
92
	if err != nil {
93
		return nil, err
94 95
	}

Jeromy's avatar
Jeromy committed
96 97
	// Ping new peer to register in their routing table
	// NOTE: this should be done better...
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98
	err = dht.Ping(ctx, npeer)
Jeromy's avatar
Jeromy committed
99
	if err != nil {
100
		return nil, fmt.Errorf("failed to ping newly connected peer: %s\n", err)
Jeromy's avatar
Jeromy committed
101 102
	}

103 104
	dht.Update(npeer)

105
	return npeer, nil
Jeromy's avatar
Jeromy committed
106 107
}

108
// HandleMessage implements the inet.Handler interface.
109
func (dht *IpfsDHT) HandleMessage(ctx context.Context, mes msg.NetMessage) msg.NetMessage {
110 111 112

	mData := mes.Data()
	if mData == nil {
113 114
		// TODO handle/log err
		return nil
115 116 117 118
	}

	mPeer := mes.Peer()
	if mPeer == nil {
119 120
		// TODO handle/log err
		return nil
121 122 123 124 125 126
	}

	// deserialize msg
	pmes := new(Message)
	err := proto.Unmarshal(mData, pmes)
	if err != nil {
127 128
		// TODO handle/log err
		return nil
129 130 131 132 133 134
	}

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

	// Print out diagnostic
Jeromy's avatar
Jeromy committed
135
	log.Debug("[peer: %s] Got message type: '%s' [from = %s]\n",
136 137 138 139 140 141
		dht.self.ID.Pretty(),
		Message_MessageType_name[int32(pmes.GetType())], mPeer.ID.Pretty())

	// get handler for this msg type.
	handler := dht.handlerForMsgType(pmes.GetType())
	if handler == nil {
142 143
		// TODO handle/log err
		return nil
144 145 146 147 148
	}

	// dispatch handler.
	rpmes, err := handler(mPeer, pmes)
	if err != nil {
149 150
		// TODO handle/log err
		return nil
151 152
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153 154
	// if nil response, return it before serializing
	if rpmes == nil {
155
		return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
156 157
	}

158 159 160
	// serialize response msg
	rmes, err := msg.FromObject(mPeer, rpmes)
	if err != nil {
161 162
		// TODO handle/log err
		return nil
163 164
	}

165
	return rmes
166 167
}

168 169 170 171 172 173 174 175 176 177 178
// sendRequest sends out a request using dht.sender, but also makes sure to
// measure the RTT for latency measurements.
func (dht *IpfsDHT) sendRequest(ctx context.Context, p *peer.Peer, pmes *Message) (*Message, error) {

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

	start := time.Now()

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179
	// Print out diagnostic
180
	log.Debug("Sent message type: '%s' [to = %s]",
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
181 182
		Message_MessageType_name[int32(pmes.GetType())], p.ID.Pretty())

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

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

	rpmes := new(Message)
	if err := proto.Unmarshal(rmes.Data(), rpmes); err != nil {
		return nil, err
	}

	return rpmes, nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202 203 204
func (dht *IpfsDHT) putValueToNetwork(ctx context.Context, p *peer.Peer,
	key string, value []byte) error {

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205 206
	pmes := newMessage(Message_PUT_VALUE, string(key), 0)
	pmes.Value = value
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208 209 210
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211 212 213 214 215

	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
216 217 218 219
}

func (dht *IpfsDHT) putProvider(ctx context.Context, p *peer.Peer, key string) error {

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220 221
	pmes := newMessage(Message_ADD_PROVIDER, string(key), 0)
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222 223 224
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
225

Jeromy's avatar
Jeromy committed
226
	log.Debug("[%s] putProvider: %s for %s", dht.self.ID.Pretty(), p.ID.Pretty(), key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227 228 229 230 231
	if *rpmes.Key != *pmes.Key {
		return errors.New("provider not added correctly")
	}

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
232 233
}

234 235 236 237
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p *peer.Peer,
	key u.Key, level int) ([]byte, []*peer.Peer, error) {

	pmes, err := dht.getValueSingle(ctx, p, key, level)
238
	if err != nil {
239
		return nil, nil, err
240 241
	}

Jeromy's avatar
Jeromy committed
242
	log.Debug("pmes.GetValue() %v", pmes.GetValue())
243
	if value := pmes.GetValue(); value != nil {
244
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
245
		log.Debug("getValueOrPeers: got value")
246
		return value, nil, nil
247
	}
248

249
	// TODO decide on providers. This probably shouldn't be happening.
250 251 252 253 254
	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
255
		log.Debug("getValueOrPeers: get from providers")
256 257
		return val, nil, nil
	}
258 259

	// Perhaps we were given closer peers
260
	var peers []*peer.Peer
261
	for _, pb := range pmes.GetCloserPeers() {
262 263 264
		if peer.ID(pb.GetId()).Equal(dht.self.ID) {
			continue
		}
265

266 267
		addr, err := ma.NewMultiaddr(pb.GetAddr())
		if err != nil {
Jeromy's avatar
Jeromy committed
268
			log.Error("%v", err.Error())
269 270
			continue
		}
271

272 273 274 275 276
		// check if we already have this peer.
		pr, _ := dht.peerstore.Get(peer.ID(pb.GetId()))
		if pr == nil {
			pr = &peer.Peer{ID: peer.ID(pb.GetId())}
			dht.peerstore.Put(pr)
277
		}
278 279
		pr.AddAddress(addr) // idempotent
		peers = append(peers, pr)
280
	}
281 282

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
295
	pmes := newMessage(Message_GET_VALUE, string(key), level)
296
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
297 298
}

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

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

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

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

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

	byt, ok := v.([]byte)
	if !ok {
		return byt, errors.New("value stored in datastore not []byte")
	}
	return byt, nil
341 342
}

343
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
344
	return dht.datastore.Put(key.DsKey(), value)
345
}
346

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

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

369
// 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
370
func (dht *IpfsDHT) Find(id peer.ID) (*peer.Peer, *kb.RoutingTable) {
371
	for _, table := range dht.routingTables {
Jeromy's avatar
Jeromy committed
372 373 374 375 376 377 378
		p := table.Find(id)
		if p != nil {
			return p, table
		}
	}
	return nil, nil
}
379

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
380 381 382
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p *peer.Peer, id peer.ID, level int) (*Message, error) {
	pmes := newMessage(Message_FIND_NODE, string(id), level)
	return dht.sendRequest(ctx, p, pmes)
383
}
384

385 386
func (dht *IpfsDHT) printTables() {
	for _, route := range dht.routingTables {
387 388 389
		route.Print()
	}
}
Jeromy's avatar
Jeromy committed
390

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
391 392 393
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p *peer.Peer, key u.Key, level int) (*Message, error) {
	pmes := newMessage(Message_GET_PROVIDERS, string(key), level)
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
394 395
}

396
// TODO: Could be done async
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
397
func (dht *IpfsDHT) addProviders(key u.Key, peers []*Message_Peer) []*peer.Peer {
398
	var provArr []*peer.Peer
Jeromy's avatar
Jeromy committed
399
	for _, prov := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
400 401
		p, err := dht.peerFromInfo(prov)
		if err != nil {
402
			log.Error("error getting peer from info: %v", err)
Jeromy's avatar
Jeromy committed
403 404
			continue
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
405

Jeromy's avatar
Jeromy committed
406
		log.Debug("[%s] adding provider: %s for %s", dht.self.ID.Pretty(), p, key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
407

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
408 409 410
		// Dont add outselves to the list
		if p.ID.Equal(dht.self.ID) {
			continue
Jeromy's avatar
Jeromy committed
411
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
412 413

		// TODO(jbenet) ensure providers is idempotent
414
		dht.providers.AddProvider(key, p)
415
		provArr = append(provArr, p)
Jeromy's avatar
Jeromy committed
416
	}
417
	return provArr
Jeromy's avatar
Jeromy committed
418
}
Jeromy's avatar
Jeromy committed
419

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
// nearestPeerToQuery returns the routing tables closest peers.
func (dht *IpfsDHT) nearestPeerToQuery(pmes *Message) *peer.Peer {
	level := pmes.GetClusterLevel()
	cluster := dht.routingTables[level]

	key := u.Key(pmes.GetKey())
	closer := cluster.NearestPeer(kb.ConvertKey(key))
	return closer
}

// betterPeerToQuery returns nearestPeerToQuery, but iff closer than self.
func (dht *IpfsDHT) betterPeerToQuery(pmes *Message) *peer.Peer {
	closer := dht.nearestPeerToQuery(pmes)

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

	// == to self? nil
	if closer.ID.Equal(dht.self.ID) {
Jeromy's avatar
Jeromy committed
441
		log.Error("Attempted to return self! this shouldnt happen...")
442 443 444 445
		return nil
	}

	// self is closer? nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
446
	key := u.Key(pmes.GetKey())
447 448 449 450 451 452 453 454
	if kb.Closer(dht.self.ID, closer.ID, key) {
		return nil
	}

	// ok seems like a closer node.
	return closer
}

455 456 457
func (dht *IpfsDHT) peerFromInfo(pbp *Message_Peer) (*peer.Peer, error) {

	id := peer.ID(pbp.GetId())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
458 459 460 461 462 463

	// continue if it's ourselves
	if id.Equal(dht.self.ID) {
		return nil, errors.New("found self")
	}

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
	p, _ := dht.peerstore.Get(id)
	if p == nil {
		p, _ = dht.Find(id)
		if p != nil {
			panic("somehow peer not getting into peerstore")
		}
	}

	if p == nil {
		maddr, err := ma.NewMultiaddr(pbp.GetAddr())
		if err != nil {
			return nil, err
		}

		// create new Peer
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
479
		p = &peer.Peer{ID: id}
480
		p.AddAddress(maddr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
481 482 483 484 485 486 487 488 489
		dht.peerstore.Put(p)
	}
	return p, nil
}

func (dht *IpfsDHT) ensureConnectedToPeer(pbp *Message_Peer) (*peer.Peer, error) {
	p, err := dht.peerFromInfo(pbp)
	if err != nil {
		return nil, err
Jeromy's avatar
Jeromy committed
490 491
	}

492
	// dial connection
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
493
	err = dht.network.DialPeer(p)
494
	return p, err
Jeromy's avatar
Jeromy committed
495
}
496

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

		dht.providers.AddProvider(k, dht.self)
510 511 512 513
	}
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
514
// Bootstrap builds up list of peers by requesting random peer IDs
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
515
func (dht *IpfsDHT) Bootstrap(ctx context.Context) {
516 517
	id := make([]byte, 16)
	rand.Read(id)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
518
	dht.FindPeer(ctx, peer.ID(id))
519
}