dual.go 7.45 KB
Newer Older
Will Scott's avatar
Will Scott committed
1 2 3 4 5 6 7 8
// 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"

9 10
	dht "github.com/libp2p/go-libp2p-kad-dht"

Will Scott's avatar
Will Scott committed
11 12 13 14
	"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"
15
	"github.com/libp2p/go-libp2p-core/protocol"
Will Scott's avatar
Will Scott committed
16
	"github.com/libp2p/go-libp2p-core/routing"
17
	kb "github.com/libp2p/go-libp2p-kbucket"
Will Scott's avatar
Will Scott committed
18
	helper "github.com/libp2p/go-libp2p-routing-helpers"
Steven Allen's avatar
Steven Allen committed
19 20
	ma "github.com/multiformats/go-multiaddr"

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

// 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
31 32
// LanExtension is used to differentiate local protocol requests from those on the WAN DHT.
const LanExtension protocol.ID = "/lan"
33

Will Scott's avatar
Will Scott committed
34 35 36 37 38 39 40 41 42 43
// 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)
)

44
// New creates a new DualDHT instance. Options provided are forwarded on to the two concrete
Will Scott's avatar
Will Scott committed
45 46
// IpfsDHT internal constructions, modulo additional options used by the Dual DHT to enforce
// the LAN-vs-WAN distinction.
47 48 49
// 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
50 51 52 53 54 55 56 57 58
	wanOpts := append(options,
		dht.QueryFilter(dht.PublicQueryFilter),
		dht.RoutingTableFilter(dht.PublicRoutingTableFilter),
	)
	wan, err := dht.New(ctx, h, wanOpts...)
	if err != nil {
		return nil, err
	}

59 60
	// Unless overridden by user supplied options, the LAN DHT should default
	// to 'AutoServer' mode.
Will Scott's avatar
Will Scott committed
61
	lanOpts := append(options,
Will Scott's avatar
Will Scott committed
62
		dht.ProtocolExtension(LanExtension),
Will Scott's avatar
Will Scott committed
63 64 65
		dht.QueryFilter(dht.PrivateQueryFilter),
		dht.RoutingTableFilter(dht.PrivateRoutingTableFilter),
	)
Will Scott's avatar
Will Scott committed
66 67 68
	if wan.Mode() != dht.ModeClient {
		lanOpts = append(lanOpts, dht.Mode(dht.ModeServer))
	}
Will Scott's avatar
Will Scott committed
69 70 71 72 73 74 75 76 77
	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
78 79
// Close closes the DHT context.
func (dht *DHT) Close() error {
80
	return combineErrors(dht.WAN.Close(), dht.LAN.Close())
Will Scott's avatar
Will Scott committed
81 82
}

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

// 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 {
97 98 99 100
	reqCtx, cancel := context.WithCancel(ctx)
	outCh := make(chan peer.AddrInfo)
	wanCh := dht.WAN.FindProvidersAsync(reqCtx, key, count)
	lanCh := dht.LAN.FindProvidersAsync(reqCtx, key, count)
Will Scott's avatar
Will Scott committed
101
	zeroCount := (count == 0)
102 103 104 105 106 107
	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
108
		for (zeroCount || count > 0) && (wanCh != nil || lanCh != nil) {
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
			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
137 138 139
}

// FindPeer searches for a peer with given ID
140
// Note: with signed peer records, we can change this to short circuit once either DHT returns.
Will Scott's avatar
Will Scott committed
141
func (dht *DHT) FindPeer(ctx context.Context, pid peer.ID) (peer.AddrInfo, error) {
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
	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()

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
	// Combine addresses. Try to avoid doing unnecessary work while we're at
	// it. Note: We're ignoring the errors for now as many of our DHT
	// commands can return both a result and an error.
	ai := peer.AddrInfo{ID: pid}
	if len(wanInfo.Addrs) == 0 {
		ai.Addrs = lanInfo.Addrs
	} else if len(lanInfo.Addrs) == 0 {
		ai.Addrs = wanInfo.Addrs
	} else {
		// combine addresses
		deduped := make(map[string]ma.Multiaddr, len(wanInfo.Addrs)+len(lanInfo.Addrs))
		for _, addr := range wanInfo.Addrs {
			deduped[string(addr.Bytes())] = addr
		}
		for _, addr := range lanInfo.Addrs {
			deduped[string(addr.Bytes())] = addr
		}
		ai.Addrs = make([]ma.Multiaddr, 0, len(deduped))
		for _, addr := range deduped {
			ai.Addrs = append(ai.Addrs, addr)
		}
Steven Allen's avatar
Steven Allen committed
178
	}
179 180 181 182

	// If one of the commands succeeded, don't return an error.
	if wanErr == nil || lanErr == nil {
		return ai, nil
Steven Allen's avatar
Steven Allen committed
183
	}
184 185 186 187 188 189 190 191 192

	// Otherwise, return what we have _and_ return the error.
	return ai, combineErrors(wanErr, lanErr)
}

func combineErrors(erra, errb error) error {
	// if the errors are the same, just return one.
	if erra == errb {
		return erra
Steven Allen's avatar
Steven Allen committed
193 194
	}

195 196 197 198 199 200 201 202
	// If one of the errors is a kb lookup failure (no peers in routing
	// table), return the other.
	if erra == kb.ErrLookupFailure {
		return errb
	} else if errb == kb.ErrLookupFailure {
		return erra
	}
	return multierror.Append(erra, errb).ErrorOrNil()
Will Scott's avatar
Will Scott committed
203 204 205 206 207 208 209
}

// 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)
210
	return combineErrors(erra, errb)
Will Scott's avatar
Will Scott committed
211 212 213 214 215 216 217 218 219 220 221
}

// 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.
222
func (d *DHT) GetValue(ctx context.Context, key string, opts ...routing.Option) ([]byte, error) {
Will Scott's avatar
Will Scott committed
223 224
	lanCtx, cancelLan := context.WithCancel(ctx)
	defer cancelLan()
225

Will Scott's avatar
Will Scott committed
226 227 228 229 230
	var (
		lanVal    []byte
		lanErr    error
		lanWaiter sync.WaitGroup
	)
Will Scott's avatar
Will Scott committed
231 232 233
	lanWaiter.Add(1)
	go func() {
		defer lanWaiter.Done()
Will Scott's avatar
Will Scott committed
234
		lanVal, lanErr = d.LAN.GetValue(lanCtx, key, opts...)
Will Scott's avatar
Will Scott committed
235
	}()
236

Will Scott's avatar
Will Scott committed
237
	wanVal, wanErr := d.WAN.GetValue(ctx, key, opts...)
Will Scott's avatar
Will Scott committed
238 239 240 241
	if wanErr == nil {
		cancelLan()
	}
	lanWaiter.Wait()
242 243 244 245
	if wanErr == nil {
		return wanVal, nil
	}
	if lanErr == nil {
Will Scott's avatar
Will Scott committed
246
		return lanVal, nil
Will Scott's avatar
Will Scott committed
247
	}
248
	return nil, combineErrors(wanErr, lanErr)
Will Scott's avatar
Will Scott committed
249 250 251 252
}

// 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
253 254
	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
255 256 257
}

// GetPublicKey returns the public key for the given peer.
Will Scott's avatar
Will Scott committed
258 259 260
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
261
}