dht.go 9.65 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
	"errors"
8
	"fmt"
9 10
	"sync"
	"time"
11

12
	key "github.com/ipfs/go-ipfs/blocks/key"
13 14
	routing "github.com/ipfs/go-ipfs/routing"
	pb "github.com/ipfs/go-ipfs/routing/dht/pb"
15
	providers "github.com/ipfs/go-ipfs/routing/dht/providers"
16 17 18
	kb "github.com/ipfs/go-ipfs/routing/kbucket"
	record "github.com/ipfs/go-ipfs/routing/record"

19 20
	logging "gx/ipfs/QmNQynaz7qfriSUJkiEZUrm2Wen1u3Kj9goZzWtrPyu7XR/go-log"
	pstore "gx/ipfs/QmQdnfvZQuhdT93LNc5bos52wAmdr3G2p6G8teLJMEN32P/go-libp2p-peerstore"
21 22
	goprocess "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess"
	goprocessctx "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess/context"
23 24
	peer "gx/ipfs/QmRBqJF7hb8ZSpRcMwUt8hNhydWcxGEhtk81HKq6oUwKvs/go-libp2p-peer"
	ci "gx/ipfs/QmUWER4r4qMvaCnX5zREcfyiWN7cXN9g3a7fkRqNz8qWPP/go-libp2p-crypto"
Jeromy's avatar
Jeromy committed
25
	proto "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/proto"
Jakub Sztandera's avatar
Jakub Sztandera committed
26
	ds "gx/ipfs/QmZ6A6P6AMo8SR3jXAwzTuSU6B9R2Y4eqW2yW9VvfUayDN/go-datastore"
27 28
	host "gx/ipfs/QmZ8bCZpMWDbFSh6h2zgTYwrhnjrGM5c9WCzw72SU8p63b/go-libp2p/p2p/host"
	protocol "gx/ipfs/QmZ8bCZpMWDbFSh6h2zgTYwrhnjrGM5c9WCzw72SU8p63b/go-libp2p/p2p/protocol"
29
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
30 31
)

Jeromy's avatar
Jeromy committed
32
var log = logging.Logger("dht")
33

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

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 {
Jeromy's avatar
Jeromy committed
45 46 47
	host      host.Host        // the network services we need
	self      peer.ID          // Local peer (yourself)
	peerstore pstore.Peerstore // Peer Registry
48

49
	datastore ds.Datastore // Local data
50

51
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
52
	providers    *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
	Selector  record.Selector  // record selection funcs
59

60 61
	ctx  context.Context
	proc goprocess.Process
62 63 64

	strmap map[peer.ID]*messageSender
	smlk   sync.Mutex
65 66
}

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

75 76 77
	// register for network notifs.
	dht.host.Network().Notify((*netNotifiee)(dht))

rht's avatar
rht committed
78
	dht.proc = goprocess.WithTeardown(func() error {
79 80 81 82
		// remove ourselves from network notifs.
		dht.host.Network().StopNotify((*netNotifiee)(dht))
		return nil
	})
83

84
	dht.strmap = make(map[peer.ID]*messageSender)
85
	dht.ctx = ctx
86

87
	h.SetStreamHandler(ProtocolDHT, dht.handleNewStream)
88 89
	dht.providers = providers.NewProviderManager(dht.ctx, dht.self, dstore)
	dht.proc.AddChild(dht.providers.Process())
rht's avatar
rht committed
90
	goprocessctx.CloseAfterContext(dht.proc, ctx)
91

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

95
	dht.Validator = make(record.Validator)
96
	dht.Validator["pk"] = record.PublicKeyValidator
97

98 99 100
	dht.Selector = make(record.Selector)
	dht.Selector["pk"] = record.PublicKeySelector

Jeromy's avatar
Jeromy committed
101
	return dht
102 103
}

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

108
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
109
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110
	rpmes, err := dht.sendRequest(ctx, p, pmes)
111 112
	switch err {
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
113
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
114 115 116 117 118 119 120
		fallthrough
	default:
		return err
	case nil:
		break
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121 122 123
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124

125
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
126 127 128
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129 130
}

131 132
var errInvalidRecord = errors.New("received invalid record")

133 134
// getValueOrPeers queries a particular peer p for the value for
// key. It returns either the value or a list of closer peers.
135
// NOTE: It will update the dht's peerstore with any new addresses
136 137
// it finds for the given peer.
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.ID,
Jeromy's avatar
Jeromy committed
138
	key key.Key) (*pb.Record, []pstore.PeerInfo, error) {
139

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

145 146 147
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

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

152 153
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
154
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155
			log.Info("Received invalid record! (discarded)")
156 157
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
158
			record = new(pb.Record)
159
		}
160
		return record, peers, err
161
	}
162

163
	if len(peers) > 0 {
164
		log.Debug("getValueOrPeers: peers")
165 166 167
		return nil, peers, nil
	}

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

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

177
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
178 179 180 181 182
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
183
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
184 185 186 187
		fallthrough
	default:
		return nil, err
	}
Jeromy's avatar
Jeromy committed
188 189
}

190
// getLocal attempts to retrieve the value from the datastore
191
func (dht *IpfsDHT) getLocal(key key.Key) (*pb.Record, error) {
192

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

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

Jeromy's avatar
Jeromy committed
210 211 212 213
	err = dht.verifyRecordLocally(rec)
	if err != nil {
		log.Debugf("local record verify failed: %s (discarded)", err)
		return nil, err
214 215
	}

216
	return rec, nil
217 218
}

Jeromy's avatar
Jeromy committed
219 220
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
Jeromy's avatar
Jeromy committed
221 222 223
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
224
		log.Warningf("%s dht cannot get own private key!", dht.self)
Jeromy's avatar
Jeromy committed
225 226 227 228 229
		return nil, fmt.Errorf("cannot get private key to sign record!")
	}
	return sk, nil
}

230
// putLocal stores the key value pair in the datastore
231
func (dht *IpfsDHT) putLocal(key key.Key, rec *pb.Record) error {
232 233 234 235 236 237
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

	return dht.datastore.Put(key.DsKey(), data)
238
}
239

240
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241
// on the given peer.
242
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
243
	log.Event(ctx, "updatePeer", p)
244
	dht.routingTable.Update(p)
245
}
Jeromy's avatar
Jeromy committed
246

Jeromy's avatar
Jeromy committed
247
// 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
248
func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
249
	p := dht.routingTable.Find(id)
250
	if p != "" {
Jeromy's avatar
Jeromy committed
251
		return dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
252
	}
Jeromy's avatar
Jeromy committed
253
	return pstore.PeerInfo{}
Jeromy's avatar
Jeromy committed
254
}
255

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

260
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
261 262 263 264 265
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
266
		log.Warningf("read timeout: %s %s", p.Pretty(), id)
267 268 269 270
		fallthrough
	default:
		return nil, err
	}
271
}
272

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

276
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
277 278 279 280 281
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
282
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
283 284 285 286
		fallthrough
	default:
		return nil, err
	}
Jeromy's avatar
Jeromy committed
287 288
}

289
// nearestPeersToQuery returns the routing tables closest peers.
290
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
291
	key := key.Key(pmes.GetKey())
292
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(key), count)
293 294 295
	return closer
}

296
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
297
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
298
	closer := dht.nearestPeersToQuery(pmes, count)
299 300 301 302 303 304

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

305 306
	// == to self? thats bad
	for _, p := range closer {
307
		if p == dht.self {
308
			log.Debug("attempted to return self! this shouldn't happen...")
309 310
			return nil
		}
311 312
	}

313
	var filtered []peer.ID
314 315 316 317 318 319
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

Jeromy's avatar
Jeromy committed
320
		filtered = append(filtered, clp)
321 322
	}

323 324
	// ok seems like closer nodes
	return filtered
325 326
}

327 328 329 330 331 332 333 334 335 336 337 338 339 340
// Context return dht's context
func (dht *IpfsDHT) Context() context.Context {
	return dht.ctx
}

// Process return dht's process
func (dht *IpfsDHT) Process() goprocess.Process {
	return dht.proc
}

// Close calls Process Close
func (dht *IpfsDHT) Close() error {
	return dht.proc.Close()
}