dual.go 6.29 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
}

Steven Allen's avatar
Steven Allen committed
80 81
// WANActive returns true when the WAN DHT is active (has peers).
func (dht *DHT) WANActive() bool {
82
	return dht.WAN.RoutingTable().Size() > 0
Will Scott's avatar
Will Scott committed
83 84 85 86
}

// Provide adds the given cid to the content routing system.
func (dht *DHT) Provide(ctx context.Context, key cid.Cid, announce bool) error {
Steven Allen's avatar
Steven Allen committed
87
	if dht.WANActive() {
Will Scott's avatar
Will Scott committed
88 89 90 91 92 93 94
		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 {
95 96 97 98
	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
99
	zeroCount := (count == 0)
100 101 102 103 104 105
	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
106
		for (zeroCount || count > 0) && (wanCh != nil || lanCh != nil) {
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 133 134
			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
135 136 137
}

// FindPeer searches for a peer with given ID
138
// Note: with signed peer records, we can change this to short circuit once either DHT returns.
Will Scott's avatar
Will Scott committed
139
func (dht *DHT) FindPeer(ctx context.Context, pid peer.ID) (peer.AddrInfo, error) {
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
	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
155 156
	return peer.AddrInfo{
		ID:    pid,
157
		Addrs: append(wanInfo.Addrs, lanInfo.Addrs...),
Will Scott's avatar
Will Scott committed
158
	}, multierror.Append(wanErr, lanErr).ErrorOrNil()
Will Scott's avatar
Will Scott committed
159 160 161 162 163 164 165
}

// 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
166
	return multierror.Append(erra, errb).ErrorOrNil()
Will Scott's avatar
Will Scott committed
167 168 169 170
}

// PutValue adds value corresponding to given Key.
func (dht *DHT) PutValue(ctx context.Context, key string, val []byte, opts ...routing.Option) error {
Steven Allen's avatar
Steven Allen committed
171
	if dht.WANActive() {
Will Scott's avatar
Will Scott committed
172 173 174 175 176 177
		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.
178
func (d *DHT) GetValue(ctx context.Context, key string, opts ...routing.Option) ([]byte, error) {
Will Scott's avatar
Will Scott committed
179 180
	lanCtx, cancelLan := context.WithCancel(ctx)
	defer cancelLan()
181

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

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

// 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
209 210
	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
211 212 213
}

// GetPublicKey returns the public key for the given peer.
Will Scott's avatar
Will Scott committed
214 215 216
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
217
}