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

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 27 28
	ctxgroup "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-ctxgroup"
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
29 30
)

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

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

35
const doPinging = false
36

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

50
	datastore ds.ThreadSafeDatastore // Local data
51

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

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

58
	Validator record.Validator // record validator funcs
59

60
	ctxgroup.ContextGroup
61 62
}

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

71 72 73 74 75 76 77 78 79
	// 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
	})

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

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

87
	dht.Validator = make(record.Validator)
88
	dht.Validator["pk"] = record.PublicKeyValidator
89

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

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

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

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

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

128
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
129
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
130
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131 132 133
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134

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

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

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

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

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

165
	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
166
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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,
174
	key key.Key) ([]byte, []peer.PeerInfo, error) {
175

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

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

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

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

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

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

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

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

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

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

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

	return rec.GetValue(), nil
244 245
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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