dht.go 10.7 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
	inet "github.com/jbenet/go-ipfs/net"
14
	peer "github.com/jbenet/go-ipfs/peer"
15
	routing "github.com/jbenet/go-ipfs/routing"
16
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
Jeromy's avatar
Jeromy committed
17
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
18
	u "github.com/jbenet/go-ipfs/util"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
19
	"github.com/jbenet/go-ipfs/util/eventlog"
20

21
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
22
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
23 24
	ctxgroup "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-ctxgroup"
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
25 26
)

27
var log = eventlog.Logger("dht")
28

29
const doPinging = false
30

31 32 33 34
// 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
35 36 37 38 39
// 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 {
40
	network   inet.Network   // the network services we need
41 42
	self      peer.ID        // Local peer (yourself)
	peerstore peer.Peerstore // Peer Registry
43

44
	datastore ds.ThreadSafeDatastore // Local data
45

46 47
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
	providers    *ProviderManager
48

49 50
	birth    time.Time  // When this peer started up
	diaglock sync.Mutex // lock to make diagnostics work better
51

52 53 54
	// record validator funcs
	Validators map[string]ValidatorFunc

55
	ctxgroup.ContextGroup
56 57
}

Jeromy's avatar
Jeromy committed
58
// NewDHT creates a new DHT object with the given peer as the 'local' host
59
func NewDHT(ctx context.Context, p peer.ID, n inet.Network, dstore ds.ThreadSafeDatastore) *IpfsDHT {
60
	dht := new(IpfsDHT)
Jeromy's avatar
Jeromy committed
61
	dht.datastore = dstore
62
	dht.self = p
63
	dht.peerstore = n.Peerstore()
64 65 66
	dht.ContextGroup = ctxgroup.WithContext(ctx)
	dht.network = n
	n.SetHandler(inet.ProtocolDHT, dht.handleNewStream)
67

68
	dht.providers = NewProviderManager(dht.Context(), p)
69
	dht.AddChildGroup(dht.providers)
70

71
	dht.routingTable = kb.NewRoutingTable(20, kb.ConvertPeerID(p), time.Minute, dht.peerstore)
72
	dht.birth = time.Now()
73

74
	dht.Validators = make(map[string]ValidatorFunc)
75
	dht.Validators["pk"] = ValidatePublicKeyRecord
76

77
	if doPinging {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
78
		dht.Children().Add(1)
79 80
		go dht.PingRoutine(time.Second * 10)
	}
Jeromy's avatar
Jeromy committed
81
	return dht
82 83
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
84 85 86 87 88
// LocalPeer returns the peer.Peer of the dht.
func (dht *IpfsDHT) LocalPeer() peer.ID {
	return dht.self
}

89
// Connect to a new peer at the given address, ping and add to the routing table
90
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.ID) error {
91
	if err := dht.network.DialPeer(ctx, npeer); err != nil {
92
		return err
93 94
	}

Jeromy's avatar
Jeromy committed
95 96
	// Ping new peer to register in their routing table
	// NOTE: this should be done better...
97
	if err := dht.Ping(ctx, npeer); err != nil {
98
		return fmt.Errorf("failed to ping newly connected peer: %s\n", err)
Jeromy's avatar
Jeromy committed
99
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
100
	log.Event(ctx, "connect", dht.self, npeer)
101
	dht.Update(ctx, npeer)
102
	return nil
Jeromy's avatar
Jeromy committed
103 104
}

105
// putValueToNetwork stores the given key/value pair at the peer 'p'
106 107
// meaning: it sends a PUT_VALUE message to p
func (dht *IpfsDHT) putValueToNetwork(ctx context.Context, p peer.ID,
108
	key string, rec *pb.Record) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109

110
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
111
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
113 114 115
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116

117
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118 119 120
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121 122
}

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

127
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
128 129

	// add self as the provider
130 131
	pi := dht.peerstore.PeerInfo(dht.self)
	pmes.ProviderPeers = pb.PeerInfosToPBPeers(dht.network, []peer.PeerInfo{pi})
132

133
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134 135 136
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138
	log.Debugf("%s putProvider: %s for %s (%s)", dht.self, p, u.Key(key), pi.Addrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139 140

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141 142
}

143 144 145 146 147 148
// 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,
	key u.Key) ([]byte, []peer.PeerInfo, error) {
149

150
	pmes, err := dht.getValueSingle(ctx, p, key)
151
	if err != nil {
152
		return nil, nil, err
153 154
	}

155
	if record := pmes.GetRecord(); record != nil {
156
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
157
		log.Debug("getValueOrPeers: got value")
158

159 160
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
161
		if err != nil {
Jeromy's avatar
Jeromy committed
162
			log.Error("Received invalid record!")
163 164 165
			return nil, nil, err
		}
		return record.GetValue(), nil, nil
166
	}
167

168
	// Perhaps we were given closer peers
169
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())
170
	if len(peers) > 0 {
171
		log.Debug("getValueOrPeers: peers")
172 173 174
		return nil, peers, nil
	}

175 176
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
177 178
}

179
// getValueSingle simply performs the get value RPC with the given parameters
180
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID,
181
	key u.Key) (*pb.Message, error) {
182

183
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
184
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
185 186
}

187
// getLocal attempts to retrieve the value from the datastore
188
func (dht *IpfsDHT) getLocal(key u.Key) ([]byte, error) {
189

Jeromy's avatar
Jeromy committed
190
	log.Debug("getLocal %s", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
191
	v, err := dht.datastore.Get(key.DsKey())
192 193 194
	if err != nil {
		return nil, err
	}
Jeromy's avatar
Jeromy committed
195
	log.Debug("found in db")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
196 197 198

	byt, ok := v.([]byte)
	if !ok {
199
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200
	}
201 202 203 204 205 206 207 208
	rec := new(pb.Record)
	err = proto.Unmarshal(byt, rec)
	if err != nil {
		return nil, err
	}

	// TODO: 'if paranoid'
	if u.Debug {
209
		err = dht.verifyRecordLocally(rec)
210
		if err != nil {
Jeromy's avatar
Jeromy committed
211
			log.Errorf("local record verify failed: %s", err)
212 213 214 215 216
			return nil, err
		}
	}

	return rec.GetValue(), nil
217 218
}

219
// putLocal stores the key value pair in the datastore
220
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
221 222 223 224 225 226 227 228 229 230
	rec, err := dht.makePutRecord(key, value)
	if err != nil {
		return err
	}
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

	return dht.datastore.Put(key.DsKey(), data)
231
}
232

233
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
234
// on the given peer.
235
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
236
	log.Event(ctx, "updatePeer", p)
237
	dht.routingTable.Update(p)
238
}
Jeromy's avatar
Jeromy committed
239

Jeromy's avatar
Jeromy committed
240
// FindLocal looks for a peer with a given ID connected to this dht and returns the peer and the table it was found in.
241
func (dht *IpfsDHT) FindLocal(id peer.ID) (peer.PeerInfo, *kb.RoutingTable) {
242
	p := dht.routingTable.Find(id)
243 244
	if p != "" {
		return dht.peerstore.PeerInfo(p), dht.routingTable
Jeromy's avatar
Jeromy committed
245
	}
246
	return peer.PeerInfo{}, nil
Jeromy's avatar
Jeromy committed
247
}
248

Jeromy's avatar
Jeromy committed
249
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
250
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
251
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252
	return dht.sendRequest(ctx, p, pmes)
253
}
254

255
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.ID, key u.Key) (*pb.Message, error) {
256
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
257
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
258 259
}

260 261 262 263 264 265
func (dht *IpfsDHT) addProviders(key u.Key, pbps []*pb.Message_Peer) []peer.ID {
	peers := pb.PBPeersToPeerInfos(pbps)

	var provArr []peer.ID
	for _, pi := range peers {
		p := pi.ID
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
266

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
267
		// Dont add outselves to the list
268
		if p == dht.self {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
269
			continue
Jeromy's avatar
Jeromy committed
270
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
271

272
		log.Debugf("%s adding provider: %s for %s", dht.self, p, key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
273
		// TODO(jbenet) ensure providers is idempotent
274
		dht.providers.AddProvider(key, p)
275
		provArr = append(provArr, p)
Jeromy's avatar
Jeromy committed
276
	}
277
	return provArr
Jeromy's avatar
Jeromy committed
278
}
Jeromy's avatar
Jeromy committed
279

280
// nearestPeersToQuery returns the routing tables closest peers.
281
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
282
	key := u.Key(pmes.GetKey())
283
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(key), count)
284 285 286
	return closer
}

287
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
288
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, count int) []peer.ID {
289
	closer := dht.nearestPeersToQuery(pmes, count)
290 291 292 293 294 295

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

296 297
	// == to self? thats bad
	for _, p := range closer {
298
		if p == dht.self {
299 300 301
			log.Error("Attempted to return self! this shouldnt happen...")
			return nil
		}
302 303
	}

304
	var filtered []peer.ID
305 306 307
	for _, p := range closer {
		// must all be closer than self
		key := u.Key(pmes.GetKey())
308
		if !kb.Closer(dht.self, p, key) {
309 310
			filtered = append(filtered, p)
		}
311 312
	}

313 314
	// ok seems like closer nodes
	return filtered
315 316
}

317 318 319
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
320 321
	}

322
	// dial connection
323
	return dht.network.DialPeer(ctx, p)
Jeromy's avatar
Jeromy committed
324
}
325

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
326
//TODO: this should be smarter about which keys it selects.
327
func (dht *IpfsDHT) loadProvidableKeys() error {
328 329 330 331
	kl, err := dht.datastore.KeyList()
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
332 333 334
	for _, dsk := range kl {
		k := u.KeyFromDsKey(dsk)
		if len(k) == 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
335
			log.Errorf("loadProvidableKeys error: %v", dsk)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
336 337 338
		}

		dht.providers.AddProvider(k, dht.self)
339 340 341 342
	}
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
343
// PingRoutine periodically pings nearest neighbors.
344
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
345 346
	defer dht.Children().Done()

347 348 349 350 351 352
	tick := time.Tick(t)
	for {
		select {
		case <-tick:
			id := make([]byte, 16)
			rand.Read(id)
353
			peers := dht.routingTable.NearestPeers(kb.ConvertKey(u.Key(id)), 5)
354
			for _, p := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
355
				ctx, _ := context.WithTimeout(dht.Context(), time.Second*5)
356 357
				err := dht.Ping(ctx, p)
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
358
					log.Errorf("Ping error: %s", err)
359 360
				}
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
361
		case <-dht.Closing():
362 363 364 365 366
			return
		}
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
367
// Bootstrap builds up list of peers by requesting random peer IDs
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
368
func (dht *IpfsDHT) Bootstrap(ctx context.Context) {
369 370

	var wg sync.WaitGroup
371
	for i := 0; i < NumBootstrapQueries; i++ {
372 373 374 375 376 377 378
		wg.Add(1)
		go func() {
			defer wg.Done()

			id := make([]byte, 16)
			rand.Read(id)
			pi, err := dht.FindPeer(ctx, peer.ID(id))
379 380 381
			if err == routing.ErrNotFound {
				// this isn't an error. this is precisely what we expect.
			} else if err != nil {
382
				log.Errorf("Bootstrap peer error: %s", err)
383 384 385
			} else {
				// woah, we got a peer under a random id? it _cannot_ be valid.
				log.Errorf("dht seemingly found a peer at a random bootstrap id (%s)...", pi)
386 387
			}
		}()
388
	}
389
	wg.Wait()
390
}