dht.go 8.92 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 15 16 17
	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"

Jeromy's avatar
Jeromy committed
18
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore"
Jeromy's avatar
Jeromy committed
19
	peer "gx/ipfs/QmQGwpJy9P4yXZySmqkZEXCmbBpJUb8xntCv8Ca4taZwDC/go-libp2p-peer"
Jeromy's avatar
Jeromy committed
20 21
	host "gx/ipfs/QmQkQP7WmeT9FRJDsEzAaGYDparttDiB6mCpVBrq2MuWQS/go-libp2p/p2p/host"
	protocol "gx/ipfs/QmQkQP7WmeT9FRJDsEzAaGYDparttDiB6mCpVBrq2MuWQS/go-libp2p/p2p/protocol"
22 23
	goprocess "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess"
	goprocessctx "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess/context"
Jeromy's avatar
Jeromy committed
24
	ci "gx/ipfs/QmUEUu1CM8bxBJxc3ZLojAi8evhTr4byQogWstABet79oY/go-libp2p-crypto"
Jeromy's avatar
Jeromy committed
25
	pstore "gx/ipfs/QmXHUpFsnpCmanRnacqYkFoLoFfEq5yS2nUgGkAjJ1Nj9j/go-libp2p-peerstore"
Jakub Sztandera's avatar
Jakub Sztandera committed
26
	logging "gx/ipfs/QmYtB7Qge8cJpXc4irsEp8zRqfnZMBeB7aTrMEkPk67DRv/go-log"
Jeromy's avatar
Jeromy committed
27
	proto "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/proto"
28
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
29 30
)

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

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

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

48
	datastore ds.Datastore // Local data
49

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

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

56
	Validator record.Validator // record validator funcs
57
	Selector  record.Selector  // record selection funcs
58

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

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

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

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

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

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

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

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

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

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

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

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

107
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
108
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110 111 112
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
113

114
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115 116 117
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118 119
}

120 121
var errInvalidRecord = errors.New("received invalid record")

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

129
	pmes, err := dht.getValueSingle(ctx, p, key)
130
	if err != nil {
131
		return nil, nil, err
132 133
	}

134 135 136
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

137
	if record := pmes.GetRecord(); record != nil {
138
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
139
		log.Debug("getValueOrPeers: got value")
140

141 142
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
143
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144
			log.Info("Received invalid record! (discarded)")
145 146
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
147
			record = new(pb.Record)
148
		}
149
		return record, peers, err
150
	}
151

152
	if len(peers) > 0 {
153
		log.Debug("getValueOrPeers: peers")
154 155 156
		return nil, peers, nil
	}

157 158
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
159 160
}

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

166
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
167
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
168 169
}

170
// getLocal attempts to retrieve the value from the datastore
171
func (dht *IpfsDHT) getLocal(key key.Key) (*pb.Record, error) {
172

Jeromy's avatar
Jeromy committed
173
	log.Debug("getLocal %s", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
174
	v, err := dht.datastore.Get(key.DsKey())
175 176 177
	if err != nil {
		return nil, err
	}
Jeromy's avatar
Jeromy committed
178
	log.Debug("found in db")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179 180 181

	byt, ok := v.([]byte)
	if !ok {
182
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183
	}
184 185 186 187 188 189
	rec := new(pb.Record)
	err = proto.Unmarshal(byt, rec)
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
190 191 192 193
	err = dht.verifyRecordLocally(rec)
	if err != nil {
		log.Debugf("local record verify failed: %s (discarded)", err)
		return nil, err
194 195
	}

196
	return rec, nil
197 198
}

Jeromy's avatar
Jeromy committed
199 200
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
Jeromy's avatar
Jeromy committed
201 202 203
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
204
		log.Warningf("%s dht cannot get own private key!", dht.self)
Jeromy's avatar
Jeromy committed
205 206 207 208 209
		return nil, fmt.Errorf("cannot get private key to sign record!")
	}
	return sk, nil
}

210
// putLocal stores the key value pair in the datastore
211
func (dht *IpfsDHT) putLocal(key key.Key, rec *pb.Record) error {
212 213 214 215 216 217
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

	return dht.datastore.Put(key.DsKey(), data)
218
}
219

220
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221
// on the given peer.
222
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
223
	log.Event(ctx, "updatePeer", p)
224
	dht.routingTable.Update(p)
225
}
Jeromy's avatar
Jeromy committed
226

Jeromy's avatar
Jeromy committed
227
// 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
228
func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
229
	p := dht.routingTable.Find(id)
230
	if p != "" {
Jeromy's avatar
Jeromy committed
231
		return dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
232
	}
Jeromy's avatar
Jeromy committed
233
	return pstore.PeerInfo{}
Jeromy's avatar
Jeromy committed
234
}
235

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

240
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
241
	return dht.sendRequest(ctx, p, pmes)
242
}
243

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

247
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
248
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
249 250
}

251
// nearestPeersToQuery returns the routing tables closest peers.
252
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
253
	key := key.Key(pmes.GetKey())
254
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(key), count)
255 256 257
	return closer
}

258
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
259
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
260
	closer := dht.nearestPeersToQuery(pmes, count)
261 262 263 264 265 266

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

267 268
	// == to self? thats bad
	for _, p := range closer {
269
		if p == dht.self {
Jeromy's avatar
Jeromy committed
270
			log.Debug("Attempted to return self! this shouldnt happen...")
271 272
			return nil
		}
273 274
	}

275
	var filtered []peer.ID
276 277 278 279 280 281
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

Jeromy's avatar
Jeromy committed
282
		filtered = append(filtered, clp)
283 284
	}

285 286
	// ok seems like closer nodes
	return filtered
287 288
}

289 290 291 292 293 294 295 296 297 298 299 300 301 302
// 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()
}