dual_test.go 8.46 KB
Newer Older
Will Scott's avatar
Will Scott committed
1 2 3 4 5 6 7 8 9
package dual

import (
	"context"
	"testing"
	"time"

	"github.com/ipfs/go-cid"
	u "github.com/ipfs/go-ipfs-util"
10
	"github.com/libp2p/go-libp2p-core/host"
Will Scott's avatar
Will Scott committed
11
	"github.com/libp2p/go-libp2p-core/peer"
Will Scott's avatar
lint  
Will Scott committed
12
	peerstore "github.com/libp2p/go-libp2p-core/peerstore"
Will Scott's avatar
Will Scott committed
13
	dht "github.com/libp2p/go-libp2p-kad-dht"
Will Scott's avatar
Will Scott committed
14 15
	test "github.com/libp2p/go-libp2p-kad-dht/internal/testing"
	record "github.com/libp2p/go-libp2p-record"
Will Scott's avatar
Will Scott committed
16 17
	swarmt "github.com/libp2p/go-libp2p-swarm/testing"
	bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
Steven Allen's avatar
Steven Allen committed
18
	"github.com/multiformats/go-multiaddr"
Will Scott's avatar
Will Scott committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
)

var wancid, lancid cid.Cid

func init() {
	wancid = cid.NewCidV1(cid.DagCBOR, u.Hash([]byte("wan cid -- value")))
	lancid = cid.NewCidV1(cid.DagCBOR, u.Hash([]byte("lan cid -- value")))
}

type blankValidator struct{}

func (blankValidator) Validate(_ string, _ []byte) error        { return nil }
func (blankValidator) Select(_ string, _ [][]byte) (int, error) { return 0, nil }

type customRtHelper struct {
	allow peer.ID
}

37
func MkFilterForPeer() (func(_ interface{}, p peer.ID) bool, *customRtHelper) {
Will Scott's avatar
Will Scott committed
38
	helper := customRtHelper{}
39 40 41 42 43 44 45 46 47

	type hasHost interface {
		Host() host.Host
	}

	f := func(dht interface{}, p peer.ID) bool {
		d := dht.(hasHost)
		conns := d.Host().Network().ConnsToPeer(p)

Will Scott's avatar
Will Scott committed
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
		for _, c := range conns {
			if c.RemotePeer() == helper.allow {
				return true
			}
		}
		return false
	}
	return f, &helper
}

func setupDHTWithFilters(ctx context.Context, t *testing.T, options ...dht.Option) (*DHT, []*customRtHelper) {
	h := bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport))

	wanFilter, wanRef := MkFilterForPeer()
	wanOpts := []dht.Option{
		dht.NamespacedValidator("v", blankValidator{}),
		dht.ProtocolPrefix("/test"),
		dht.DisableAutoRefresh(),
		dht.RoutingTableFilter(wanFilter),
	}
	wan, err := dht.New(ctx, h, wanOpts...)
	if err != nil {
		t.Fatal(err)
	}

	lanFilter, lanRef := MkFilterForPeer()
	lanOpts := []dht.Option{
		dht.NamespacedValidator("v", blankValidator{}),
		dht.ProtocolPrefix("/test"),
Will Scott's avatar
Will Scott committed
77
		dht.ProtocolExtension(LanExtension),
Will Scott's avatar
Will Scott committed
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
		dht.DisableAutoRefresh(),
		dht.RoutingTableFilter(lanFilter),
		dht.Mode(dht.ModeServer),
	}
	lan, err := dht.New(ctx, h, lanOpts...)
	if err != nil {
		t.Fatal(err)
	}

	impl := DHT{wan, lan}
	return &impl, []*customRtHelper{wanRef, lanRef}
}

func setupDHT(ctx context.Context, t *testing.T, options ...dht.Option) *DHT {
	t.Helper()
	baseOpts := []dht.Option{
		dht.NamespacedValidator("v", blankValidator{}),
		dht.ProtocolPrefix("/test"),
		dht.DisableAutoRefresh(),
	}

	d, err := New(
		ctx,
		bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
102
		append([]Option{DHTOption(baseOpts...)}, DHTOption(options...))...,
Will Scott's avatar
Will Scott committed
103 104 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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
	)
	if err != nil {
		t.Fatal(err)
	}
	return d
}

func connect(ctx context.Context, t *testing.T, a, b *dht.IpfsDHT) {
	t.Helper()
	bid := b.PeerID()
	baddr := b.Host().Peerstore().Addrs(bid)
	if len(baddr) == 0 {
		t.Fatal("no addresses for connection.")
	}
	a.Host().Peerstore().AddAddrs(bid, baddr, peerstore.TempAddrTTL)
	if err := a.Host().Connect(ctx, peer.AddrInfo{ID: bid}); err != nil {
		t.Fatal(err)
	}
	wait(ctx, t, a, b)
}

func wait(ctx context.Context, t *testing.T, a, b *dht.IpfsDHT) {
	t.Helper()
	for a.RoutingTable().Find(b.PeerID()) == "" {
		//fmt.Fprintf(os.Stderr, "%v\n", a.RoutingTable().GetPeerInfos())
		select {
		case <-ctx.Done():
			t.Fatal(ctx.Err())
		case <-time.After(time.Millisecond * 5):
		}
	}
}

func setupTier(ctx context.Context, t *testing.T) (*DHT, *dht.IpfsDHT, *dht.IpfsDHT) {
	t.Helper()
	baseOpts := []dht.Option{
		dht.NamespacedValidator("v", blankValidator{}),
		dht.ProtocolPrefix("/test"),
		dht.DisableAutoRefresh(),
	}

	d, hlprs := setupDHTWithFilters(ctx, t)

	wan, err := dht.New(
		ctx,
		bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
		append(baseOpts, dht.Mode(dht.ModeServer))...,
	)
	if err != nil {
		t.Fatal(err)
	}
	hlprs[0].allow = wan.PeerID()
Will Scott's avatar
Will Scott committed
155
	connect(ctx, t, d.WAN, wan)
Will Scott's avatar
Will Scott committed
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

	lan, err := dht.New(
		ctx,
		bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
		append(baseOpts, dht.Mode(dht.ModeServer), dht.ProtocolExtension("/lan"))...,
	)
	if err != nil {
		t.Fatal(err)
	}
	hlprs[1].allow = lan.PeerID()
	connect(ctx, t, d.LAN, lan)

	return d, wan, lan
}

func TestDualModes(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()

	d := setupDHT(ctx, t)
	defer d.Close()

	if d.WAN.Mode() != dht.ModeAuto {
		t.Fatal("wrong default mode for wan")
	} else if d.LAN.Mode() != dht.ModeServer {
		t.Fatal("wrong default mode for lan")
	}

	d2 := setupDHT(ctx, t, dht.Mode(dht.ModeClient))
	defer d2.Close()
	if d2.WAN.Mode() != dht.ModeClient ||
		d2.LAN.Mode() != dht.ModeClient {
		t.Fatal("wrong client mode operation")
	}
}

func TestFindProviderAsync(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()

	d, wan, lan := setupTier(ctx, t)
	defer d.Close()
	defer wan.Close()
	defer lan.Close()

Will Scott's avatar
lint  
Will Scott committed
201 202
	time.Sleep(5 * time.Millisecond)

Will Scott's avatar
Will Scott committed
203
	if err := wan.Provide(ctx, wancid, false); err != nil {
Will Scott's avatar
Will Scott committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
		t.Fatal(err)
	}

	if err := lan.Provide(ctx, lancid, true); err != nil {
		t.Fatal(err)
	}

	wpc := d.FindProvidersAsync(ctx, wancid, 1)
	select {
	case p := <-wpc:
		if p.ID != wan.PeerID() {
			t.Fatal("wrong wan provider")
		}
	case <-ctx.Done():
		t.Fatal("find provider timeout.")
	}

	lpc := d.FindProvidersAsync(ctx, lancid, 1)
	select {
	case p := <-lpc:
		if p.ID != lan.PeerID() {
			t.Fatal("wrong lan provider")
		}
	case <-ctx.Done():
		t.Fatal("find provider timeout.")
	}
}
Will Scott's avatar
Will Scott committed
231 232 233 234 235 236 237 238 239 240

func TestValueGetSet(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()

	d, wan, lan := setupTier(ctx, t)
	defer d.Close()
	defer wan.Close()
	defer lan.Close()

Will Scott's avatar
lint  
Will Scott committed
241 242
	time.Sleep(5 * time.Millisecond)

Will Scott's avatar
Will Scott committed
243
	err := d.PutValue(ctx, "/v/hello", []byte("valid"))
Will Scott's avatar
Will Scott committed
244 245 246 247 248 249 250
	if err != nil {
		t.Fatal(err)
	}
	val, err := wan.GetValue(ctx, "/v/hello")
	if err != nil {
		t.Fatal(err)
	}
Will Scott's avatar
Will Scott committed
251
	if string(val) != "valid" {
Will Scott's avatar
Will Scott committed
252 253 254
		t.Fatal("failed to get expected string.")
	}

Will Scott's avatar
lint  
Will Scott committed
255
	_, err = lan.GetValue(ctx, "/v/hello")
Will Scott's avatar
Will Scott committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269
	if err == nil {
		t.Fatal(err)
	}
}

func TestSearchValue(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()

	d, wan, lan := setupTier(ctx, t)
	defer d.Close()
	defer wan.Close()
	defer lan.Close()

Will Scott's avatar
Will Scott committed
270 271 272
	d.WAN.Validator.(record.NamespacedValidator)["v"] = test.TestValidator{}
	d.LAN.Validator.(record.NamespacedValidator)["v"] = test.TestValidator{}

Will Scott's avatar
lint  
Will Scott committed
273
	_ = wan.PutValue(ctx, "/v/hello", []byte("valid"))
Will Scott's avatar
Will Scott committed
274 275 276 277 278 279 280 281

	valCh, err := d.SearchValue(ctx, "/v/hello", dht.Quorum(0))
	if err != nil {
		t.Fatal(err)
	}

	select {
	case v := <-valCh:
Will Scott's avatar
Will Scott committed
282 283
		if string(v) != "valid" {
			t.Errorf("expected 'valid', got '%s'", string(v))
Will Scott's avatar
Will Scott committed
284 285 286 287 288
		}
	case <-ctx.Done():
		t.Fatal(ctx.Err())
	}

Will Scott's avatar
Will Scott committed
289 290 291 292 293 294 295 296 297
	select {
	case _, ok := <-valCh:
		if ok {
			t.Errorf("chan should close")
		}
	case <-ctx.Done():
		t.Fatal(ctx.Err())
	}

Will Scott's avatar
Will Scott committed
298 299 300 301 302
	err = lan.PutValue(ctx, "/v/hello", []byte("newer"))
	if err != nil {
		t.Error(err)
	}

Will Scott's avatar
Will Scott committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
	valCh, err = d.SearchValue(ctx, "/v/hello", dht.Quorum(0))
	if err != nil {
		t.Fatal(err)
	}

	var lastVal []byte
	for c := range valCh {
		lastVal = c
	}
	if string(lastVal) != "newer" {
		t.Fatal("incorrect best search value")
	}
}

func TestGetPublicKey(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()

	d, wan, lan := setupTier(ctx, t)
	defer d.Close()
	defer wan.Close()
	defer lan.Close()

Will Scott's avatar
lint  
Will Scott committed
326 327
	time.Sleep(5 * time.Millisecond)

Will Scott's avatar
Will Scott committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
	pk, err := d.GetPublicKey(ctx, wan.PeerID())
	if err != nil {
		t.Fatal(err)
	}
	id, err := peer.IDFromPublicKey(pk)
	if err != nil {
		t.Fatal(err)
	}
	if id != wan.PeerID() {
		t.Fatal("incorrect PK")
	}

	pk, err = d.GetPublicKey(ctx, lan.PeerID())
	if err != nil {
		t.Fatal(err)
	}
	id, err = peer.IDFromPublicKey(pk)
	if err != nil {
		t.Fatal(err)
	}
	if id != lan.PeerID() {
		t.Fatal("incorrect PK")
	}
}

func TestFindPeer(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()

	d, wan, lan := setupTier(ctx, t)
	defer d.Close()
	defer wan.Close()
	defer lan.Close()

Will Scott's avatar
lint  
Will Scott committed
362 363
	time.Sleep(5 * time.Millisecond)

Will Scott's avatar
Will Scott committed
364 365 366 367
	p, err := d.FindPeer(ctx, lan.PeerID())
	if err != nil {
		t.Fatal(err)
	}
Steven Allen's avatar
Steven Allen committed
368
	assertUniqueMultiaddrs(t, p.Addrs)
Will Scott's avatar
Will Scott committed
369 370 371 372
	p, err = d.FindPeer(ctx, wan.PeerID())
	if err != nil {
		t.Fatal(err)
	}
Steven Allen's avatar
Steven Allen committed
373 374 375 376 377 378 379 380 381 382
	assertUniqueMultiaddrs(t, p.Addrs)
}

func assertUniqueMultiaddrs(t *testing.T, addrs []multiaddr.Multiaddr) {
	set := make(map[string]bool)
	for _, addr := range addrs {
		if set[string(addr.Bytes())] {
			t.Errorf("duplicate address %s", addr)
		}
		set[string(addr.Bytes())] = true
Will Scott's avatar
Will Scott committed
383 384
	}
}