dht.go 9.81 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
	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"
17
	ci "gx/ipfs/QmUEUu1CM8bxBJxc3ZLojAi8evhTr4byQogWstABet79oY/go-libp2p-crypto"
Jeromy's avatar
Jeromy committed
18 19
	host "gx/ipfs/QmUHrgorZ1F9yGkgF2His5fsQ9xtCzjdsPGjizmcEW94i5/go-libp2p/p2p/host"
	protocol "gx/ipfs/QmUHrgorZ1F9yGkgF2His5fsQ9xtCzjdsPGjizmcEW94i5/go-libp2p/p2p/protocol"
20
	peer "gx/ipfs/QmZpD74pUj6vuxTp1o6LhA3JavC2Bvh9fsWPPVvHnD9sE7/go-libp2p-peer"
21
	logging "gx/ipfs/QmaDNZ4QMdBdku1YZWBysufYyoQt1negQGNav6PLYarbY8/go-log"
22

Jeromy's avatar
Jeromy committed
23
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/ipfs/go-datastore"
24 25
	goprocess "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess"
	goprocessctx "gx/ipfs/QmQopLATEYMNg7dVqZRNDfeE2S1yKy8zrRh5xnYiuqeZBn/goprocess/context"
Jeromy's avatar
Jeromy committed
26
	proto "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/proto"
27
	context "gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"
28 29
)

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

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

34 35 36 37
// 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
38 39 40 41 42
// 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 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43
	host      host.Host      // the network services we need
44 45
	self      peer.ID        // Local peer (yourself)
	peerstore peer.Peerstore // Peer Registry
46

47
	datastore ds.Datastore // Local data
48

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

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

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

58 59
	ctx  context.Context
	proc goprocess.Process
60 61
}

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

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

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

79
	dht.ctx = ctx
80

81
	h.SetStreamHandler(ProtocolDHT, dht.handleNewStream)
82 83
	dht.providers = NewProviderManager(dht.ctx, dht.self)
	dht.proc.AddChild(dht.providers.proc)
rht's avatar
rht committed
84
	goprocessctx.CloseAfterContext(dht.proc, ctx)
85

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

89
	dht.Validator = make(record.Validator)
90
	dht.Validator["pk"] = record.PublicKeyValidator
91

92 93 94
	dht.Selector = make(record.Selector)
	dht.Selector["pk"] = record.PublicKeySelector

Jeromy's avatar
Jeromy committed
95
	return dht
96 97
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98 99 100 101 102
// LocalPeer returns the peer.Peer of the dht.
func (dht *IpfsDHT) LocalPeer() peer.ID {
	return dht.self
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103
// log returns the dht's logger
Jeromy's avatar
Jeromy committed
104
func (dht *IpfsDHT) log() logging.EventLogger {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
105
	return log // TODO rm
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106 107
}

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

112
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
113
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
115 116 117
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118

119
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
120 121 122
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123 124
}

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

129
	// add self as the provider
130 131 132 133 134
	pi := peer.PeerInfo{
		ID:    dht.self,
		Addrs: dht.host.Addrs(),
	}

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

142
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, skey, 0)
143
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]peer.PeerInfo{pi})
144
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145 146 147
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148

149
	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
150
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
151 152
}

153 154
var errInvalidRecord = errors.New("received invalid record")

155 156
// getValueOrPeers queries a particular peer p for the value for
// key. It returns either the value or a list of closer peers.
157
// NOTE: It will update the dht's peerstore with any new addresses
158 159
// it finds for the given peer.
func (dht *IpfsDHT) getValueOrPeers(ctx context.Context, p peer.ID,
160
	key key.Key) (*pb.Record, []peer.PeerInfo, error) {
161

162
	pmes, err := dht.getValueSingle(ctx, p, key)
163
	if err != nil {
164
		return nil, nil, err
165 166
	}

167 168 169
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

170
	if record := pmes.GetRecord(); record != nil {
171
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
172
		log.Debug("getValueOrPeers: got value")
173

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

185
	if len(peers) > 0 {
186
		log.Debug("getValueOrPeers: peers")
187 188 189
		return nil, peers, nil
	}

190 191
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
192 193
}

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

199
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
200
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
201 202
}

203
// getLocal attempts to retrieve the value from the datastore
204
func (dht *IpfsDHT) getLocal(key key.Key) (*pb.Record, error) {
205

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

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

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

229
	return rec, nil
230 231
}

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

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

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

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

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

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

273
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
274
	return dht.sendRequest(ctx, p, pmes)
275
}
276

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

280
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
281
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
282 283
}

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

291
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
292
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
293
	closer := dht.nearestPeersToQuery(pmes, count)
294 295 296 297 298 299

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

300 301
	// == to self? thats bad
	for _, p := range closer {
302
		if p == dht.self {
Jeromy's avatar
Jeromy committed
303
			log.Debug("Attempted to return self! this shouldnt happen...")
304 305
			return nil
		}
306 307
	}

308
	var filtered []peer.ID
309 310 311 312 313 314
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

Jeromy's avatar
Jeromy committed
315
		filtered = append(filtered, clp)
316 317
	}

318 319
	// ok seems like closer nodes
	return filtered
320 321
}

322 323 324 325 326 327 328 329 330 331 332 333 334 335
// 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()
}