dht.go 10.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
	"crypto/rand"
8
	"errors"
9
	"fmt"
10 11
	"sync"
	"time"
12

13
	key "github.com/ipfs/go-ipfs/blocks/key"
14 15 16 17 18 19 20 21 22 23 24
	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"
	"github.com/ipfs/go-ipfs/thirdparty/eventlog"
	u "github.com/ipfs/go-ipfs/util"

25
	proto "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/gogo/protobuf/proto"
26
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
27 28
	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"
29
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
30 31
)

32
var log = eventlog.Logger("dht")
33

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

36
const doPinging = false
37

38 39 40 41
// 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
42 43 44 45 46
// 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
47
	host      host.Host      // the network services we need
48 49
	self      peer.ID        // Local peer (yourself)
	peerstore peer.Peerstore // Peer Registry
50

51
	datastore ds.ThreadSafeDatastore // Local data
52

53 54
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
	providers    *ProviderManager
55

56 57
	birth    time.Time  // When this peer started up
	diaglock sync.Mutex // lock to make diagnostics work better
58

59
	Validator record.Validator // record validator funcs
60

61 62
	Context context.Context
	goprocess.Process
63 64
}

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

73 74 75
	// register for network notifs.
	dht.host.Network().Notify((*netNotifiee)(dht))

76 77
	procctx = goprocessctx.WithContext(ctx)
	procctx.SetTeardown(func() error {
78 79 80 81
		// remove ourselves from network notifs.
		dht.host.Network().StopNotify((*netNotifiee)(dht))
		return nil
	})
82 83
	dht.Process = procctx
	dht.Context = ctx
84

85
	h.SetStreamHandler(ProtocolDHT, dht.handleNewStream)
86
	dht.providers = NewProviderManager(dht.Context, dht.self)
87
	dht.AddChild(dht.providers)
88

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

92
	dht.Validator = make(record.Validator)
93
	dht.Validator["pk"] = record.PublicKeyValidator
94

95
	if doPinging {
96
		dht.Go(func() { dht.PingRoutine(time.Second * 10) })
97
	}
Jeromy's avatar
Jeromy committed
98
	return dht
99 100
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101 102 103 104 105
// 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
106 107
// log returns the dht's logger
func (dht *IpfsDHT) log() eventlog.EventLogger {
Brian Tiger Chow's avatar
Brian Tiger Chow committed
108
	return log // TODO rm
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109 110
}

111
// Connect to a new peer at the given address, ping and add to the routing table
112
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.ID) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
113 114
	// TODO: change interface to accept a PeerInfo as well.
	if err := dht.host.Connect(ctx, peer.PeerInfo{ID: npeer}); err != nil {
115
		return err
116 117
	}

Jeromy's avatar
Jeromy committed
118 119
	// Ping new peer to register in their routing table
	// NOTE: this should be done better...
120 121
	if _, err := dht.Ping(ctx, npeer); err != nil {
		return fmt.Errorf("failed to ping newly connected peer: %s", err)
Jeromy's avatar
Jeromy committed
122
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
123
	log.Event(ctx, "connect", dht.self, npeer)
124
	dht.Update(ctx, npeer)
125
	return nil
Jeromy's avatar
Jeromy committed
126 127
}

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

132
	pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
133
	pmes.Record = rec
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
	rpmes, err := dht.sendRequest(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
135 136 137
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138

139
	if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140 141 142
		return errors.New("value not put correctly")
	}
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143 144
}

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

149
	// add self as the provider
150 151 152 153 154
	pi := peer.PeerInfo{
		ID:    dht.self,
		Addrs: dht.host.Addrs(),
	}

155 156 157
	// // only share WAN-friendly addresses ??
	// pi.Addrs = addrutil.WANShareableAddrs(pi.Addrs)
	if len(pi.Addrs) < 1 {
158
		// log.Infof("%s putProvider: %s for %s error: no wan-friendly addresses", dht.self, p, key.Key(key), pi.Addrs)
159 160
		return fmt.Errorf("no known addresses for self. cannot put provider.")
	}
161

162
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, skey, 0)
163
	pmes.ProviderPeers = pb.RawPeerInfosToPBPeers([]peer.PeerInfo{pi})
164
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
165 166 167
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168

169
	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
170
	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171 172
}

173 174 175 176 177
// 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,
178
	key key.Key) ([]byte, []peer.PeerInfo, error) {
179

180
	pmes, err := dht.getValueSingle(ctx, p, key)
181
	if err != nil {
182
		return nil, nil, err
183 184
	}

185
	if record := pmes.GetRecord(); record != nil {
186
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
187
		log.Debug("getValueOrPeers: got value")
188

189 190
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
191
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192
			log.Info("Received invalid record! (discarded)")
193 194 195
			return nil, nil, err
		}
		return record.GetValue(), nil, nil
196
	}
197

198
	// Perhaps we were given closer peers
199
	peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())
200
	if len(peers) > 0 {
201
		log.Debug("getValueOrPeers: peers")
202 203 204
		return nil, peers, nil
	}

205 206
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
207 208
}

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

214
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
215
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
216 217
}

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

Jeromy's avatar
Jeromy committed
221
	log.Debug("getLocal %s", key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
222
	v, err := dht.datastore.Get(key.DsKey())
223 224 225
	if err != nil {
		return nil, err
	}
Jeromy's avatar
Jeromy committed
226
	log.Debug("found in db")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
227 228 229

	byt, ok := v.([]byte)
	if !ok {
230
		return nil, errors.New("value stored in datastore not []byte")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
	}
232 233 234 235 236 237 238 239
	rec := new(pb.Record)
	err = proto.Unmarshal(byt, rec)
	if err != nil {
		return nil, err
	}

	// TODO: 'if paranoid'
	if u.Debug {
240
		err = dht.verifyRecordLocally(rec)
241
		if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
242
			log.Debugf("local record verify failed: %s (discarded)", err)
243 244 245 246 247
			return nil, err
		}
	}

	return rec.GetValue(), nil
248 249
}

Jeromy's avatar
Jeromy committed
250 251
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
Jeromy's avatar
Jeromy committed
252 253 254
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
255
		log.Warningf("%s dht cannot get own private key!", dht.self)
Jeromy's avatar
Jeromy committed
256 257 258 259 260
		return nil, fmt.Errorf("cannot get private key to sign record!")
	}
	return sk, nil
}

261
// putLocal stores the key value pair in the datastore
262
func (dht *IpfsDHT) putLocal(key key.Key, rec *pb.Record) error {
263 264 265 266 267 268
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

	return dht.datastore.Put(key.DsKey(), data)
269
}
270

271
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
272
// on the given peer.
273
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
274
	log.Event(ctx, "updatePeer", p)
275
	dht.routingTable.Update(p)
276
}
Jeromy's avatar
Jeromy committed
277

Jeromy's avatar
Jeromy committed
278
// 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
279
func (dht *IpfsDHT) FindLocal(id peer.ID) peer.PeerInfo {
280
	p := dht.routingTable.Find(id)
281
	if p != "" {
Jeromy's avatar
Jeromy committed
282
		return dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
283
	}
Jeromy's avatar
Jeromy committed
284
	return peer.PeerInfo{}
Jeromy's avatar
Jeromy committed
285
}
286

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

291
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
292
	return dht.sendRequest(ctx, p, pmes)
293
}
294

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

298
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
299
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
300 301
}

302
// nearestPeersToQuery returns the routing tables closest peers.
303
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
304
	key := key.Key(pmes.GetKey())
305
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(key), count)
306 307 308
	return closer
}

309
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
310
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
311
	closer := dht.nearestPeersToQuery(pmes, count)
312 313 314 315 316 317

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

318 319
	// == to self? thats bad
	for _, p := range closer {
320
		if p == dht.self {
Jeromy's avatar
Jeromy committed
321
			log.Debug("Attempted to return self! this shouldnt happen...")
322 323
			return nil
		}
324 325
	}

326
	var filtered []peer.ID
327 328 329 330 331 332
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

333
		// must all be closer than self
334
		key := key.Key(pmes.GetKey())
335 336
		if !kb.Closer(dht.self, clp, key) {
			filtered = append(filtered, clp)
337
		}
338 339
	}

340 341
	// ok seems like closer nodes
	return filtered
342 343
}

344 345 346
func (dht *IpfsDHT) ensureConnectedToPeer(ctx context.Context, p peer.ID) error {
	if p == dht.self {
		return errors.New("attempting to ensure connection to self")
Jeromy's avatar
Jeromy committed
347 348
	}

349
	// dial connection
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
350
	return dht.host.Connect(ctx, peer.PeerInfo{ID: p})
Jeromy's avatar
Jeromy committed
351
}
352

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
353
// PingRoutine periodically pings nearest neighbors.
354 355 356 357 358 359 360
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
	tick := time.Tick(t)
	for {
		select {
		case <-tick:
			id := make([]byte, 16)
			rand.Read(id)
361
			peers := dht.routingTable.NearestPeers(kb.ConvertKey(key.Key(id)), 5)
362
			for _, p := range peers {
363
				ctx, cancel := context.WithTimeout(dht.Context, time.Second*5)
364
				_, err := dht.Ping(ctx, p)
365
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
366
					log.Debugf("Ping error: %s", err)
367
				}
368
				cancel()
369
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
370
		case <-dht.Closing():
371 372 373 374
			return
		}
	}
}