dht.go 9.7 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
}

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

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

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

80
	dht.ctx = ctx
81

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

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

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

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

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

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

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

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

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

120
	// add self as the provider
Jeromy's avatar
Jeromy committed
121
	pi := pstore.PeerInfo{
122 123 124 125
		ID:    dht.self,
		Addrs: dht.host.Addrs(),
	}

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

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

140
	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
141
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142 143
}

144 145
var errInvalidRecord = errors.New("received invalid record")

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

153
	pmes, err := dht.getValueSingle(ctx, p, key)
154
	if err != nil {
155
		return nil, nil, err
156 157
	}

158 159 160
	// Perhaps we were given closer peers
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())

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

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

176
	if len(peers) > 0 {
177
		log.Debug("getValueOrPeers: peers")
178 179 180
		return nil, peers, nil
	}

181 182
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
183 184
}

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

190
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
191
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
192 193
}

194
// getLocal attempts to retrieve the value from the datastore
195
func (dht *IpfsDHT) getLocal(key key.Key) (*pb.Record, error) {
196

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

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

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

220
	return rec, nil
221 222
}

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

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

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

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

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

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

264
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
265
	return dht.sendRequest(ctx, p, pmes)
266
}
267

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

271
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
272
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
273 274
}

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

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

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

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

299
	var filtered []peer.ID
300 301 302 303 304 305
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

Jeromy's avatar
Jeromy committed
306
		filtered = append(filtered, clp)
307 308
	}

309 310
	// ok seems like closer nodes
	return filtered
311 312
}

313 314 315 316 317 318 319 320 321 322 323 324 325 326
// 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()
}