dht.go 10.4 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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31 32 33 34 35
// 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 {
36
	network   inet.Network   // the network services we need
37 38
	self      peer.ID        // Local peer (yourself)
	peerstore peer.Peerstore // Peer Registry
39

40
	datastore ds.ThreadSafeDatastore // Local data
41

42 43
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
	providers    *ProviderManager
44

45 46
	birth    time.Time  // When this peer started up
	diaglock sync.Mutex // lock to make diagnostics work better
47

48 49 50
	// record validator funcs
	Validators map[string]ValidatorFunc

51
	ctxgroup.ContextGroup
52 53
}

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

64
	dht.providers = NewProviderManager(dht.Context(), p)
65
	dht.AddChildGroup(dht.providers)
66

67
	dht.routingTable = kb.NewRoutingTable(20, kb.ConvertPeerID(p), time.Minute, dht.peerstore)
68
	dht.birth = time.Now()
69

70
	dht.Validators = make(map[string]ValidatorFunc)
71
	dht.Validators["pk"] = ValidatePublicKeyRecord
72

73
	if doPinging {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74
		dht.Children().Add(1)
75 76
		go dht.PingRoutine(time.Second * 10)
	}
Jeromy's avatar
Jeromy committed
77
	return dht
78 79
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
80 81 82 83 84
// LocalPeer returns the peer.Peer of the dht.
func (dht *IpfsDHT) LocalPeer() peer.ID {
	return dht.self
}

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

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

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

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

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

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

123
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
124 125

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

129
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130 131 132
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
	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
135 136

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137 138
}

139 140 141 142 143 144
// 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) {
145

146
	pmes, err := dht.getValueSingle(ctx, p, key)
147
	if err != nil {
148
		return nil, nil, err
149 150
	}

151
	if record := pmes.GetRecord(); record != nil {
152
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
153
		log.Debug("getValueOrPeers: got value")
154

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

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

171 172
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
173 174
}

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

179
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
180
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
181 182
}

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

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

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

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

	return rec.GetValue(), nil
213 214
}

215
// putLocal stores the key value pair in the datastore
216
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
217 218 219 220 221 222 223 224 225 226
	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)
227
}
228

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

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

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

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

256 257 258 259 260 261
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
262

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
263
		// Dont add outselves to the list
264
		if p == dht.self {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
265
			continue
Jeromy's avatar
Jeromy committed
266
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
267

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

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

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

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

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

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

309 310
	// ok seems like closer nodes
	return filtered
311 312
}

313 314 315
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
316 317
	}

318
	// dial connection
319
	return dht.network.DialPeer(ctx, p)
Jeromy's avatar
Jeromy committed
320
}
321

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

		dht.providers.AddProvider(k, dht.self)
335 336 337 338
	}
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
339
// PingRoutine periodically pings nearest neighbors.
340
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
341 342
	defer dht.Children().Done()

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
363
// Bootstrap builds up list of peers by requesting random peer IDs
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
364
func (dht *IpfsDHT) Bootstrap(ctx context.Context) {
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()

			id := make([]byte, 16)
			rand.Read(id)
			pi, err := dht.FindPeer(ctx, peer.ID(id))
			if err != nil {
				// NOTE: this is not an error. this is expected!
				log.Errorf("Bootstrap peer error: %s", err)
			}

			// 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)
		}()
383
	}
384
	wg.Wait()
385
}