dht.go 10 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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13
	host "github.com/jbenet/go-ipfs/p2p/host"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14
	peer "github.com/jbenet/go-ipfs/p2p/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15
	protocol "github.com/jbenet/go-ipfs/p2p/protocol"
16
	routing "github.com/jbenet/go-ipfs/routing"
17
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
Jeromy's avatar
Jeromy committed
18
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
19
	u "github.com/jbenet/go-ipfs/util"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
20
	"github.com/jbenet/go-ipfs/util/eventlog"
21

22
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
23
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
24 25
	ctxgroup "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-ctxgroup"
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
26 27
)

28
var log = eventlog.Logger("dht")
29

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

32
const doPinging = false
33

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.ThreadSafeDatastore // 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 56 57
	// record validator funcs
	Validators map[string]ValidatorFunc

58
	ctxgroup.ContextGroup
59 60
}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
71
	dht.providers = NewProviderManager(dht.Context(), dht.self)
72
	dht.AddChildGroup(dht.providers)
73

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

77
	dht.Validators = make(map[string]ValidatorFunc)
78
	dht.Validators["pk"] = ValidatePublicKeyRecord
79

80
	if doPinging {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
81
		dht.Children().Add(1)
82 83
		go dht.PingRoutine(time.Second * 10)
	}
Jeromy's avatar
Jeromy committed
84
	return dht
85 86
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87 88 89 90 91
// LocalPeer returns the peer.Peer of the dht.
func (dht *IpfsDHT) LocalPeer() peer.ID {
	return dht.self
}

92
// Connect to a new peer at the given address, ping and add to the routing table
93
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.ID) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
94 95
	// TODO: change interface to accept a PeerInfo as well.
	if err := dht.host.Connect(ctx, peer.PeerInfo{ID: npeer}); err != nil {
96
		return err
97 98
	}

Jeromy's avatar
Jeromy committed
99 100
	// Ping new peer to register in their routing table
	// NOTE: this should be done better...
101
	if err := dht.Ping(ctx, npeer); err != nil {
102
		return fmt.Errorf("failed to ping newly connected peer: %s\n", err)
Jeromy's avatar
Jeromy committed
103
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
104
	log.Event(ctx, "connect", dht.self, npeer)
105
	dht.Update(ctx, npeer)
106
	return nil
Jeromy's avatar
Jeromy committed
107 108
}

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

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

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

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

130
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
131 132

	// add self as the provider
133
	pi := dht.peerstore.PeerInfo(dht.self)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
	pmes.ProviderPeers = pb.PeerInfosToPBPeers(dht.host.Network(), []peer.PeerInfo{pi})
135

136
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137 138 139
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141
	log.Debugf("%s putProvider: %s for %s (%s)", dht.self, p, u.Key(key), pi.Addrs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142 143

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
144 145
}

146 147 148 149 150 151
// 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,
	key u.Key) ([]byte, []peer.PeerInfo, error) {
152

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

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

162 163
		// make sure record is valid.
		err = dht.verifyRecordOnline(ctx, record)
164
		if err != nil {
Jeromy's avatar
Jeromy committed
165
			log.Error("Received invalid record!")
166 167 168
			return nil, nil, err
		}
		return record.GetValue(), nil, nil
169
	}
170

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

178 179
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
180 181
}

182
// getValueSingle simply performs the get value RPC with the given parameters
183
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID,
184
	key u.Key) (*pb.Message, error) {
185

186
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
187
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
188 189
}

190
// getLocal attempts to retrieve the value from the datastore
191
func (dht *IpfsDHT) getLocal(key u.Key) ([]byte, error) {
192

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

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

	// TODO: 'if paranoid'
	if u.Debug {
212
		err = dht.verifyRecordLocally(rec)
213
		if err != nil {
Jeromy's avatar
Jeromy committed
214
			log.Errorf("local record verify failed: %s", err)
215 216 217 218 219
			return nil, err
		}
	}

	return rec.GetValue(), nil
220 221
}

222
// putLocal stores the key value pair in the datastore
223
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
224 225 226 227 228 229 230 231 232 233
	rec, err := dht.makePutRecord(key, value)
	if err != nil {
		return err
	}
	data, err := proto.Marshal(rec)
	if err != nil {
		return err
	}

	return dht.datastore.Put(key.DsKey(), data)
234
}
235

236
// Update signals the routingTable to Update its last-seen status
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
237
// on the given peer.
238
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
239
	log.Event(ctx, "updatePeer", p)
240
	dht.routingTable.Update(p)
241
}
Jeromy's avatar
Jeromy committed
242

Jeromy's avatar
Jeromy committed
243
// 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
244
func (dht *IpfsDHT) FindLocal(id peer.ID) peer.PeerInfo {
245
	p := dht.routingTable.Find(id)
246
	if p != "" {
Jeromy's avatar
Jeromy committed
247
		return dht.peerstore.PeerInfo(p)
Jeromy's avatar
Jeromy committed
248
	}
Jeromy's avatar
Jeromy committed
249
	return peer.PeerInfo{}
Jeromy's avatar
Jeromy committed
250
}
251

Jeromy's avatar
Jeromy committed
252
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
253
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
254
	pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
255
	return dht.sendRequest(ctx, p, pmes)
256
}
257

258
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.ID, key u.Key) (*pb.Message, error) {
259
	pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
260
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
261 262
}

263
// nearestPeersToQuery returns the routing tables closest peers.
264
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
265
	key := u.Key(pmes.GetKey())
266
	closer := dht.routingTable.NearestPeers(kb.ConvertKey(key), count)
267 268 269
	return closer
}

270
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
271
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
272
	closer := dht.nearestPeersToQuery(pmes, count)
273 274 275 276 277 278

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

279 280
	// == to self? thats bad
	for _, p := range closer {
281
		if p == dht.self {
282 283 284
			log.Error("Attempted to return self! this shouldnt happen...")
			return nil
		}
285 286
	}

287
	var filtered []peer.ID
288 289 290 291 292 293
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

294 295
		// must all be closer than self
		key := u.Key(pmes.GetKey())
296 297
		if !kb.Closer(dht.self, clp, key) {
			filtered = append(filtered, clp)
298
		}
299 300
	}

301 302
	// ok seems like closer nodes
	return filtered
303 304
}

305 306 307
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
308 309
	}

310
	// dial connection
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
311
	return dht.host.Connect(ctx, peer.PeerInfo{ID: p})
Jeromy's avatar
Jeromy committed
312
}
313

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
314
// PingRoutine periodically pings nearest neighbors.
315
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
316 317
	defer dht.Children().Done()

318 319 320 321 322 323
	tick := time.Tick(t)
	for {
		select {
		case <-tick:
			id := make([]byte, 16)
			rand.Read(id)
324
			peers := dht.routingTable.NearestPeers(kb.ConvertKey(u.Key(id)), 5)
325
			for _, p := range peers {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
326
				ctx, _ := context.WithTimeout(dht.Context(), time.Second*5)
327 328
				err := dht.Ping(ctx, p)
				if err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
329
					log.Errorf("Ping error: %s", err)
330 331
				}
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
332
		case <-dht.Closing():
333 334 335 336 337
			return
		}
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
338
// Bootstrap builds up list of peers by requesting random peer IDs
339
func (dht *IpfsDHT) Bootstrap(ctx context.Context, queries int) {
340

341
	// bootstrap sequentially, as results will compound
342
	for i := 0; i < NumBootstrapQueries; i++ {
343 344 345 346 347 348 349 350 351 352 353
		id := make([]byte, 16)
		rand.Read(id)
		pi, err := dht.FindPeer(ctx, peer.ID(id))
		if err == routing.ErrNotFound {
			// this isn't an error. this is precisely what we expect.
		} else if err != nil {
			log.Errorf("Bootstrap peer error: %s", err)
		} else {
			// woah, we got a peer under a random id? it _cannot_ be valid.
			log.Errorf("dht seemingly found a peer at a random bootstrap id (%s)...", pi)
		}
354
	}
355
}