dht.go 9.8 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"
20 21
	goprocess "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess"
	goprocessctx "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess/context"
Jeromy's avatar
Jeromy committed
22
	ci "gx/ipfs/QmUEUu1CM8bxBJxc3ZLojAi8evhTr4byQogWstABet79oY/go-libp2p-crypto"
Jeromy's avatar
Jeromy committed
23 24
	host "gx/ipfs/QmXJBB9U6e6ennAJPzk8E2rSaVGuHVR2jCxE9H9gPDtRrq/go-libp2p/p2p/host"
	protocol "gx/ipfs/QmXJBB9U6e6ennAJPzk8E2rSaVGuHVR2jCxE9H9gPDtRrq/go-libp2p/p2p/protocol"
Jeromy's avatar
Jeromy committed
25
	proto "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/proto"
Jeromy's avatar
Jeromy committed
26
	pstore "gx/ipfs/QmZ62t46e9p7vMYqCmptwQC1RhRv5cpQ5cwoqYspedaXyq/go-libp2p-peerstore"
27
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
Jeromy's avatar
Jeromy committed
28
	logging "gx/ipfs/QmaDNZ4QMdBdku1YZWBysufYyoQt1negQGNav6PLYarbY8/go-log"
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
}

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

124
	// add self as the provider
Jeromy's avatar
Jeromy committed
125
	pi := pstore.PeerInfo{
126 127 128 129
		ID:    dht.self,
		Addrs: dht.host.Addrs(),
	}

130 131 132
	// // only share WAN-friendly addresses ??
	// pi.Addrs = addrutil.WANShareableAddrs(pi.Addrs)
	if len(pi.Addrs) < 1 {
133
		// log.Infof("%s putProvider: %s for %s error: no wan-friendly addresses", dht.self, p, key.Key(key), pi.Addrs)
134 135
		return fmt.Errorf("no known addresses for self. cannot put provider.")
	}
136

137
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, skey, 0)
Jeromy's avatar
Jeromy committed
138
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]pstore.PeerInfo{pi})
139
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140 141 142
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143

144
	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
145
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146 147
}

148 149
var errInvalidRecord = errors.New("received invalid record")

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

157
	pmes, err := dht.getValueSingle(ctx, p, key)
158
	if err != nil {
159
		return nil, nil, err
160 161
	}

162 163 164
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

165
	if record := pmes.GetRecord(); record != nil {
166
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
167
		log.Debug("getValueOrPeers: got value")
168

169 170
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
171
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172
			log.Info("Received invalid record! (discarded)")
173 174
			// return a sentinal to signify an invalid record was received
			err = errInvalidRecord
175
			record = new(pb.Record)
176
		}
177
		return record, peers, err
178
	}
179

180
	if len(peers) > 0 {
181
		log.Debug("getValueOrPeers: peers")
182 183 184
		return nil, peers, nil
	}

185 186
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
187 188
}

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

194
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
195
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
196 197
}

198
// getLocal attempts to retrieve the value from the datastore
199
func (dht *IpfsDHT) getLocal(key key.Key) (*pb.Record, error) {
200

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

	byt, ok := v.([]byte)
	if !ok {
210
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211
	}
212 213 214 215 216 217
	rec := new(pb.Record)
	err = proto.Unmarshal(byt, rec)
	if err != nil {
		return nil, err
	}

Jeromy's avatar
Jeromy committed
218 219 220 221
	err = dht.verifyRecordLocally(rec)
	if err != nil {
		log.Debugf("local record verify failed: %s (discarded)", err)
		return nil, err
222 223
	}

224
	return rec, nil
225 226
}

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

238
// putLocal stores the key value pair in the datastore
239
func (dht *IpfsDHT) putLocal(key key.Key, rec *pb.Record) error {
240 241 242 243 244 245
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

	return dht.datastore.Put(key.DsKey(), data)
246
}
247

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

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

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

268
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
269
	return dht.sendRequest(ctx, p, pmes)
270
}
271

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

275
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
276
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
277 278
}

279
// nearestPeersToQuery returns the routing tables closest peers.
280
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
281
	key := key.Key(pmes.GetKey())
282
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(key), count)
283 284 285
	return closer
}

286
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
287
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
288
	closer := dht.nearestPeersToQuery(pmes, count)
289 290 291 292 293 294

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

295 296
	// == to self? thats bad
	for _, p := range closer {
297
		if p == dht.self {
Jeromy's avatar
Jeromy committed
298
			log.Debug("Attempted to return self! this shouldnt happen...")
299 300
			return nil
		}
301 302
	}

303
	var filtered []peer.ID
304 305 306 307 308 309
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

Jeromy's avatar
Jeromy committed
310
		filtered = append(filtered, clp)
311 312
	}

313 314
	// ok seems like closer nodes
	return filtered
315 316
}

317 318 319 320 321 322 323 324 325 326 327 328 329 330
// 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()
}