346 lines
9.5 KiB
Go
Raw Normal View History

2014-11-20 10:46:19 -08:00
// Package dht implements a distributed hash table that satisfies the ipfs routing
// interface. This DHT is modeled after kademlia with Coral and S/Kademlia modifications.
2014-07-23 04:48:30 -07:00
package dht
import (
2014-09-19 08:07:56 -07:00
"bytes"
2014-09-16 00:56:40 -07:00
"errors"
"fmt"
"sync"
"time"
proto "github.com/gogo/protobuf/proto"
ds "github.com/ipfs/go-datastore"
2016-09-02 20:21:23 +01:00
key "github.com/ipfs/go-key"
ci "github.com/ipfs/go-libp2p-crypto"
peer "github.com/ipfs/go-libp2p-peer"
pstore "github.com/ipfs/go-libp2p-peerstore"
logging "github.com/ipfs/go-log"
goprocess "github.com/jbenet/goprocess"
goprocessctx "github.com/jbenet/goprocess/context"
2016-09-02 20:21:23 +01:00
pb "github.com/libp2p/go-libp2p-kad-dht/pb"
providers "github.com/libp2p/go-libp2p-kad-dht/providers"
kb "github.com/libp2p/go-libp2p-kbucket"
record "github.com/libp2p/go-libp2p-record"
2016-09-03 20:35:59 +01:00
recpb "github.com/libp2p/go-libp2p-record/pb"
2016-09-02 20:21:23 +01:00
routing "github.com/libp2p/go-libp2p-routing"
host "github.com/libp2p/go-libp2p/p2p/host"
protocol "github.com/libp2p/go-libp2p/p2p/protocol"
context "golang.org/x/net/context"
)
var log = logging.Logger("dht")
2016-09-23 02:45:58 -07:00
var ProtocolDHT protocol.ID = "/ipfs/kad/1.0.0"
var ProtocolDHTOld protocol.ID = "/ipfs/dht"
2015-01-01 12:45:39 -08:00
2014-12-23 22:04:21 -08:00
// NumBootstrapQueries defines the number of random dht queries to do to
// collect members of the routing table.
const NumBootstrapQueries = 5
2014-07-23 04:48:30 -07:00
// 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 {
host host.Host // the network services we need
self peer.ID // Local peer (yourself)
peerstore pstore.Peerstore // Peer Registry
datastore ds.Datastore // Local data
2014-12-16 08:55:46 -08:00
routingTable *kb.RoutingTable // Array of routing tables for differently distanced nodes
providers *providers.ProviderManager
2014-12-16 08:55:46 -08:00
birth time.Time // When this peer started up
diaglock sync.Mutex // lock to make diagnostics work better
Validator record.Validator // record validator funcs
Selector record.Selector // record selection funcs
ctx context.Context
proc goprocess.Process
strmap map[peer.ID]*messageSender
smlk sync.Mutex
}
2014-08-09 22:28:46 -07:00
// NewDHT creates a new DHT object with the given peer as the 'local' host
func NewDHT(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
2016-09-23 04:38:05 -07:00
dht := makeDHT(ctx, h, dstore)
2014-09-16 00:56:40 -07:00
// register for network notifs.
dht.host.Network().Notify((*netNotifiee)(dht))
2016-09-23 04:38:05 -07:00
dht.proc = goprocessctx.WithContextAndTeardown(ctx, func() error {
// remove ourselves from network notifs.
dht.host.Network().StopNotify((*netNotifiee)(dht))
return nil
})
2016-09-23 04:38:05 -07:00
dht.proc.AddChild(dht.providers.Process())
h.SetStreamHandler(ProtocolDHT, dht.handleNewStream)
2016-09-23 02:45:58 -07:00
h.SetStreamHandler(ProtocolDHTOld, dht.handleNewStream)
dht.Validator["pk"] = record.PublicKeyValidator
dht.Selector["pk"] = record.PublicKeySelector
2014-08-10 21:40:17 -07:00
return dht
}
2016-09-23 04:38:05 -07:00
func makeDHT(ctx context.Context, h host.Host, dstore ds.Batching) *IpfsDHT {
return &IpfsDHT{
datastore: dstore,
self: h.ID(),
peerstore: h.Peerstore(),
host: h,
strmap: make(map[peer.ID]*messageSender),
ctx: ctx,
providers: providers.NewProviderManager(ctx, h.ID(), dstore),
birth: time.Now(),
routingTable: kb.NewRoutingTable(KValue, kb.ConvertPeerID(h.ID()), time.Minute, h.Peerstore()),
Validator: make(record.Validator),
Selector: make(record.Selector),
}
}
2014-12-28 23:46:25 +00:00
// putValueToPeer stores the given key/value pair at the peer 'p'
func (dht *IpfsDHT) putValueToPeer(ctx context.Context, p peer.ID,
2016-09-03 20:35:59 +01:00
key key.Key, rec *recpb.Record) error {
2014-09-19 08:07:56 -07:00
pmes := pb.NewMessage(pb.Message_PUT_VALUE, string(key), 0)
pmes.Record = rec
2014-09-19 08:07:56 -07:00
rpmes, err := dht.sendRequest(ctx, p, pmes)
switch err {
case ErrReadTimeout:
log.Warningf("read timeout: %s %s", p.Pretty(), key)
fallthrough
default:
return err
case nil:
break
}
2014-09-17 07:19:40 -07:00
if err != nil {
return err
}
2014-09-19 08:07:56 -07:00
if !bytes.Equal(rpmes.GetRecord().Value, pmes.GetRecord().Value) {
2014-09-19 08:07:56 -07:00
return errors.New("value not put correctly")
}
return nil
2014-09-17 07:19:40 -07:00
}
var errInvalidRecord = errors.New("received invalid record")
// 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,
2016-09-03 20:35:59 +01:00
key key.Key) (*recpb.Record, []pstore.PeerInfo, error) {
2014-09-16 02:43:11 -07:00
pmes, err := dht.getValueSingle(ctx, p, key)
if err != nil {
return nil, nil, err
}
// Perhaps we were given closer peers
peers := pb.PBPeersToPeerInfos(pmes.GetCloserPeers())
if record := pmes.GetRecord(); record != nil {
// Success! We were given the value
2014-09-28 00:13:07 -07:00
log.Debug("getValueOrPeers: got value")
// make sure record is valid.
err = dht.verifyRecordOnline(ctx, record)
if err != nil {
2015-01-26 19:12:12 -08:00
log.Info("Received invalid record! (discarded)")
// return a sentinal to signify an invalid record was received
err = errInvalidRecord
2016-09-03 20:35:59 +01:00
record = new(recpb.Record)
}
return record, peers, err
2014-08-16 23:03:36 -07:00
}
if len(peers) > 0 {
log.Debug("getValueOrPeers: peers")
return nil, peers, nil
}
log.Warning("getValueOrPeers: routing.ErrNotFound")
return nil, nil, routing.ErrNotFound
}
// getValueSingle simply performs the get value RPC with the given parameters
func (dht *IpfsDHT) getValueSingle(ctx context.Context, p peer.ID,
key key.Key) (*pb.Message, error) {
2015-01-15 04:45:34 +00:00
defer log.EventBegin(ctx, "getValueSingle", p, &key).Done()
2014-09-16 02:43:11 -07:00
pmes := pb.NewMessage(pb.Message_GET_VALUE, string(key), 0)
resp, err := dht.sendRequest(ctx, p, pmes)
switch err {
case nil:
return resp, nil
case ErrReadTimeout:
log.Warningf("read timeout: %s %s", p.Pretty(), key)
fallthrough
default:
return nil, err
}
2014-08-09 22:28:46 -07:00
}
// getLocal attempts to retrieve the value from the datastore
2016-09-03 20:35:59 +01:00
func (dht *IpfsDHT) getLocal(key key.Key) (*recpb.Record, error) {
2014-11-11 16:28:20 -08:00
log.Debug("getLocal %s", key)
2014-10-03 15:34:08 -07:00
v, err := dht.datastore.Get(key.DsKey())
if err != nil {
return nil, err
}
2014-11-11 16:28:20 -08:00
log.Debug("found in db")
byt, ok := v.([]byte)
if !ok {
return nil, errors.New("value stored in datastore not []byte")
}
2016-09-03 20:35:59 +01:00
rec := new(recpb.Record)
err = proto.Unmarshal(byt, rec)
if err != nil {
return nil, err
}
err = dht.verifyRecordLocally(rec)
if err != nil {
log.Debugf("local record verify failed: %s (discarded)", err)
return nil, err
}
return rec, nil
}
2015-01-16 23:53:56 +00:00
// getOwnPrivateKey attempts to load the local peers private
// key from the peerstore.
func (dht *IpfsDHT) getOwnPrivateKey() (ci.PrivKey, error) {
sk := dht.peerstore.PrivKey(dht.self)
if sk == nil {
2015-01-26 19:12:12 -08:00
log.Warningf("%s dht cannot get own private key!", dht.self)
return nil, fmt.Errorf("cannot get private key to sign record!")
}
return sk, nil
}
// putLocal stores the key value pair in the datastore
2016-09-03 20:35:59 +01:00
func (dht *IpfsDHT) putLocal(key key.Key, rec *recpb.Record) error {
data, err := proto.Marshal(rec)
if err != nil {
return err
}
return dht.datastore.Put(key.DsKey(), data)
}
// Update signals the routingTable to Update its last-seen status
2014-09-16 06:40:17 -07:00
// on the given peer.
func (dht *IpfsDHT) Update(ctx context.Context, p peer.ID) {
log.Event(ctx, "updatePeer", p)
dht.routingTable.Update(p)
}
2014-08-09 22:28:46 -07:00
2014-10-11 10:43:54 -07:00
// FindLocal looks for a peer with a given ID connected to this dht and returns the peer and the table it was found in.
func (dht *IpfsDHT) FindLocal(id peer.ID) pstore.PeerInfo {
p := dht.routingTable.Find(id)
if p != "" {
2014-12-28 23:46:25 +00:00
return dht.peerstore.PeerInfo(p)
2014-08-09 22:28:46 -07:00
}
return pstore.PeerInfo{}
2014-08-09 22:28:46 -07:00
}
2014-11-03 03:02:56 +00:00
// findPeerSingle asks peer 'p' if they know where the peer with id 'id' is
func (dht *IpfsDHT) findPeerSingle(ctx context.Context, p peer.ID, id peer.ID) (*pb.Message, error) {
2015-01-15 04:45:34 +00:00
defer log.EventBegin(ctx, "findPeerSingle", p, id).Done()
pmes := pb.NewMessage(pb.Message_FIND_NODE, string(id), 0)
resp, err := dht.sendRequest(ctx, p, pmes)
switch err {
case nil:
return resp, nil
case ErrReadTimeout:
log.Warningf("read timeout: %s %s", p.Pretty(), id)
fallthrough
default:
return nil, err
}
}
func (dht *IpfsDHT) findProvidersSingle(ctx context.Context, p peer.ID, key key.Key) (*pb.Message, error) {
2015-01-15 04:45:34 +00:00
defer log.EventBegin(ctx, "findProvidersSingle", p, &key).Done()
pmes := pb.NewMessage(pb.Message_GET_PROVIDERS, string(key), 0)
resp, err := dht.sendRequest(ctx, p, pmes)
switch err {
case nil:
return resp, nil
case ErrReadTimeout:
log.Warningf("read timeout: %s %s", p.Pretty(), key)
fallthrough
default:
return nil, err
}
2014-08-14 08:32:17 -07:00
}
// nearestPeersToQuery returns the routing tables closest peers.
func (dht *IpfsDHT) nearestPeersToQuery(pmes *pb.Message, count int) []peer.ID {
key := key.Key(pmes.GetKey())
closer := dht.routingTable.NearestPeers(kb.ConvertKey(key), count)
return closer
}
// betterPeerToQuery returns nearestPeersToQuery, but iff closer than self.
func (dht *IpfsDHT) betterPeersToQuery(pmes *pb.Message, p peer.ID, count int) []peer.ID {
closer := dht.nearestPeersToQuery(pmes, count)
// no node? nil
if closer == nil {
return nil
}
// == to self? thats bad
for _, p := range closer {
if p == dht.self {
log.Debug("attempted to return self! this shouldn't happen...")
return nil
}
}
var filtered []peer.ID
for _, clp := range closer {
// Dont send a peer back themselves
if p == clp {
continue
}
filtered = append(filtered, clp)
}
// ok seems like closer nodes
return filtered
}
// 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()
}