dht.go 9.59 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 18 19 20 21
	ci "github.com/ipfs/go-ipfs/p2p/crypto"
	host "github.com/ipfs/go-ipfs/p2p/host"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	protocol "github.com/ipfs/go-ipfs/p2p/protocol"
	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"
	u "github.com/ipfs/go-ipfs/util"
Jeromy's avatar
Jeromy committed
22
	logging "github.com/ipfs/go-ipfs/vendor/go-log-v1.0.0"
23

24
	proto "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/gogo/protobuf/proto"
25
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
26 27
	goprocess "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
	goprocessctx "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess/context"
28
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/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 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44
	host      host.Host      // the network services we need
45 46
	self      peer.ID        // Local peer (yourself)
	peerstore peer.Peerstore // Peer Registry
47

48
	datastore ds.ThreadSafeDatastore // 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

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
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
63
func NewDHT(ctx context.Context, h host.Host, dstore ds.ThreadSafeDatastore) *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

Jeromy's avatar
Jeromy committed
92
	return dht
93 94
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95 96 97 98 99
// 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
100
// log returns the dht's logger
Jeromy's avatar
Jeromy committed
101
func (dht *IpfsDHT) log() logging.EventLogger {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
102
	return log // TODO rm
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
103 104
}

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

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

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

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

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

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

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

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

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

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

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

166 167
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
168
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169
			log.Info("Received invalid record! (discarded)")
170 171 172
			return nil, nil, err
		}
		return record.GetValue(), nil, nil
173
	}
174

175
	// Perhaps we were given closer peers
176
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())
177
	if len(peers) > 0 {
178
		log.Debug("getValueOrPeers: peers")
179 180 181
		return nil, peers, nil
	}

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

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

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

195
// getLocal attempts to retrieve the value from the datastore
196
func (dht *IpfsDHT) getLocal(key key.Key) ([]byte, error) {
197

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

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

	// TODO: 'if paranoid'
	if u.Debug {
217
		err = dht.verifyRecordLocally(rec)
218
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219
			log.Debugf("local record verify failed: %s (discarded)", err)
220 221 222 223 224
			return nil, err
		}
	}

	return rec.GetValue(), 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) peer.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 peer.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
		}

310
		// must all be closer than self
311
		key := key.Key(pmes.GetKey())
312 313
		if !kb.Closer(dht.self, clp, key) {
			filtered = append(filtered, clp)
314
		}
315 316
	}

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

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