dht.go 10.3 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
}

80
// Connect to a new peer at the given address, ping and add to the routing table
81
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.ID) error {
82
	if err := dht.network.DialPeer(ctx, npeer); err != nil {
83
		return 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
	if err := dht.Ping(ctx, npeer); err != nil {
89
		return fmt.Errorf("failed to ping newly connected peer: %s\n", err)
Jeromy's avatar
Jeromy committed
90
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
91
	log.Event(ctx, "connect", dht.self, npeer)
92
	dht.Update(ctx, npeer)
93
	return nil
Jeromy's avatar
Jeromy committed
94 95
}

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

101
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
102
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104 105 106
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
107

108
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109 110 111
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112 113
}

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

118
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
119 120

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

124
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125 126 127
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
128

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
	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
130 131

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132 133
}

134 135 136 137 138 139
// 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) {
140

141
	pmes, err := dht.getValueSingle(ctx, p, key)
142
	if err != nil {
143
		return nil, nil, err
144 145
	}

146
	if record := pmes.GetRecord(); record != nil {
147
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
148
		log.Debug("getValueOrPeers: got value")
149

150 151
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
152
		if err != nil {
Jeromy's avatar
Jeromy committed
153
			log.Error("Received invalid record!")
154 155 156
			return nil, nil, err
		}
		return record.GetValue(), nil, nil
157
	}
158

159
	// Perhaps we were given closer peers
160
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())
161
	if len(peers) > 0 {
162
		log.Debug("getValueOrPeers: peers")
163 164 165
		return nil, peers, nil
	}

166 167
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
168 169
}

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

174
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
175
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
176 177
}

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

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

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

	// TODO: 'if paranoid'
	if u.Debug {
200
		err = dht.verifyRecordLocally(rec)
201
		if err != nil {
Jeromy's avatar
Jeromy committed
202
			log.Errorf("local record verify failed: %s", err)
203 204 205 206 207
			return nil, err
		}
	}

	return rec.GetValue(), nil
208 209
}

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

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

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

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

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

251 252 253 254 255 256
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
257

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
258
		// Dont add outselves to the list
259
		if p == dht.self {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
260
			continue
Jeromy's avatar
Jeromy committed
261
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
262

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

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

278
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
279
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, count int) []peer.ID {
280
	closer := dht.nearestPeersToQuery(pmes, count)
281 282 283 284 285 286

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

287 288
	// == to self? thats bad
	for _, p := range closer {
289
		if p == dht.self {
290 291 292
			log.Error("Attempted to return self! this shouldnt happen...")
			return nil
		}
293 294
	}

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

304 305
	// ok seems like closer nodes
	return filtered
306 307
}

308 309 310
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
311 312
	}

313
	// dial connection
314
	return dht.network.DialPeer(ctx, p)
Jeromy's avatar
Jeromy committed
315
}
316

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

		dht.providers.AddProvider(k, dht.self)
330 331 332 333
	}
	return nil
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
334
// PingRoutine periodically pings nearest neighbors.
335
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
336 337
	defer dht.Children().Done()

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

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

	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)
		}()
378
	}
379
	wg.Wait()
380
}