dht.go 9.38 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 13
	proto "github.com/gogo/protobuf/proto"
	ds "github.com/ipfs/go-datastore"
George Antoniadis's avatar
George Antoniadis committed
14
	key "github.com/ipfs/go-key"
15 16 17 18 19 20
	ci "github.com/ipfs/go-libp2p-crypto"
	peer "github.com/ipfs/go-libp2p-peer"
	pstore "github.com/ipfs/go-libp2p-peerstore"
	logging "github.com/ipfs/go-log"
	goprocess "github.com/jbenet/goprocess"
	goprocessctx "github.com/jbenet/goprocess/context"
George Antoniadis's avatar
George Antoniadis committed
21 22 23 24
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
	providers "github.com/libp2p/go-libp2p-kad-dht/providers"
	kb "github.com/libp2p/go-libp2p-kbucket"
	record "github.com/libp2p/go-libp2p-record"
George Antoniadis's avatar
George Antoniadis committed
25
	recpb "github.com/libp2p/go-libp2p-record/pb"
George Antoniadis's avatar
George Antoniadis committed
26 27 28
	routing "github.com/libp2p/go-libp2p-routing"
	host "github.com/libp2p/go-libp2p/p2p/host"
	protocol "github.com/libp2p/go-libp2p/p2p/protocol"
29
	context "golang.org/x/net/context"
30 31
)

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

Jeromy's avatar
Jeromy committed
34 35
var ProtocolDHT protocol.ID = "/ipfs/kad/1.0.0"
var ProtocolDHTOld protocol.ID = "/ipfs/dht"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
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 {
Jeromy's avatar
Jeromy committed
46 47 48
	host      host.Host        // the network services we need
	self      peer.ID          // Local peer (yourself)
	peerstore pstore.Peerstore // Peer Registry
49

50
	datastore ds.Datastore // Local data
51

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

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

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

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

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

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

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

88
	h.SetStreamHandler(ProtocolDHT, dht.handleNewStream)
Jeromy's avatar
Jeromy committed
89 90
	h.SetStreamHandler(ProtocolDHTOld, dht.handleNewStream)

91 92
	dht.providers = providers.NewProviderManager(dht.ctx, dht.self, dstore)
	dht.proc.AddChild(dht.providers.Process())
rht's avatar
rht committed
93
	goprocessctx.CloseAfterContext(dht.proc, ctx)
94

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

98
	dht.Validator = make(record.Validator)
99
	dht.Validator["pk"] = record.PublicKeyValidator
100

101 102 103
	dht.Selector = make(record.Selector)
	dht.Selector["pk"] = record.PublicKeySelector

Jeromy's avatar
Jeromy committed
104
	return dht
105 106
}

Jeromy's avatar
Jeromy committed
107 108
// putValueToPeer stores the given key/value pair at the peer 'p'
func (dht *IpfsDHT) putValueToPeer(ctx context.Context, p peer.ID,
George Antoniadis's avatar
George Antoniadis committed
109
	key key.Key, rec *recpb.Record) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
124 125 126
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127

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

134 135
var errInvalidRecord = errors.New("received invalid record")

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

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

148 149 150
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

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 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
			log.Info("Received invalid record! (discarded)")
159 160
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
George Antoniadis's avatar
George Antoniadis committed
161
			record = new(recpb.Record)
162
		}
163
		return record, peers, err
164
	}
165

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 key.Key) (*pb.Message, error) {
Jeromy's avatar
Jeromy committed
178
	defer log.EventBegin(ctx, "getValueSingle", p, &key).Done()
179

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

193
// getLocal attempts to retrieve the value from the datastore
George Antoniadis's avatar
George Antoniadis committed
194
func (dht *IpfsDHT) getLocal(key key.Key) (*recpb.Record, error) {
195

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

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

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

219
	return rec, nil
220 221
}

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

233
// putLocal stores the key value pair in the datastore
George Antoniadis's avatar
George Antoniadis committed
234
func (dht *IpfsDHT) putLocal(key key.Key, rec *recpb.Record) error {
235 236 237 238 239 240
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

	return dht.datastore.Put(key.DsKey(), data)
241
}
242

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

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

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

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

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

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

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

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

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

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

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

Jeromy's avatar
Jeromy committed
323
		filtered = append(filtered, clp)
324 325
	}

326 327
	// ok seems like closer nodes
	return filtered
328 329
}

330 331 332 333 334 335 336 337 338 339 340 341 342 343
// 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()
}