dht.go 11.1 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1
// Package dht implements a distributed hash table that satisfies the ipfs routing
2
// 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
	key "github.com/ipfs/go-ipfs/blocks/key"
14 15 16 17 18 19 20 21 22 23 24
	ci "github.com/ipfs/go-ipfs/p2p/crypto"
	host "github.com/ipfs/go-ipfs/p2p/host"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	protocol "github.com/ipfs/go-ipfs/p2p/protocol"
	routing "github.com/ipfs/go-ipfs/routing"
	pb "github.com/ipfs/go-ipfs/routing/dht/pb"
	kb "github.com/ipfs/go-ipfs/routing/kbucket"
	record "github.com/ipfs/go-ipfs/routing/record"
	"github.com/ipfs/go-ipfs/thirdparty/eventlog"
	u "github.com/ipfs/go-ipfs/util"

25
	proto "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/gogo/protobuf/proto"
26
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
27 28
	goprocess "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
	goprocessctx "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess/context"
29
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
30 31
)

32
var log = eventlog.Logger("dht")
33

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34 35
var ProtocolDHT protocol.ID = "/ipfs/dht"

36
const doPinging = false
37

38 39 40 41
// NumBootstrapQueries defines the number of random dht queries to do to
// collect members of the routing table.
const NumBootstrapQueries = 5

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42 43 44 45 46
// 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 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47
	host      host.Host      // the network services we need
48 49
	self      peer.ID        // Local peer (yourself)
	peerstore peer.Peerstore // Peer Registry
50

51
	datastore ds.ThreadSafeDatastore // Local data
52

53 54
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
	providers    *ProviderManager
55

56 57
	birth    time.Time  // When this peer started up
	diaglock sync.Mutex // lock to make diagnostics work better
58

59
	Validator record.Validator // record validator funcs
60

61 62
	ctx  context.Context
	proc goprocess.Process
63 64
}

Jeromy's avatar
Jeromy committed
65
// NewDHT creates a new DHT object with the given peer as the 'local' host
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
66
func NewDHT(ctx context.Context, h host.Host, dstore ds.ThreadSafeDatastore) *IpfsDHT {
67
	dht := new(IpfsDHT)
Jeromy's avatar
Jeromy committed
68
	dht.datastore = dstore
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69 70 71
	dht.self = h.ID()
	dht.peerstore = h.Peerstore()
	dht.host = h
72

73 74 75
	// register for network notifs.
	dht.host.Network().Notify((*netNotifiee)(dht))

76 77
	proc := goprocessctx.WithContext(ctx)
	proc.SetTeardown(func() error {
78 79 80 81
		// remove ourselves from network notifs.
		dht.host.Network().StopNotify((*netNotifiee)(dht))
		return nil
	})
82 83
	dht.proc = proc
	dht.ctx = ctx
84

85
	h.SetStreamHandler(ProtocolDHT, dht.handleNewStream)
86 87
	dht.providers = NewProviderManager(dht.ctx, dht.self)
	dht.proc.AddChild(dht.providers.proc)
88

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
89
	dht.routingTable = kb.NewRoutingTable(20, kb.ConvertPeerID(dht.self), time.Minute, dht.peerstore)
90
	dht.birth = time.Now()
91

92
	dht.Validator = make(record.Validator)
93
	dht.Validator["pk"] = record.PublicKeyValidator
94

95
	if doPinging {
96 97 98
		dht.proc.Go(func(p goprocess.Process) {
			dht.PingRoutine(time.Second * 10)
		})
99
	}
Jeromy's avatar
Jeromy committed
100
	return dht
101 102
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103 104 105 106 107
// LocalPeer returns the peer.Peer of the dht.
func (dht *IpfsDHT) LocalPeer() peer.ID {
	return dht.self
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108 109
// log returns the dht's logger
func (dht *IpfsDHT) log() eventlog.EventLogger {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
110
	return log // TODO rm
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111 112
}

113
// Connect to a new peer at the given address, ping and add to the routing table
114
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.ID) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115 116
	// TODO: change interface to accept a PeerInfo as well.
	if err := dht.host.Connect(ctx, peer.PeerInfo{ID: npeer}); err != nil {
117
		return err
118 119
	}

Jeromy's avatar
Jeromy committed
120 121
	// Ping new peer to register in their routing table
	// NOTE: this should be done better...
122 123
	if _, err := dht.Ping(ctx, npeer); err != nil {
		return fmt.Errorf("failed to ping newly connected peer: %s", err)
Jeromy's avatar
Jeromy committed
124
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
125
	log.Event(ctx, "connect", dht.self, npeer)
126
	dht.Update(ctx, npeer)
127
	return nil
Jeromy's avatar
Jeromy committed
128 129
}

Jeromy's avatar
Jeromy committed
130 131
// putValueToPeer stores the given key/value pair at the peer 'p'
func (dht *IpfsDHT) putValueToPeer(ctx context.Context, p peer.ID,
132
	key key.Key, rec *pb.Record) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133

134
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
135
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137 138 139
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140

141
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142 143 144
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145 146
}

Jeromy's avatar
Jeromy committed
147 148
// putProvider sends a message to peer 'p' saying that the local node
// can provide the value of 'key'
149
func (dht *IpfsDHT) putProvider(ctx context.Context, p peer.ID, skey string) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150

151
	// add self as the provider
152 153 154 155 156
	pi := peer.PeerInfo{
		ID:    dht.self,
		Addrs: dht.host.Addrs(),
	}

157 158 159
	// // only share WAN-friendly addresses ??
	// pi.Addrs = addrutil.WANShareableAddrs(pi.Addrs)
	if len(pi.Addrs) < 1 {
160
		// log.Infof("%s putProvider: %s for %s error: no wan-friendly addresses", dht.self, p, key.Key(key), pi.Addrs)
161 162
		return fmt.Errorf("no known addresses for self. cannot put provider.")
	}
163

164
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, skey, 0)
165
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]peer.PeerInfo{pi})
166
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167 168 169
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170

171
	log.Debugf("%s putProvider: %s for %s (%s)", dht.self, p, key.Key(skey), pi.Addrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173 174
}

175 176 177 178 179
// getValueOrPeers queries a particular peer p for the value for
// key. It returns either the value or a list of closer peers.
// NOTE: it will update the dht's peerstore with any new addresses
// it finds for the given peer.
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.ID,
180
	key key.Key) ([]byte, []peer.PeerInfo, error) {
181

182
	pmes, err := dht.getValueSingle(ctx, p, key)
183
	if err != nil {
184
		return nil, nil, err
185 186
	}

187
	if record := pmes.GetRecord(); record != nil {
188
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
189
		log.Debug("getValueOrPeers: got value")
190

191 192
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
193
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194
			log.Info("Received invalid record! (discarded)")
195 196 197
			return nil, nil, err
		}
		return record.GetValue(), nil, nil
198
	}
199

200
	// Perhaps we were given closer peers
201
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())
202
	if len(peers) > 0 {
203
		log.Debug("getValueOrPeers: peers")
204 205 206
		return nil, peers, nil
	}

207 208
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
209 210
}

211
// getValueSingle simply performs the get value RPC with the given parameters
212
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID,
213
	key key.Key) (*pb.Message, error) {
Jeromy's avatar
Jeromy committed
214
	defer log.EventBegin(ctx, "getValueSingle", p, &key).Done()
215

216
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
217
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
218 219
}

220
// getLocal attempts to retrieve the value from the datastore
221
func (dht *IpfsDHT) getLocal(key key.Key) ([]byte, error) {
222

Jeromy's avatar
Jeromy committed
223
	log.Debug("getLocal %s", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224
	v, err := dht.datastore.Get(key.DsKey())
225 226 227
	if err != nil {
		return nil, err
	}
Jeromy's avatar
Jeromy committed
228
	log.Debug("found in db")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
229 230 231

	byt, ok := v.([]byte)
	if !ok {
232
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
233
	}
234 235 236 237 238 239 240 241
	rec := new(pb.Record)
	err = proto.Unmarshal(byt, rec)
	if err != nil {
		return nil, err
	}

	// TODO: 'if paranoid'
	if u.Debug {
242
		err = dht.verifyRecordLocally(rec)
243
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244
			log.Debugf("local record verify failed: %s (discarded)", err)
245 246 247 248 249
			return nil, err
		}
	}

	return rec.GetValue(), nil
250 251
}

Jeromy's avatar
Jeromy committed
252 253
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
Jeromy's avatar
Jeromy committed
254 255 256
func (dht *IpfsDHT) getOwnPrivateKey() (ci.PrivKey, error) {
	sk := dht.peerstore.PrivKey(dht.self)
	if sk == nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
257
		log.Warningf("%s dht cannot get own private key!", dht.self)
Jeromy's avatar
Jeromy committed
258 259 260 261 262
		return nil, fmt.Errorf("cannot get private key to sign record!")
	}
	return sk, nil
}

263
// putLocal stores the key value pair in the datastore
264
func (dht *IpfsDHT) putLocal(key key.Key, rec *pb.Record) error {
265 266 267 268 269 270
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

	return dht.datastore.Put(key.DsKey(), data)
271
}
272

273
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
274
// on the given peer.
275
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
276
	log.Event(ctx, "updatePeer", p)
277
	dht.routingTable.Update(p)
278
}
Jeromy's avatar
Jeromy committed
279

Jeromy's avatar
Jeromy committed
280
// FindLocal 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
281
func (dht *IpfsDHT) FindLocal(id peer.ID) peer.PeerInfo {
282
	p := dht.routingTable.Find(id)
283
	if p != "" {
Jeromy's avatar
Jeromy committed
284
		return dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
285
	}
Jeromy's avatar
Jeromy committed
286
	return peer.PeerInfo{}
Jeromy's avatar
Jeromy committed
287
}
288

Jeromy's avatar
Jeromy committed
289
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
290
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
Jeromy's avatar
Jeromy committed
291
	defer log.EventBegin(ctx, "findPeerSingle", p, id).Done()
292

293
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294
	return dht.sendRequest(ctx, p, pmes)
295
}
296

297
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.ID, key key.Key) (*pb.Message, error) {
Jeromy's avatar
Jeromy committed
298
	defer log.EventBegin(ctx, "findProvidersSingle", p, &key).Done()
299

300
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
301
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
302 303
}

304
// nearestPeersToQuery returns the routing tables closest peers.
305
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
306
	key := key.Key(pmes.GetKey())
307
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(key), count)
308 309 310
	return closer
}

311
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
312
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
313
	closer := dht.nearestPeersToQuery(pmes, count)
314 315 316 317 318 319

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

320 321
	// == to self? thats bad
	for _, p := range closer {
322
		if p == dht.self {
Jeromy's avatar
Jeromy committed
323
			log.Debug("Attempted to return self! this shouldnt happen...")
324 325
			return nil
		}
326 327
	}

328
	var filtered []peer.ID
329 330 331 332 333 334
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

335
		// must all be closer than self
336
		key := key.Key(pmes.GetKey())
337 338
		if !kb.Closer(dht.self, clp, key) {
			filtered = append(filtered, clp)
339
		}
340 341
	}

342 343
	// ok seems like closer nodes
	return filtered
344 345
}

346 347 348
func (dht *IpfsDHT) ensureConnectedToPeer(ctx context.Context, p peer.ID) error {
	if p == dht.self {
		return errors.New("attempting to ensure connection to self")
Jeromy's avatar
Jeromy committed
349 350
	}

351
	// dial connection
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
352
	return dht.host.Connect(ctx, peer.PeerInfo{ID: p})
Jeromy's avatar
Jeromy committed
353
}
354

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
355
// PingRoutine periodically pings nearest neighbors.
356 357 358 359 360 361 362
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
	tick := time.Tick(t)
	for {
		select {
		case <-tick:
			id := make([]byte, 16)
			rand.Read(id)
363
			peers := dht.routingTable.NearestPeers(kb.ConvertKey(key.Key(id)), 5)
364
			for _, p := range peers {
365
				ctx, cancel := context.WithTimeout(dht.Context(), time.Second*5)
366
				_, err := dht.Ping(ctx, p)
367
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
368
					log.Debugf("Ping error: %s", err)
369
				}
370
				cancel()
371
			}
372
		case <-dht.proc.Closing():
373 374 375 376
			return
		}
	}
}
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391

// Context return dht's context
func (dht *IpfsDHT) Context() context.Context {
	return dht.ctx
}

// Process return dht's process
func (dht *IpfsDHT) Process() goprocess.Process {
	return dht.proc
}

// Close calls Process Close
func (dht *IpfsDHT) Close() error {
	return dht.proc.Close()
}