dht.go 9.69 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"
Jeromy's avatar
Jeromy committed
7
	"context"
8
	"errors"
9
	"fmt"
10 11
	"sync"
	"time"
12

13 14 15 16
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
	providers "github.com/libp2p/go-libp2p-kad-dht/providers"
	routing "github.com/libp2p/go-libp2p-routing"

17
	proto "github.com/gogo/protobuf/proto"
18
	cid "github.com/ipfs/go-cid"
19 20 21 22
	ds "github.com/ipfs/go-datastore"
	logging "github.com/ipfs/go-log"
	goprocess "github.com/jbenet/goprocess"
	goprocessctx "github.com/jbenet/goprocess/context"
23 24
	ci "github.com/libp2p/go-libp2p-crypto"
	host "github.com/libp2p/go-libp2p-host"
George Antoniadis's avatar
George Antoniadis committed
25
	kb "github.com/libp2p/go-libp2p-kbucket"
26 27 28
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
	protocol "github.com/libp2p/go-libp2p-protocol"
George Antoniadis's avatar
George Antoniadis committed
29
	record "github.com/libp2p/go-libp2p-record"
George Antoniadis's avatar
George Antoniadis committed
30
	recpb "github.com/libp2p/go-libp2p-record/pb"
31
	base32 "github.com/whyrusleeping/base32"
32 33
)

Jeromy's avatar
Jeromy committed
34
var log = logging.Logger("dht")
35

Jeromy's avatar
Jeromy committed
36 37
var ProtocolDHT protocol.ID = "/ipfs/kad/1.0.0"
var ProtocolDHTOld protocol.ID = "/ipfs/dht"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
38

39 40 41 42
// 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
43 44 45
// 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

Jeromy's avatar
Jeromy committed
55
	birth time.Time // When this peer started up
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.Batching) *IpfsDHT {
Justin Drake's avatar
Justin Drake committed
69
	dht := NewDHTClient(ctx, h, dstore)
70

71
	h.SetStreamHandler(ProtocolDHT, dht.handleNewStream)
Jeromy's avatar
Jeromy committed
72
	h.SetStreamHandler(ProtocolDHTOld, dht.handleNewStream)
Jeromy's avatar
Jeromy committed
73

Jeromy's avatar
Jeromy committed
74
	return dht
75 76
}

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
// NewDHTClient creates a new DHT object with the given peer as the 'local' host
func NewDHTClient(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
	dht := makeDHT(ctx, h, dstore)

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

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

	dht.proc.AddChild(dht.providers.Process())

	dht.Validator["pk"] = record.PublicKeyValidator
	dht.Selector["pk"] = record.PublicKeySelector

	return dht
}

Jeromy's avatar
Jeromy committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
func makeDHT(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
	return &IpfsDHT{
		datastore:    dstore,
		self:         h.ID(),
		peerstore:    h.Peerstore(),
		host:         h,
		strmap:       make(map[peer.ID]*messageSender),
		ctx:          ctx,
		providers:    providers.NewProviderManager(ctx, h.ID(), dstore),
		birth:        time.Now(),
		routingTable: kb.NewRoutingTable(KValue, kb.ConvertPeerID(h.ID()), time.Minute, h.Peerstore()),

		Validator: make(record.Validator),
		Selector:  make(record.Selector),
	}
}

Jeromy's avatar
Jeromy committed
115 116
// putValueToPeer stores the given key/value pair at the peer 'p'
func (dht *IpfsDHT) putValueToPeer(ctx context.Context, p peer.ID,
117
	key string, rec *recpb.Record) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118

119
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, key, 0)
120
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121
	rpmes, err := dht.sendRequest(ctx, p, pmes)
122 123
	switch err {
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
124
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
125 126 127 128 129 130 131
		fallthrough
	default:
		return err
	case nil:
		break
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
132 133 134
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135

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

142 143
var errInvalidRecord = errors.New("received invalid record")

144 145
// getValueOrPeers queries a particular peer p for the value for
// key. It returns either the value or a list of closer peers.
146
// NOTE: It will update the dht's peerstore with any new addresses
147
// it finds for the given peer.
148
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.ID, key string) (*recpb.Record, []pstore.PeerInfo, error) {
149

150
	pmes, err := dht.getValueSingle(ctx, p, key)
151
	if err != nil {
152
		return nil, nil, err
153 154
	}

155 156 157
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

158
	if record := pmes.GetRecord(); record != nil {
159
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
160
		log.Debug("getValueOrPeers: got value")
161

162 163
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
164
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165
			log.Info("Received invalid record! (discarded)")
166 167
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
George Antoniadis's avatar
George Antoniadis committed
168
			record = new(recpb.Record)
169
		}
170
		return record, peers, err
171
	}
172

173
	if len(peers) > 0 {
174
		log.Debug("getValueOrPeers: peers")
175 176 177
		return nil, peers, nil
	}

178 179
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
180 181
}

182
// getValueSingle simply performs the get value RPC with the given parameters
183 184 185 186 187 188 189
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID, key string) (*pb.Message, error) {
	meta := logging.LoggableMap{
		"key":  key,
		"peer": p,
	}

	defer log.EventBegin(ctx, "getValueSingle", meta).Done()
190

191
	pmes := pb.NewMessage(pb.Message_GET_VALUE, key, 0)
192 193 194 195 196
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
197
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
198 199 200 201
		fallthrough
	default:
		return nil, err
	}
Jeromy's avatar
Jeromy committed
202 203
}

204
// getLocal attempts to retrieve the value from the datastore
205 206
func (dht *IpfsDHT) getLocal(key string) (*recpb.Record, error) {
	log.Debugf("getLocal %s", key)
207

208
	v, err := dht.datastore.Get(mkDsKey(key))
209 210 211
	if err != nil {
		return nil, err
	}
212
	log.Debugf("found %s in local datastore")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213 214 215

	byt, ok := v.([]byte)
	if !ok {
216
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
217
	}
George Antoniadis's avatar
George Antoniadis committed
218
	rec := new(recpb.Record)
219 220 221 222 223
	err = proto.Unmarshal(byt, rec)
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
224 225 226 227
	err = dht.verifyRecordLocally(rec)
	if err != nil {
		log.Debugf("local record verify failed: %s (discarded)", err)
		return nil, err
228 229
	}

230
	return rec, nil
231 232
}

Jeromy's avatar
Jeromy committed
233 234
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
Jeromy's avatar
Jeromy committed
235 236 237
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
238
		log.Warningf("%s dht cannot get own private key!", dht.self)
Jeromy's avatar
Jeromy committed
239 240 241 242 243
		return nil, fmt.Errorf("cannot get private key to sign record!")
	}
	return sk, nil
}

244
// putLocal stores the key value pair in the datastore
245
func (dht *IpfsDHT) putLocal(key string, rec *recpb.Record) error {
246 247 248 249 250
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

251
	return dht.datastore.Put(mkDsKey(key), data)
252
}
253

254
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
255
// on the given peer.
256
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
257
	log.Event(ctx, "updatePeer", p)
258
	dht.routingTable.Update(p)
259
}
Jeromy's avatar
Jeromy committed
260

Jeromy's avatar
Jeromy committed
261
// 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
262
func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
263
	p := dht.routingTable.Find(id)
264
	if p != "" {
Jeromy's avatar
Jeromy committed
265
		return dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
266
	}
Jeromy's avatar
Jeromy committed
267
	return pstore.PeerInfo{}
Jeromy's avatar
Jeromy committed
268
}
269

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

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

287 288
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.ID, key *cid.Cid) (*pb.Message, error) {
	defer log.EventBegin(ctx, "findProvidersSingle", p, key).Done()
289

290
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, key.KeyString(), 0)
291 292 293 294 295
	resp, err := dht.sendRequest(ctx, p, pmes)
	switch err {
	case nil:
		return resp, nil
	case ErrReadTimeout:
Jeromy's avatar
Jeromy committed
296
		log.Warningf("read timeout: %s %s", p.Pretty(), key)
297 298 299 300
		fallthrough
	default:
		return nil, err
	}
Jeromy's avatar
Jeromy committed
301 302
}

303
// nearestPeersToQuery returns the routing tables closest peers.
304
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
305
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(pmes.GetKey()), count)
306 307 308
	return closer
}

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

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

318 319
	// == to self? thats bad
	for _, p := range closer {
320
		if p == dht.self {
321
			log.Debug("attempted to return self! this shouldn't happen...")
322 323
			return nil
		}
324 325
	}

326
	var filtered []peer.ID
327 328 329 330 331 332
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

Jeromy's avatar
Jeromy committed
333
		filtered = append(filtered, clp)
334 335
	}

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

340 341 342 343 344 345 346 347 348 349 350 351 352 353
// 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()
}
354 355 356 357

func mkDsKey(s string) ds.Key {
	return ds.NewKey(base32.RawStdEncoding.EncodeToString([]byte(s)))
}