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

Jeromy's avatar
Jeromy committed
13
	ci "github.com/jbenet/go-ipfs/p2p/crypto"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14
	host "github.com/jbenet/go-ipfs/p2p/host"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
	peer "github.com/jbenet/go-ipfs/p2p/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16
	protocol "github.com/jbenet/go-ipfs/p2p/protocol"
17
	routing "github.com/jbenet/go-ipfs/routing"
18
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
Jeromy's avatar
Jeromy committed
19
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
Jeromy's avatar
Jeromy committed
20
	record "github.com/jbenet/go-ipfs/routing/record"
21
	"github.com/jbenet/go-ipfs/thirdparty/eventlog"
22
	u "github.com/jbenet/go-ipfs/util"
23

24
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
25 26
	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"
27
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
28 29
)

30
var log = eventlog.Logger("dht")
31

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

34
const doPinging = false
35

36 37 38 39
// 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
40 41 42 43 44
// 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
45
	host      host.Host      // the network services we need
46 47
	self      peer.ID        // Local peer (yourself)
	peerstore peer.Peerstore // Peer Registry
48

49
	datastore ds.ThreadSafeDatastore // Local data
50

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

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

57
	Validator record.Validator // record validator funcs
58

59
	ctxgroup.ContextGroup
60 61
}

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

70 71 72 73 74 75 76 77 78
	// register for network notifs.
	dht.host.Network().Notify((*netNotifiee)(dht))

	dht.ContextGroup = ctxgroup.WithContextAndTeardown(ctx, func() error {
		// remove ourselves from network notifs.
		dht.host.Network().StopNotify((*netNotifiee)(dht))
		return nil
	})

79
	h.SetStreamHandler(ProtocolDHT, dht.handleNewStream)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
80
	dht.providers = NewProviderManager(dht.Context(), dht.self)
81
	dht.AddChild(dht.providers)
82

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

86 87
	dht.Validator = make(record.Validator)
	dht.Validator["pk"] = record.ValidatePublicKeyRecord
88

89
	if doPinging {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90
		dht.Children().Add(1)
91 92
		go dht.PingRoutine(time.Second * 10)
	}
Jeromy's avatar
Jeromy committed
93
	return dht
94 95
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96 97 98 99 100
// 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
101 102
// log returns the dht's logger
func (dht *IpfsDHT) log() eventlog.EventLogger {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
103
	return log // TODO rm
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104 105
}

106
// Connect to a new peer at the given address, ping and add to the routing table
107
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.ID) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108 109
	// TODO: change interface to accept a PeerInfo as well.
	if err := dht.host.Connect(ctx, peer.PeerInfo{ID: npeer}); err != nil {
110
		return err
111 112
	}

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

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

127
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
128
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
	rpmes, err := dht.sendRequest(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

134
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135 136 137
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138 139
}

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

144
	// add self as the provider
145 146 147 148 149
	pi := peer.PeerInfo{
		ID:    dht.self,
		Addrs: dht.host.Addrs(),
	}

150 151 152
	// // only share WAN-friendly addresses ??
	// pi.Addrs = addrutil.WANShareableAddrs(pi.Addrs)
	if len(pi.Addrs) < 1 {
153
		// log.Infof("%s putProvider: %s for %s error: no wan-friendly addresses", dht.self, p, u.Key(key), pi.Addrs)
154 155
		return fmt.Errorf("no known addresses for self. cannot put provider.")
	}
156

157
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
158
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]peer.PeerInfo{pi})
159
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160 161 162
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164
	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
165
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
166 167
}

168 169 170 171 172 173
// 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) {
174

175
	pmes, err := dht.getValueSingle(ctx, p, key)
176
	if err != nil {
177
		return nil, nil, err
178 179
	}

180
	if record := pmes.GetRecord(); record != nil {
181
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
182
		log.Debug("getValueOrPeers: got value")
183

184 185
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
186
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187
			log.Info("Received invalid record! (discarded)")
188 189 190
			return nil, nil, err
		}
		return record.GetValue(), nil, nil
191
	}
192

193
	// Perhaps we were given closer peers
194
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())
195
	if len(peers) > 0 {
196
		log.Debug("getValueOrPeers: peers")
197 198 199
		return nil, peers, nil
	}

200 201
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
202 203
}

204
// getValueSingle simply performs the get value RPC with the given parameters
205
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID,
206
	key u.Key) (*pb.Message, error) {
Jeromy's avatar
Jeromy committed
207
	defer log.EventBegin(ctx, "getValueSingle", p, &key).Done()
208

209
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
210
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
211 212
}

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

Jeromy's avatar
Jeromy committed
216
	log.Debug("getLocal %s", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217
	v, err := dht.datastore.Get(key.DsKey())
218 219 220
	if err != nil {
		return nil, err
	}
Jeromy's avatar
Jeromy committed
221
	log.Debug("found in db")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222 223 224

	byt, ok := v.([]byte)
	if !ok {
225
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
226
	}
227 228 229 230 231 232 233 234
	rec := new(pb.Record)
	err = proto.Unmarshal(byt, rec)
	if err != nil {
		return nil, err
	}

	// TODO: 'if paranoid'
	if u.Debug {
235
		err = dht.verifyRecordLocally(rec)
236
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237
			log.Debugf("local record verify failed: %s (discarded)", err)
238 239 240 241 242
			return nil, err
		}
	}

	return rec.GetValue(), nil
243 244
}

Jeromy's avatar
Jeromy committed
245 246
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
Jeromy's avatar
Jeromy committed
247 248 249
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
250
		log.Warningf("%s dht cannot get own private key!", dht.self)
Jeromy's avatar
Jeromy committed
251 252 253 254 255
		return nil, fmt.Errorf("cannot get private key to sign record!")
	}
	return sk, nil
}

256
// putLocal stores the key value pair in the datastore
Jeromy's avatar
Jeromy committed
257
func (dht *IpfsDHT) putLocal(key u.Key, rec *pb.Record) error {
258 259 260 261 262 263
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

	return dht.datastore.Put(key.DsKey(), data)
264
}
265

266
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
267
// on the given peer.
268
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
269
	log.Event(ctx, "updatePeer", p)
270
	dht.routingTable.Update(p)
271
}
Jeromy's avatar
Jeromy committed
272

Jeromy's avatar
Jeromy committed
273
// 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
274
func (dht *IpfsDHT) FindLocal(id peer.ID) peer.PeerInfo {
275
	p := dht.routingTable.Find(id)
276
	if p != "" {
Jeromy's avatar
Jeromy committed
277
		return dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
278
	}
Jeromy's avatar
Jeromy committed
279
	return peer.PeerInfo{}
Jeromy's avatar
Jeromy committed
280
}
281

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

286
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
287
	return dht.sendRequest(ctx, p, pmes)
288
}
289

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

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

297
// nearestPeersToQuery returns the routing tables closest peers.
298
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
299
	key := u.Key(pmes.GetKey())
300
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(key), count)
301 302 303
	return closer
}

304
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
305
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
306
	closer := dht.nearestPeersToQuery(pmes, count)
307 308 309 310 311 312

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

313 314
	// == to self? thats bad
	for _, p := range closer {
315
		if p == dht.self {
Jeromy's avatar
Jeromy committed
316
			log.Info("Attempted to return self! this shouldnt happen...")
317 318
			return nil
		}
319 320
	}

321
	var filtered []peer.ID
322 323 324 325 326 327
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

328 329
		// must all be closer than self
		key := u.Key(pmes.GetKey())
330 331
		if !kb.Closer(dht.self, clp, key) {
			filtered = append(filtered, clp)
332
		}
333 334
	}

335 336
	// ok seems like closer nodes
	return filtered
337 338
}

339 340 341
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
342 343
	}

344
	// dial connection
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
345
	return dht.host.Connect(ctx, peer.PeerInfo{ID: p})
Jeromy's avatar
Jeromy committed
346
}
347

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
348
// PingRoutine periodically pings nearest neighbors.
349
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
350 351
	defer dht.Children().Done()

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