dht.go 9.82 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
	inet "github.com/jbenet/go-ipfs/net"
14
	peer "github.com/jbenet/go-ipfs/peer"
15
	routing "github.com/jbenet/go-ipfs/routing"
16
	pb "github.com/jbenet/go-ipfs/routing/dht/pb"
Jeromy's avatar
Jeromy committed
17
	kb "github.com/jbenet/go-ipfs/routing/kbucket"
18
	u "github.com/jbenet/go-ipfs/util"
Brian Tiger Chow's avatar
Brian Tiger Chow committed
19
	"github.com/jbenet/go-ipfs/util/eventlog"
20

21
	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"
22
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
23 24
	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"
25 26
)

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

29
const doPinging = false
30

31 32 33 34
// 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
35 36 37 38 39
// 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 {
40
	network   inet.Network   // the network services we need
41 42
	self      peer.ID        // Local peer (yourself)
	peerstore peer.Peerstore // Peer Registry
43

44
	datastore ds.ThreadSafeDatastore // Local data
45

46 47
	routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
	providers    *ProviderManager
48

49 50
	birth    time.Time  // When this peer started up
	diaglock sync.Mutex // lock to make diagnostics work better
51

52 53 54
	// record validator funcs
	Validators map[string]ValidatorFunc

55
	ctxgroup.ContextGroup
56 57
}

Jeromy's avatar
Jeromy committed
58
// NewDHT creates a new DHT object with the given peer as the 'local' host
59
func NewDHT(ctx context.Context, p peer.ID, n inet.Network, dstore ds.ThreadSafeDatastore) *IpfsDHT {
60
	dht := new(IpfsDHT)
Jeromy's avatar
Jeromy committed
61
	dht.datastore = dstore
62
	dht.self = p
63
	dht.peerstore = n.Peerstore()
64 65 66
	dht.ContextGroup = ctxgroup.WithContext(ctx)
	dht.network = n
	n.SetHandler(inet.ProtocolDHT, dht.handleNewStream)
67

68
	dht.providers = NewProviderManager(dht.Context(), p)
69
	dht.AddChildGroup(dht.providers)
70

71
	dht.routingTable = kb.NewRoutingTable(20, kb.ConvertPeerID(p), time.Minute, dht.peerstore)
72
	dht.birth = time.Now()
73

74
	dht.Validators = make(map[string]ValidatorFunc)
75
	dht.Validators["pk"] = ValidatePublicKeyRecord
76

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

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

89
// Connect to a new peer at the given address, ping and add to the routing table
90
func (dht *IpfsDHT) Connect(ctx context.Context, npeer peer.ID) error {
91
	if err := dht.network.DialPeer(ctx, npeer); err != nil {
92
		return err
93 94
	}

Jeromy's avatar
Jeromy committed
95 96
	// Ping new peer to register in their routing table
	// NOTE: this should be done better...
97
	if err := dht.Ping(ctx, npeer); err != nil {
98
		return fmt.Errorf("failed to ping newly connected peer: %s\n", err)
Jeromy's avatar
Jeromy committed
99
	}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
100
	log.Event(ctx, "connect", dht.self, npeer)
101
	dht.Update(ctx, npeer)
102
	return nil
Jeromy's avatar
Jeromy 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 u.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, key string) error {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125

126
	pmes := pb.NewMessage(pb.Message_ADD_PROVIDER, string(key), 0)
127 128

	// add self as the provider
129 130
	pi := dht.peerstore.PeerInfo(dht.self)
	pmes.ProviderPeers = pb.PeerInfosToPBPeers(dht.network, []peer.PeerInfo{pi})
131

132
	err := dht.sendMessage(ctx, p, pmes)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133 134 135
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137
	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
138 139

	return nil
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140 141
}

142 143 144 145 146 147
// 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) {
148

149
	pmes, err := dht.getValueSingle(ctx, p, key)
150
	if err != nil {
151
		return nil, nil, err
152 153
	}

154
	if record := pmes.GetRecord(); record != nil {
155
		// Success! We were given the value
Jeromy's avatar
Jeromy committed
156
		log.Debug("getValueOrPeers: got value")
157

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

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

174 175
	log.Warning("getValueOrPeers: routing.ErrNotFound")
	return nil, nil, routing.ErrNotFound
176 177
}

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

182
	pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
183
	return dht.sendRequest(ctx, p, pmes)
Jeromy's avatar
Jeromy committed
184 185
}

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

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

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

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

	return rec.GetValue(), nil
216 217
}

218
// putLocal stores the key value pair in the datastore
219
func (dht *IpfsDHT) putLocal(key u.Key, value []byte) error {
220 221 222 223 224 225 226 227 228 229
	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)
230
}
231

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

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

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

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

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

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

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

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

283
	var filtered []peer.ID
284 285 286 287 288 289
	for _, clp := range closer {
		// Dont send a peer back themselves
		if p == clp {
			continue
		}

290 291
		// must all be closer than self
		key := u.Key(pmes.GetKey())
292 293
		if !kb.Closer(dht.self, clp, key) {
			filtered = append(filtered, clp)
294
		}
295 296
	}

297 298
	// ok seems like closer nodes
	return filtered
299 300
}

301 302 303
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
304 305
	}

306
	// dial connection
307
	return dht.network.DialPeer(ctx, p)
Jeromy's avatar
Jeromy committed
308
}
309

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
310
// PingRoutine periodically pings nearest neighbors.
311
func (dht *IpfsDHT) PingRoutine(t time.Duration) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
312 313
	defer dht.Children().Done()

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

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

337
	// bootstrap sequentially, as results will compound
338
	for i := 0; i < NumBootstrapQueries; i++ {
339 340 341 342 343 344 345 346 347 348 349
		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)
		}
350
	}
351
}