dual.go 6.18 KB
Newer Older
Will Scott's avatar
Will Scott committed
1 2 3 4 5 6 7 8 9 10 11 12
// Package dual provides an implementaiton of a split or "dual" dht, where two parallel instances
// are maintained for the global internet and the local LAN respectively.
package dual

import (
	"context"
	"sync"

	"github.com/ipfs/go-cid"
	ci "github.com/libp2p/go-libp2p-core/crypto"
	"github.com/libp2p/go-libp2p-core/host"
	"github.com/libp2p/go-libp2p-core/peer"
13
	"github.com/libp2p/go-libp2p-core/protocol"
Will Scott's avatar
Will Scott committed
14 15
	"github.com/libp2p/go-libp2p-core/routing"
	dht "github.com/libp2p/go-libp2p-kad-dht"
Will Scott's avatar
Will Scott committed
16
	helper "github.com/libp2p/go-libp2p-routing-helpers"
Will Scott's avatar
Will Scott committed
17 18

	"github.com/hashicorp/go-multierror"
Will Scott's avatar
Will Scott committed
19 20 21 22 23 24 25 26 27
)

// DHT implements the routing interface to provide two concrete DHT implementationts for use
// in IPFS that are used to support both global network users and disjoint LAN usecases.
type DHT struct {
	WAN *dht.IpfsDHT
	LAN *dht.IpfsDHT
}

Will Scott's avatar
Will Scott committed
28 29
// LanExtension is used to differentiate local protocol requests from those on the WAN DHT.
const LanExtension protocol.ID = "/lan"
30

Will Scott's avatar
Will Scott committed
31 32 33 34 35 36 37 38 39 40
// Assert that IPFS assumptions about interfaces aren't broken. These aren't a
// guarantee, but we can use them to aid refactoring.
var (
	_ routing.ContentRouting = (*DHT)(nil)
	_ routing.Routing        = (*DHT)(nil)
	_ routing.PeerRouting    = (*DHT)(nil)
	_ routing.PubKeyFetcher  = (*DHT)(nil)
	_ routing.ValueStore     = (*DHT)(nil)
)

41
// New creates a new DualDHT instance. Options provided are forwarded on to the two concrete
Will Scott's avatar
Will Scott committed
42 43
// IpfsDHT internal constructions, modulo additional options used by the Dual DHT to enforce
// the LAN-vs-WAN distinction.
44 45 46
// Note: query or routing table functional options provided as arguments to this function
// will be overriden by this constructor.
func New(ctx context.Context, h host.Host, options ...dht.Option) (*DHT, error) {
Will Scott's avatar
Will Scott committed
47 48 49 50 51 52 53 54 55
	wanOpts := append(options,
		dht.QueryFilter(dht.PublicQueryFilter),
		dht.RoutingTableFilter(dht.PublicRoutingTableFilter),
	)
	wan, err := dht.New(ctx, h, wanOpts...)
	if err != nil {
		return nil, err
	}

56 57
	// Unless overridden by user supplied options, the LAN DHT should default
	// to 'AutoServer' mode.
Will Scott's avatar
Will Scott committed
58
	lanOpts := append(options,
Will Scott's avatar
Will Scott committed
59
		dht.ProtocolExtension(LanExtension),
Will Scott's avatar
Will Scott committed
60 61 62
		dht.QueryFilter(dht.PrivateQueryFilter),
		dht.RoutingTableFilter(dht.PrivateRoutingTableFilter),
	)
Will Scott's avatar
Will Scott committed
63 64 65
	if wan.Mode() != dht.ModeClient {
		lanOpts = append(lanOpts, dht.Mode(dht.ModeServer))
	}
Will Scott's avatar
Will Scott committed
66 67 68 69 70 71 72 73 74
	lan, err := dht.New(ctx, h, lanOpts...)
	if err != nil {
		return nil, err
	}

	impl := DHT{wan, lan}
	return &impl, nil
}

Will Scott's avatar
Will Scott committed
75 76
// Close closes the DHT context.
func (dht *DHT) Close() error {
Will Scott's avatar
Will Scott committed
77
	return multierror.Append(dht.WAN.Close(), dht.LAN.Close()).ErrorOrNil()
Will Scott's avatar
Will Scott committed
78 79
}

Will Scott's avatar
Will Scott committed
80
func (dht *DHT) activeWAN() bool {
81
	return dht.WAN.RoutingTable().Size() > 0
Will Scott's avatar
Will Scott committed
82 83 84 85 86 87 88 89 90 91 92 93
}

// Provide adds the given cid to the content routing system.
func (dht *DHT) Provide(ctx context.Context, key cid.Cid, announce bool) error {
	if dht.activeWAN() {
		return dht.WAN.Provide(ctx, key, announce)
	}
	return dht.LAN.Provide(ctx, key, announce)
}

// FindProvidersAsync searches for peers who are able to provide a given key
func (dht *DHT) FindProvidersAsync(ctx context.Context, key cid.Cid, count int) <-chan peer.AddrInfo {
94 95 96 97 98 99 100 101 102 103
	reqCtx, cancel := context.WithCancel(ctx)
	outCh := make(chan peer.AddrInfo)
	wanCh := dht.WAN.FindProvidersAsync(reqCtx, key, count)
	lanCh := dht.LAN.FindProvidersAsync(reqCtx, key, count)
	go func() {
		defer cancel()
		defer close(outCh)

		found := make(map[peer.ID]struct{}, count)
		var pi peer.AddrInfo
Will Scott's avatar
Will Scott committed
104
		for count > 0 && (wanCh != nil || lanCh != nil) {
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
			var ok bool
			select {
			case pi, ok = <-wanCh:
				if !ok {
					wanCh = nil
					continue
				}
			case pi, ok = <-lanCh:
				if !ok {
					lanCh = nil
					continue
				}
			}
			// already found
			if _, ok = found[pi.ID]; ok {
				continue
			}

			select {
			case outCh <- pi:
				found[pi.ID] = struct{}{}
				count--
			case <-ctx.Done():
				return
			}
		}
	}()
	return outCh
Will Scott's avatar
Will Scott committed
133 134 135
}

// FindPeer searches for a peer with given ID
136
// Note: with signed peer records, we can change this to short circuit once either DHT returns.
Will Scott's avatar
Will Scott committed
137
func (dht *DHT) FindPeer(ctx context.Context, pid peer.ID) (peer.AddrInfo, error) {
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
	var wg sync.WaitGroup
	wg.Add(2)
	var wanInfo, lanInfo peer.AddrInfo
	var wanErr, lanErr error
	go func() {
		defer wg.Done()
		wanInfo, wanErr = dht.WAN.FindPeer(ctx, pid)
	}()
	go func() {
		defer wg.Done()
		lanInfo, lanErr = dht.LAN.FindPeer(ctx, pid)
	}()

	wg.Wait()

Will Scott's avatar
Will Scott committed
153 154
	return peer.AddrInfo{
		ID:    pid,
155
		Addrs: append(wanInfo.Addrs, lanInfo.Addrs...),
Will Scott's avatar
Will Scott committed
156
	}, multierror.Append(wanErr, lanErr).ErrorOrNil()
Will Scott's avatar
Will Scott committed
157 158 159 160 161 162 163
}

// Bootstrap allows callers to hint to the routing system to get into a
// Boostrapped state and remain there.
func (dht *DHT) Bootstrap(ctx context.Context) error {
	erra := dht.WAN.Bootstrap(ctx)
	errb := dht.LAN.Bootstrap(ctx)
Will Scott's avatar
Will Scott committed
164
	return multierror.Append(erra, errb).ErrorOrNil()
Will Scott's avatar
Will Scott committed
165 166 167 168 169 170 171 172 173 174 175
}

// PutValue adds value corresponding to given Key.
func (dht *DHT) PutValue(ctx context.Context, key string, val []byte, opts ...routing.Option) error {
	if dht.activeWAN() {
		return dht.WAN.PutValue(ctx, key, val, opts...)
	}
	return dht.LAN.PutValue(ctx, key, val, opts...)
}

// GetValue searches for the value corresponding to given Key.
176
func (d *DHT) GetValue(ctx context.Context, key string, opts ...routing.Option) ([]byte, error) {
Will Scott's avatar
Will Scott committed
177 178
	lanCtx, cancelLan := context.WithCancel(ctx)
	defer cancelLan()
179

Will Scott's avatar
Will Scott committed
180 181 182 183 184
	var (
		lanVal    []byte
		lanErr    error
		lanWaiter sync.WaitGroup
	)
Will Scott's avatar
Will Scott committed
185 186 187
	lanWaiter.Add(1)
	go func() {
		defer lanWaiter.Done()
Will Scott's avatar
Will Scott committed
188
		lanVal, lanErr = d.LAN.GetValue(lanCtx, key, opts...)
Will Scott's avatar
Will Scott committed
189
	}()
190

Will Scott's avatar
Will Scott committed
191
	wanVal, wanErr := d.WAN.GetValue(ctx, key, opts...)
Will Scott's avatar
Will Scott committed
192 193 194 195
	if wanErr == nil {
		cancelLan()
	}
	lanWaiter.Wait()
Will Scott's avatar
Will Scott committed
196 197 198
	if wanErr != nil {
		if lanErr != nil {
			return nil, multierror.Append(wanErr, lanErr).ErrorOrNil()
199
		}
Will Scott's avatar
Will Scott committed
200
		return lanVal, nil
Will Scott's avatar
Will Scott committed
201
	}
Will Scott's avatar
Will Scott committed
202
	return wanVal, nil
Will Scott's avatar
Will Scott committed
203 204 205 206
}

// SearchValue searches for better values from this value
func (dht *DHT) SearchValue(ctx context.Context, key string, opts ...routing.Option) (<-chan []byte, error) {
Will Scott's avatar
Will Scott committed
207 208
	p := helper.Parallel{Routers: []routing.Routing{dht.WAN, dht.LAN}, Validator: dht.WAN.Validator}
	return p.SearchValue(ctx, key, opts...)
Will Scott's avatar
Will Scott committed
209 210 211
}

// GetPublicKey returns the public key for the given peer.
Will Scott's avatar
Will Scott committed
212 213 214
func (dht *DHT) GetPublicKey(ctx context.Context, pid peer.ID) (ci.PubKey, error) {
	p := helper.Parallel{Routers: []routing.Routing{dht.WAN, dht.LAN}, Validator: dht.WAN.Validator}
	return p.GetPublicKey(ctx, pid)
Will Scott's avatar
Will Scott committed
215
}