dht.go 9.65 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
	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"
Jeromy's avatar
Jeromy committed
21
	logging "github.com/ipfs/go-ipfs/vendor/QmQg1J6vikuXF9oDvm4wpdeAUvvkVEKW1EYDw9HhTMnP2b/go-log"
22

23
	proto "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/gogo/protobuf/proto"
24
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
25 26
	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"
27
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/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 155 156 157
// 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,
158
	key key.Key) (*pb.Record, []peer.PeerInfo, error) {
159

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

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

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

172 173
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
174
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175
			log.Info("Received invalid record! (discarded)")
176 177 178
			// still return a non-nil record to signify that we received
			// a bad record from this peer
			record = new(pb.Record)
179
		}
180
		return record, peers, nil
181
	}
182

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

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

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

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

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

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

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

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

227
	return rec, nil
228 229
}

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

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

	return dht.datastore.Put(key.DsKey(), data)
249
}
250

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

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

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

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

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

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

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

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

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

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

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

Jeromy's avatar
Jeromy committed
313
		filtered = append(filtered, clp)
314 315
	}

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

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