dht_test.go 45.8 KB
Newer Older
1 2
package dht

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
3
import (
4
	"bytes"
Jeromy's avatar
Jeromy committed
5
	"context"
6
	"encoding/binary"
7
	"errors"
8
	"fmt"
9
	"math/rand"
10
	"sort"
11
	"strings"
12
	"sync"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
13
	"testing"
14
	"time"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
15

16 17
	"github.com/libp2p/go-libp2p-core/event"
	"github.com/libp2p/go-libp2p-core/network"
18 19 20
	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/libp2p/go-libp2p-core/peerstore"
	"github.com/libp2p/go-libp2p-core/routing"
21
	"github.com/multiformats/go-multihash"
22
	"github.com/multiformats/go-multistream"
23 24 25 26

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

27
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
28

29
	"github.com/ipfs/go-cid"
30
	u "github.com/ipfs/go-ipfs-util"
31
	kb "github.com/libp2p/go-libp2p-kbucket"
32
	record "github.com/libp2p/go-libp2p-record"
Steven Allen's avatar
Steven Allen committed
33
	swarmt "github.com/libp2p/go-libp2p-swarm/testing"
34
	"github.com/libp2p/go-libp2p-testing/ci"
Jeromy's avatar
Jeromy committed
35
	bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
36
	ma "github.com/multiformats/go-multiaddr"
37 38

	detectrace "github.com/ipfs/go-detect-race"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39 40
)

41
var testCaseCids []cid.Cid
42 43 44 45

func init() {
	for i := 0; i < 100; i++ {
		v := fmt.Sprintf("%d -- value", i)
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
		var newCid cid.Cid
		switch i % 3 {
		case 0:
			mhv := u.Hash([]byte(v))
			newCid = cid.NewCidV0(mhv)
		case 1:
			mhv := u.Hash([]byte(v))
			newCid = cid.NewCidV1(cid.DagCBOR, mhv)
		case 2:
			rawMh := make([]byte, 12)
			binary.PutUvarint(rawMh, cid.Raw)
			binary.PutUvarint(rawMh[1:], 10)
			copy(rawMh[2:], []byte(v)[:10])
			_, mhv, err := multihash.MHFromBytes(rawMh)
			if err != nil {
				panic(err)
			}
			newCid = cid.NewCidV1(cid.Raw, mhv)
		}
		testCaseCids = append(testCaseCids, newCid)
67 68 69
	}
}

70 71 72 73 74 75 76 77 78 79
type blankValidator struct{}

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

type testValidator struct{}

func (testValidator) Select(_ string, bs [][]byte) (int, error) {
	index := -1
	for i, b := range bs {
80
		if bytes.Equal(b, []byte("newer")) {
81
			index = i
82
		} else if bytes.Equal(b, []byte("valid")) {
83 84 85 86 87 88 89 90 91 92 93
			if index == -1 {
				index = i
			}
		}
	}
	if index == -1 {
		return -1, errors.New("no rec found")
	}
	return index, nil
}
func (testValidator) Validate(_ string, b []byte) error {
94
	if bytes.Equal(b, []byte("expired")) {
95 96 97 98 99
		return errors.New("expired")
	}
	return nil
}

100 101 102 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
type testAtomicPutValidator struct {
	testValidator
}

// selects the entry with the 'highest' last byte
func (testAtomicPutValidator) Select(_ string, bs [][]byte) (int, error) {
	index := -1
	max := uint8(0)
	for i, b := range bs {
		if bytes.Equal(b, []byte("valid")) {
			if index == -1 {
				index = i
			}
			continue
		}

		str := string(b)
		n := str[len(str)-1]
		if n > max {
			max = n
			index = i
		}

	}
	if index == -1 {
		return -1, errors.New("no rec found")
	}
	return index, nil
}

Adin Schmahmann's avatar
Adin Schmahmann committed
130 131
var testPrefix = ProtocolPrefix("/test")

132 133
func setupDHT(ctx context.Context, t *testing.T, client bool, options ...Option) *IpfsDHT {
	baseOpts := []Option{
Adin Schmahmann's avatar
Adin Schmahmann committed
134
		testPrefix,
135 136
		NamespacedValidator("v", blankValidator{}),
		DisableAutoRefresh(),
137 138 139
	}

	if client {
140
		baseOpts = append(baseOpts, Mode(ModeClient))
141
	} else {
142
		baseOpts = append(baseOpts, Mode(ModeServer))
143 144
	}

145 146
	d, err := New(
		ctx,
Steven Allen's avatar
Steven Allen committed
147
		bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
148
		append(baseOpts, options...)...,
149 150 151
	)
	if err != nil {
		t.Fatal(err)
152
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153 154 155
	return d
}

156
func setupDHTS(t *testing.T, ctx context.Context, n int) []*IpfsDHT {
157
	addrs := make([]ma.Multiaddr, n)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
	dhts := make([]*IpfsDHT, n)
159 160
	peers := make([]peer.ID, n)

161 162 163
	sanityAddrsMap := make(map[string]struct{})
	sanityPeersMap := make(map[string]struct{})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164
	for i := 0; i < n; i++ {
165
		dhts[i] = setupDHT(ctx, t, false)
166 167
		peers[i] = dhts[i].PeerID()
		addrs[i] = dhts[i].host.Addrs()[0]
168 169

		if _, lol := sanityAddrsMap[addrs[i].String()]; lol {
Jakub Sztandera's avatar
Jakub Sztandera committed
170
			t.Fatal("While setting up DHTs address got duplicated.")
171 172 173 174
		} else {
			sanityAddrsMap[addrs[i].String()] = struct{}{}
		}
		if _, lol := sanityPeersMap[peers[i].String()]; lol {
Jakub Sztandera's avatar
Jakub Sztandera committed
175
			t.Fatal("While setting up DHTs peerid got duplicated.")
176 177 178
		} else {
			sanityPeersMap[peers[i].String()] = struct{}{}
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179 180
	}

181
	return dhts
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182 183
}

184
func connectNoSync(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
185 186
	t.Helper()

187
	idB := b.self
188
	addrB := b.peerstore.Addrs(idB)
189 190
	if len(addrB) == 0 {
		t.Fatal("peers setup incorrectly: no local address")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
191
	}
192

193 194
	a.peerstore.AddAddrs(idB, addrB, peerstore.TempAddrTTL)
	pi := peer.AddrInfo{ID: idB}
Jeromy's avatar
Jeromy committed
195
	if err := a.host.Connect(ctx, pi); err != nil {
196
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197
	}
198 199
}

200 201
func wait(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
	t.Helper()
202

203 204
	// loop until connection notification has been received.
	// under high load, this may not happen as immediately as we would like.
205
	for a.routingTable.Find(b.self) == "" {
206 207 208 209 210
		select {
		case <-ctx.Done():
			t.Fatal(ctx.Err())
		case <-time.After(time.Millisecond * 5):
		}
211
	}
212
}
213

214 215 216 217 218
func connect(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
	t.Helper()
	connectNoSync(t, ctx, a, b)
	wait(t, ctx, a, b)
	wait(t, ctx, b, a)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
219 220
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
221
func bootstrap(t *testing.T, ctx context.Context, dhts []*IpfsDHT) {
222
	ctx, cancel := context.WithCancel(ctx)
Steven Allen's avatar
Steven Allen committed
223 224
	defer cancel()

225
	logger.Debugf("refreshing DHTs routing tables...")
226 227 228 229 230 231 232 233 234

	// tried async. sequential fares much better. compare:
	// 100 async https://gist.github.com/jbenet/56d12f0578d5f34810b2
	// 100 sync https://gist.github.com/jbenet/6c59e7c15426e48aaedd
	// probably because results compound

	start := rand.Intn(len(dhts)) // randomize to decrease bias.
	for i := range dhts {
		dht := dhts[(start+i)%len(dhts)]
235 236 237 238 239 240 241 242
		select {
		case err := <-dht.RefreshRoutingTable():
			if err != nil {
				t.Error(err)
			}
		case <-ctx.Done():
			return
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
243 244 245
	}
}

246 247
// Check to make sure we always signal the RefreshRoutingTable channel.
func TestRefreshMultiple(t *testing.T) {
Adin Schmahmann's avatar
Adin Schmahmann committed
248 249
	// TODO: What's with this test? How long should it take and why does RefreshRoutingTable not take a context?
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
	defer cancel()

	dhts := setupDHTS(t, ctx, 5)
	defer func() {
		for _, dht := range dhts {
			dht.Close()
			defer dht.host.Close()
		}
	}()

	for _, dht := range dhts[1:] {
		connect(t, ctx, dhts[0], dht)
	}

	a := dhts[0].RefreshRoutingTable()
	time.Sleep(time.Nanosecond)
	b := dhts[0].RefreshRoutingTable()
	time.Sleep(time.Nanosecond)
	c := dhts[0].RefreshRoutingTable()

	// make sure that all of these eventually return
	select {
	case <-a:
	case <-ctx.Done():
		t.Fatal("first channel didn't signal")
	}
	select {
	case <-b:
	case <-ctx.Done():
		t.Fatal("second channel didn't signal")
	}
	select {
	case <-c:
	case <-ctx.Done():
		t.Fatal("third channel didn't signal")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288
func TestValueGetSet(t *testing.T) {
289 290
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
291

Steven Allen's avatar
Steven Allen committed
292
	var dhts [5]*IpfsDHT
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
293

Steven Allen's avatar
Steven Allen committed
294 295 296 297 298
	for i := range dhts {
		dhts[i] = setupDHT(ctx, t, false)
		defer dhts[i].Close()
		defer dhts[i].host.Close()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
299

Steven Allen's avatar
Steven Allen committed
300
	connect(t, ctx, dhts[0], dhts[1])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
301

Steven Allen's avatar
Steven Allen committed
302
	t.Log("adding value on: ", dhts[0].self)
Jeromy's avatar
Jeromy committed
303 304
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
Steven Allen's avatar
Steven Allen committed
305
	err := dhts[0].PutValue(ctxT, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
306 307 308 309
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
310
	t.Log("requesting value on dhts: ", dhts[1].self)
Adin Schmahmann's avatar
Adin Schmahmann committed
311
	ctxT, cancel = context.WithTimeout(ctx, time.Second*2*60)
Jeromy's avatar
Jeromy committed
312
	defer cancel()
Steven Allen's avatar
Steven Allen committed
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329

	val, err := dhts[1].GetValue(ctxT, "/v/hello")
	if err != nil {
		t.Fatal(err)
	}

	if string(val) != "world" {
		t.Fatalf("Expected 'world' got '%s'", string(val))
	}

	// late connect

	connect(t, ctx, dhts[2], dhts[0])
	connect(t, ctx, dhts[2], dhts[1])

	t.Log("requesting value (offline) on dhts: ", dhts[2].self)
	vala, err := dhts[2].GetValue(ctxT, "/v/hello", Quorum(0))
Adin Schmahmann's avatar
Adin Schmahmann committed
330 331
	if err != nil {
		t.Fatal(err)
Steven Allen's avatar
Steven Allen committed
332 333
	}

Adin Schmahmann's avatar
Adin Schmahmann committed
334 335 336
	if string(vala) != "world" {
		t.Fatalf("Expected 'world' got '%s'", string(vala))
	}
Steven Allen's avatar
Steven Allen committed
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
	t.Log("requesting value (online) on dhts: ", dhts[2].self)
	val, err = dhts[2].GetValue(ctxT, "/v/hello")
	if err != nil {
		t.Fatal(err)
	}

	if string(val) != "world" {
		t.Fatalf("Expected 'world' got '%s'", string(val))
	}

	for _, d := range dhts[:3] {
		connect(t, ctx, dhts[3], d)
	}
	connect(t, ctx, dhts[4], dhts[3])

	t.Log("requesting value (requires peer routing) on dhts: ", dhts[4].self)
	val, err = dhts[4].GetValue(ctxT, "/v/hello")
354 355 356 357
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
358 359
	if string(val) != "world" {
		t.Fatalf("Expected 'world' got '%s'", string(val))
360
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
361 362
}

363 364 365 366 367 368 369 370 371 372 373 374
func TestValueSetInvalid(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dhtA := setupDHT(ctx, t, false)
	dhtB := setupDHT(ctx, t, false)

	defer dhtA.Close()
	defer dhtB.Close()
	defer dhtA.host.Close()
	defer dhtB.host.Close()

375
	dhtA.Validator.(record.NamespacedValidator)["v"] = testValidator{}
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
	dhtB.Validator.(record.NamespacedValidator)["v"] = blankValidator{}

	connect(t, ctx, dhtA, dhtB)

	testSetGet := func(val string, failset bool, exp string, experr error) {
		t.Helper()

		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		err := dhtA.PutValue(ctxT, "/v/hello", []byte(val))
		if failset {
			if err == nil {
				t.Error("expected set to fail")
			}
		} else {
			if err != nil {
				t.Error(err)
			}
		}

		ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
		defer cancel()
		valb, err := dhtB.GetValue(ctxT, "/v/hello")
		if err != experr {
			t.Errorf("Set/Get %v: Expected %v error but got %v", val, experr, err)
		} else if err == nil && string(valb) != exp {
			t.Errorf("Expected '%v' got '%s'", exp, string(valb))
		}
	}

	// Expired records should not be set
	testSetGet("expired", true, "", routing.ErrNotFound)
	// Valid record should be returned
	testSetGet("valid", false, "valid", nil)
	// Newer record should supersede previous record
	testSetGet("newer", false, "newer", nil)
	// Attempt to set older record again should be ignored
	testSetGet("valid", true, "newer", nil)
}

Aarsh Shah's avatar
Aarsh Shah committed
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
func TestContextShutDown(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dht := setupDHT(ctx, t, false)

	// context is alive
	select {
	case <-dht.Context().Done():
		t.Fatal("context should not be done")
	default:
	}

	// shut down dht
	require.NoError(t, dht.Close())

	// now context should be done
	select {
	case <-dht.Context().Done():
	default:
		t.Fatal("context should be done")
	}
}

Łukasz Magiera's avatar
Łukasz Magiera committed
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
func TestSearchValue(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dhtA := setupDHT(ctx, t, false)
	dhtB := setupDHT(ctx, t, false)

	defer dhtA.Close()
	defer dhtB.Close()
	defer dhtA.host.Close()
	defer dhtB.host.Close()

	connect(t, ctx, dhtA, dhtB)

	dhtA.Validator.(record.NamespacedValidator)["v"] = testValidator{}
	dhtB.Validator.(record.NamespacedValidator)["v"] = testValidator{}

	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()

	err := dhtA.PutValue(ctxT, "/v/hello", []byte("valid"))
	if err != nil {
		t.Error(err)
	}

	ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
	defer cancel()
467
	valCh, err := dhtA.SearchValue(ctxT, "/v/hello", Quorum(0))
468 469 470
	if err != nil {
		t.Fatal(err)
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495

	select {
	case v := <-valCh:
		if string(v) != "valid" {
			t.Errorf("expected 'valid', got '%s'", string(v))
		}
	case <-ctxT.Done():
		t.Fatal(ctxT.Err())
	}

	err = dhtB.PutValue(ctxT, "/v/hello", []byte("newer"))
	if err != nil {
		t.Error(err)
	}

	select {
	case v := <-valCh:
		if string(v) != "newer" {
			t.Errorf("expected 'newer', got '%s'", string(v))
		}
	case <-ctxT.Done():
		t.Fatal(ctxT.Err())
	}
}

496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
func TestGetValues(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dhtA := setupDHT(ctx, t, false)
	dhtB := setupDHT(ctx, t, false)

	defer dhtA.Close()
	defer dhtB.Close()
	defer dhtA.host.Close()
	defer dhtB.host.Close()

	connect(t, ctx, dhtA, dhtB)

	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()

	err := dhtB.PutValue(ctxT, "/v/hello", []byte("newer"))
	if err != nil {
		t.Error(err)
	}

	err = dhtA.PutValue(ctxT, "/v/hello", []byte("valid"))
	if err != nil {
		t.Error(err)
	}

	ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
	defer cancel()
	vals, err := dhtA.GetValues(ctxT, "/v/hello", 16)
	if err != nil {
		t.Fatal(err)
	}

	if len(vals) != 2 {
		t.Fatalf("expected to get 2 values, got %d", len(vals))
	}

534
	sort.Slice(vals, func(i, j int) bool { return string(vals[i].Val) < string(vals[j].Val) })
535 536 537 538 539 540 541 542 543

	if string(vals[0].Val) != "valid" {
		t.Errorf("unexpected vals[0]: %s", string(vals[0].Val))
	}
	if string(vals[1].Val) != "valid" {
		t.Errorf("unexpected vals[1]: %s", string(vals[1].Val))
	}
}

544 545 546 547 548 549 550 551 552 553 554 555 556
func TestValueGetInvalid(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dhtA := setupDHT(ctx, t, false)
	dhtB := setupDHT(ctx, t, false)

	defer dhtA.Close()
	defer dhtB.Close()
	defer dhtA.host.Close()
	defer dhtB.host.Close()

	dhtA.Validator.(record.NamespacedValidator)["v"] = blankValidator{}
557
	dhtB.Validator.(record.NamespacedValidator)["v"] = testValidator{}
558 559 560 561

	connect(t, ctx, dhtA, dhtB)

	testSetGet := func(val string, exp string, experr error) {
562 563
		t.Helper()

564 565 566 567
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		err := dhtA.PutValue(ctxT, "/v/hello", []byte(val))
		if err != nil {
568
			t.Error(err)
569 570 571 572 573 574
		}

		ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
		defer cancel()
		valb, err := dhtB.GetValue(ctxT, "/v/hello")
		if err != experr {
Łukasz Magiera's avatar
Łukasz Magiera committed
575
			t.Errorf("Set/Get %v: Expected '%v' error but got '%v'", val, experr, err)
576 577
		} else if err == nil && string(valb) != exp {
			t.Errorf("Expected '%v' got '%s'", exp, string(valb))
578 579 580 581 582 583 584 585 586 587 588 589 590
		}
	}

	// Expired records should not be returned
	testSetGet("expired", "", routing.ErrNotFound)
	// Valid record should be returned
	testSetGet("valid", "valid", nil)
	// Newer record should supersede previous record
	testSetGet("newer", "newer", nil)
	// Attempt to set older record again should be ignored
	testSetGet("valid", "newer", nil)
}

591
func TestInvalidMessageSenderTracking(t *testing.T) {
Steven Allen's avatar
Steven Allen committed
592 593 594
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

595
	dht := setupDHT(ctx, t, false)
Steven Allen's avatar
Steven Allen committed
596 597
	defer dht.Close()

598
	foo := peer.ID("asdasd")
Steven Allen's avatar
Steven Allen committed
599
	_, err := dht.messageSenderForPeer(ctx, foo)
600 601 602 603 604
	if err == nil {
		t.Fatal("that shouldnt have succeeded")
	}

	dht.smlk.Lock()
Steven Allen's avatar
Steven Allen committed
605 606 607 608
	mscnt := len(dht.strmap)
	dht.smlk.Unlock()

	if mscnt > 0 {
609 610 611 612
		t.Fatal("should have no message senders in map")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
613 614
func TestProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
615 616
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
617

618
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
619 620
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
621
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
622
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
623 624 625
		}
	}()

626 627 628
	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
	connect(t, ctx, dhts[1], dhts[3])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
629

630
	for _, k := range testCaseCids {
Matt Joiner's avatar
Matt Joiner committed
631
		logger.Debugf("announcing provider for %s", k)
Jeromy's avatar
Jeromy committed
632
		if err := dhts[3].Provide(ctx, k, true); err != nil {
633 634
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
635 636
	}

637 638 639 640
	// what is this timeout for? was 60ms before.
	time.Sleep(time.Millisecond * 6)

	n := 0
641
	for _, c := range testCaseCids {
642 643
		n = (n + 1) % 3

Matt Joiner's avatar
Matt Joiner committed
644
		logger.Debugf("getting providers for %s from %d", c, n)
Jeromy's avatar
Jeromy committed
645 646
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
647
		provchan := dhts[n].FindProvidersAsync(ctxT, c, 1)
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662

		select {
		case prov := <-provchan:
			if prov.ID == "" {
				t.Fatal("Got back nil provider")
			}
			if prov.ID != dhts[3].self {
				t.Fatal("Got back wrong provider")
			}
		case <-ctxT.Done():
			t.Fatal("Did not get a provider back.")
		}
	}
}

Jeromy's avatar
Jeromy committed
663 664
func TestLocalProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
665 666
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Jeromy's avatar
Jeromy committed
667

668
	dhts := setupDHTS(t, ctx, 4)
Jeromy's avatar
Jeromy committed
669 670 671 672 673 674 675 676 677 678 679 680
	defer func() {
		for i := 0; i < 4; i++ {
			dhts[i].Close()
			defer dhts[i].host.Close()
		}
	}()

	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
	connect(t, ctx, dhts[1], dhts[3])

	for _, k := range testCaseCids {
Matt Joiner's avatar
Matt Joiner committed
681
		logger.Debugf("announcing provider for %s", k)
Jeromy's avatar
Jeromy committed
682 683 684 685 686 687 688 689 690
		if err := dhts[3].Provide(ctx, k, false); err != nil {
			t.Fatal(err)
		}
	}

	time.Sleep(time.Millisecond * 10)

	for _, c := range testCaseCids {
		for i := 0; i < 3; i++ {
691
			provs := dhts[i].ProviderManager.GetProviders(ctx, c.Hash())
Jeromy's avatar
Jeromy committed
692 693 694 695 696 697 698
			if len(provs) > 0 {
				t.Fatal("shouldnt know this")
			}
		}
	}
}

699 700 701 702 703 704 705 706 707 708
// if minPeers or avgPeers is 0, dont test for it.
func waitForWellFormedTables(t *testing.T, dhts []*IpfsDHT, minPeers, avgPeers int, timeout time.Duration) bool {
	// test "well-formed-ness" (>= minPeers peers in every routing table)

	checkTables := func() bool {
		totalPeers := 0
		for _, dht := range dhts {
			rtlen := dht.routingTable.Size()
			totalPeers += rtlen
			if minPeers > 0 && rtlen < minPeers {
709
				//t.Logf("routing table for %s only has %d peers (should have >%d)", dht.self, rtlen, minPeers)
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
				return false
			}
		}
		actualAvgPeers := totalPeers / len(dhts)
		t.Logf("avg rt size: %d", actualAvgPeers)
		if avgPeers > 0 && actualAvgPeers < avgPeers {
			t.Logf("avg rt size: %d < %d", actualAvgPeers, avgPeers)
			return false
		}
		return true
	}

	timeoutA := time.After(timeout)
	for {
		select {
		case <-timeoutA:
Matt Joiner's avatar
Matt Joiner committed
726
			logger.Debugf("did not reach well-formed routing tables by %s", timeout)
727 728 729 730 731 732 733 734 735 736 737
			return false // failed
		case <-time.After(5 * time.Millisecond):
			if checkTables() {
				return true // succeeded
			}
		}
	}
}

func printRoutingTables(dhts []*IpfsDHT) {
	// the routing tables should be full now. let's inspect them.
738
	fmt.Printf("checking routing table of %d\n", len(dhts))
739 740 741 742 743 744 745
	for _, dht := range dhts {
		fmt.Printf("checking routing table of %s\n", dht.self)
		dht.routingTable.Print()
		fmt.Println("")
	}
}

746
func TestRefresh(t *testing.T) {
747 748 749 750
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
751 752
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
753

754
	nDHTs := 30
755
	dhts := setupDHTS(t, ctx, nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
756 757 758
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
759
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
760 761 762 763 764 765 766 767
		}
	}()

	t.Logf("connecting %d dhts in a ring", nDHTs)
	for i := 0; i < nDHTs; i++ {
		connect(t, ctx, dhts[i], dhts[(i+1)%len(dhts)])
	}

768
	<-time.After(100 * time.Millisecond)
769
	// bootstrap a few times until we get good tables.
Steven Allen's avatar
Steven Allen committed
770 771 772 773
	t.Logf("bootstrapping them so they find each other %d", nDHTs)
	ctxT, cancelT := context.WithTimeout(ctx, 5*time.Second)
	defer cancelT()

Aarsh Shah's avatar
Aarsh Shah committed
774 775 776 777 778 779 780 781 782
	for ctxT.Err() == nil {
		bootstrap(t, ctxT, dhts)

		// wait a bit.
		select {
		case <-time.After(50 * time.Millisecond):
			continue // being explicit
		case <-ctxT.Done():
			return
783
		}
Aarsh Shah's avatar
Aarsh Shah committed
784
	}
785

Aarsh Shah's avatar
Aarsh Shah committed
786
	waitForWellFormedTables(t, dhts, 7, 10, 10*time.Second)
Steven Allen's avatar
Steven Allen committed
787
	cancelT()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
788

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
789 790
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
791 792 793 794
		printRoutingTables(dhts)
	}
}

795
func TestRefreshBelowMinRTThreshold(t *testing.T) {
Aarsh Shah's avatar
Aarsh Shah committed
796
	ctx := context.Background()
797 798 799 800 801

	// enable auto bootstrap on A
	dhtA, err := New(
		ctx,
		bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
Adin Schmahmann's avatar
Adin Schmahmann committed
802
		testPrefix,
803 804
		Mode(ModeServer),
		NamespacedValidator("v", blankValidator{}),
805 806 807 808 809
	)
	if err != nil {
		t.Fatal(err)
	}

Aarsh Shah's avatar
Aarsh Shah committed
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
	dhtB := setupDHT(ctx, t, false)
	dhtC := setupDHT(ctx, t, false)

	defer func() {
		dhtA.Close()
		dhtA.host.Close()

		dhtB.Close()
		dhtB.host.Close()

		dhtC.Close()
		dhtC.host.Close()
	}()

	connect(t, ctx, dhtA, dhtB)
	connect(t, ctx, dhtB, dhtC)

	// we ONLY init bootstrap on A
828
	dhtA.RefreshRoutingTable()
Aarsh Shah's avatar
Aarsh Shah committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
	// and wait for one round to complete i.e. A should be connected to both B & C
	waitForWellFormedTables(t, []*IpfsDHT{dhtA}, 2, 2, 20*time.Second)

	// now we create two new peers
	dhtD := setupDHT(ctx, t, false)
	dhtE := setupDHT(ctx, t, false)

	// connect them to each other
	connect(t, ctx, dhtD, dhtE)
	defer func() {
		dhtD.Close()
		dhtD.host.Close()

		dhtE.Close()
		dhtE.host.Close()
	}()

	// and then, on connecting the peer D to A, the min RT threshold gets triggered on A which leads to a bootstrap.
	// since the default bootstrap scan interval is 30 mins - 1 hour, we can be sure that if bootstrap happens,
	// it is because of the min RT threshold getting triggered (since default min value is 4 & we only have 2 peers in the RT when D gets connected)
	connect(t, ctx, dhtA, dhtD)

	// and because of the above bootstrap, A also discovers E !
	waitForWellFormedTables(t, []*IpfsDHT{dhtA}, 4, 4, 20*time.Second)
	assert.Equal(t, dhtE.self, dhtA.routingTable.Find(dhtE.self), "A's routing table should have peer E!")
}

856
func TestPeriodicRefresh(t *testing.T) {
857 858 859
	if ci.IsRunning() {
		t.Skip("skipping on CI. highly timing dependent")
	}
860 861 862 863
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
864 865
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
866 867

	nDHTs := 30
868
	dhts := setupDHTS(t, ctx, nDHTs)
869 870 871 872 873 874 875
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
			defer dhts[i].host.Close()
		}
	}()

876
	t.Logf("dhts are not connected. %d", nDHTs)
877 878 879 880 881 882 883 884 885 886 887
	for _, dht := range dhts {
		rtlen := dht.routingTable.Size()
		if rtlen > 0 {
			t.Errorf("routing table for %s should have 0 peers. has %d", dht.self, rtlen)
		}
	}

	for i := 0; i < nDHTs; i++ {
		connect(t, ctx, dhts[i], dhts[(i+1)%len(dhts)])
	}

888
	t.Logf("DHTs are now connected to 1-2 others. %d", nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
889
	for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
890
		rtlen := dht.routingTable.Size()
891 892
		if rtlen > 2 {
			t.Errorf("routing table for %s should have at most 2 peers. has %d", dht.self, rtlen)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
893
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
894
	}
895

896 897 898 899
	if u.Debug {
		printRoutingTables(dhts)
	}

900
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
Aarsh Shah's avatar
Aarsh Shah committed
901
	var wg sync.WaitGroup
Matt Joiner's avatar
Matt Joiner committed
902
	for _, dht := range dhts {
Aarsh Shah's avatar
Aarsh Shah committed
903 904 905 906 907
		wg.Add(1)
		go func(d *IpfsDHT) {
			<-d.RefreshRoutingTable()
			wg.Done()
		}(dht)
908
	}
909

Aarsh Shah's avatar
Aarsh Shah committed
910
	wg.Wait()
911 912
	// this is async, and we dont know when it's finished with one cycle, so keep checking
	// until the routing tables look better, or some long timeout for the failure case.
913
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
914 915 916

	if u.Debug {
		printRoutingTables(dhts)
917
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
918 919
}

920 921
func TestProvidesMany(t *testing.T) {
	t.Skip("this test doesn't work")
Steven Allen's avatar
Steven Allen committed
922 923
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
924 925

	nDHTs := 40
926
	dhts := setupDHTS(t, ctx, nDHTs)
927 928 929
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
930
			defer dhts[i].host.Close()
931 932 933 934 935 936 937 938
		}
	}()

	t.Logf("connecting %d dhts in a ring", nDHTs)
	for i := 0; i < nDHTs; i++ {
		connect(t, ctx, dhts[i], dhts[(i+1)%len(dhts)])
	}

939
	<-time.After(100 * time.Millisecond)
940
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
Jeromy's avatar
Jeromy committed
941 942
	ctxT, cancel := context.WithTimeout(ctx, 20*time.Second)
	defer cancel()
943 944
	bootstrap(t, ctxT, dhts)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
945 946 947 948 949 950 951 952
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
		t.Logf("checking routing table of %d", nDHTs)
		for _, dht := range dhts {
			fmt.Printf("checking routing table of %s\n", dht.self)
			dht.routingTable.Print()
			fmt.Println("")
		}
953
	}
954

955
	providers := make(map[cid.Cid]peer.ID)
956

957
	d := 0
958
	for _, c := range testCaseCids {
959 960
		d = (d + 1) % len(dhts)
		dht := dhts[d]
961
		providers[c] = dht.self
962

963
		t.Logf("announcing provider for %s", c)
Jeromy's avatar
Jeromy committed
964
		if err := dht.Provide(ctx, c, true); err != nil {
965 966
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
967 968
	}

969 970
	// what is this timeout for? was 60ms before.
	time.Sleep(time.Millisecond * 6)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
971

972 973
	errchan := make(chan error)

Jeromy's avatar
Jeromy committed
974 975
	ctxT, cancel = context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
976 977

	var wg sync.WaitGroup
978
	getProvider := func(dht *IpfsDHT, k cid.Cid) {
979
		defer wg.Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
980

981
		expected := providers[k]
982

983 984 985
		provchan := dht.FindProvidersAsync(ctxT, k, 1)
		select {
		case prov := <-provchan:
986 987
			actual := prov.ID
			if actual == "" {
988
				errchan <- fmt.Errorf("Got back nil provider (%s at %s)", k, dht.self)
989 990 991
			} else if actual != expected {
				errchan <- fmt.Errorf("Got back wrong provider (%s != %s) (%s at %s)",
					expected, actual, k, dht.self)
992 993 994
			}
		case <-ctxT.Done():
			errchan <- fmt.Errorf("Did not get a provider back (%s at %s)", k, dht.self)
Jeromy's avatar
Jeromy committed
995
		}
996 997
	}

998
	for _, c := range testCaseCids {
999 1000
		// everyone should be able to find it...
		for _, dht := range dhts {
Matt Joiner's avatar
Matt Joiner committed
1001
			logger.Debugf("getting providers for %s at %s", c, dht.self)
1002
			wg.Add(1)
1003
			go getProvider(dht, c)
1004
		}
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
	}

	// we need this because of printing errors
	go func() {
		wg.Wait()
		close(errchan)
	}()

	for err := range errchan {
		t.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1015 1016 1017
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1018
func TestProvidesAsync(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1019
	// t.Skip("skipping test to debug another")
1020 1021 1022
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1023

Steven Allen's avatar
Steven Allen committed
1024 1025
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1026

1027
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1028 1029
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1030
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1031
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1032 1033 1034
		}
	}()

1035 1036 1037
	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
	connect(t, ctx, dhts[1], dhts[3])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1038

Jeromy's avatar
Jeromy committed
1039
	err := dhts[3].Provide(ctx, testCaseCids[0], true)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1040 1041 1042 1043 1044 1045
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 60)

Jeromy's avatar
Jeromy committed
1046 1047
	ctxT, cancel := context.WithTimeout(ctx, time.Millisecond*300)
	defer cancel()
1048
	provs := dhts[0].FindProvidersAsync(ctxT, testCaseCids[0], 5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1049
	select {
Jeromy's avatar
Jeromy committed
1050 1051 1052 1053
	case p, ok := <-provs:
		if !ok {
			t.Fatal("Provider channel was closed...")
		}
1054
		if p.ID == "" {
Jeromy's avatar
Jeromy committed
1055 1056
			t.Fatal("Got back nil provider!")
		}
1057
		if p.ID != dhts[3].self {
1058
			t.Fatalf("got a provider, but not the right one. %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1059
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1060
	case <-ctxT.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1061 1062 1063 1064
		t.Fatal("Didnt get back providers")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1065
func TestLayeredGet(t *testing.T) {
1066 1067
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
1068

1069
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1070 1071
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1072
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1073
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1074 1075 1076
		}
	}()

1077 1078
	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
1079
	connect(t, ctx, dhts[2], dhts[3])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1080

1081
	err := dhts[3].PutValue(ctx, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1082 1083 1084 1085
	if err != nil {
		t.Fatal(err)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1086
	time.Sleep(time.Millisecond * 6)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1087

Jeromy's avatar
Jeromy committed
1088 1089
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
1090 1091 1092
	val, err := dhts[0].GetValue(ctxT, "/v/hello")
	if err != nil {
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1093
	}
1094 1095 1096

	if string(val) != "world" {
		t.Error("got wrong value")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1097 1098 1099
	}
}

1100 1101 1102 1103 1104 1105 1106 1107
func TestUnfindablePeer(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

1108
	dhts := setupDHTS(t, ctx, 4)
1109 1110 1111
	defer func() {
		for i := 0; i < 4; i++ {
			dhts[i].Close()
1112
			dhts[i].Host().Close()
1113 1114 1115 1116 1117 1118 1119 1120
		}
	}()

	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
	connect(t, ctx, dhts[2], dhts[3])

	// Give DHT 1 a bad addr for DHT 2.
1121 1122
	dhts[1].host.Peerstore().ClearAddrs(dhts[2].PeerID())
	dhts[1].host.Peerstore().AddAddr(dhts[2].PeerID(), dhts[0].Host().Addrs()[0], time.Minute)
1123 1124 1125

	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
1126
	_, err := dhts[0].FindPeer(ctxT, dhts[3].PeerID())
1127 1128 1129 1130 1131 1132 1133 1134
	if err == nil {
		t.Error("should have failed to find peer")
	}
	if ctxT.Err() != nil {
		t.Error("FindPeer should have failed before context expired")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1135
func TestFindPeer(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1136
	// t.Skip("skipping test to debug another")
1137 1138 1139
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1140

Steven Allen's avatar
Steven Allen committed
1141 1142
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1143

1144
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1145 1146
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1147
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1148
			dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1149 1150 1151
		}
	}()

1152 1153 1154
	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
	connect(t, ctx, dhts[1], dhts[3])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1155

Jeromy's avatar
Jeromy committed
1156 1157
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
1158
	p, err := dhts[0].FindPeer(ctxT, dhts[2].PeerID())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1159 1160 1161 1162
	if err != nil {
		t.Fatal(err)
	}

1163
	if p.ID == "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1164 1165 1166
		t.Fatal("Failed to find peer.")
	}

1167
	if p.ID != dhts[2].PeerID() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1168 1169 1170
		t.Fatal("Didnt find expected peer.")
	}
}
1171 1172

func TestConnectCollision(t *testing.T) {
1173 1174 1175
	if testing.Short() {
		t.SkipNow()
	}
Steven Allen's avatar
Steven Allen committed
1176 1177
	if ci.IsRunning() {
		t.Skip("Skipping on CI.")
1178
	}
1179

1180
	runTimes := 10
1181

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1182
	for rtime := 0; rtime < runTimes; rtime++ {
Matt Joiner's avatar
Matt Joiner committed
1183
		logger.Info("Running Time: ", rtime)
1184

Steven Allen's avatar
Steven Allen committed
1185
		ctx, cancel := context.WithCancel(context.Background())
1186

1187 1188
		dhtA := setupDHT(ctx, t, false)
		dhtB := setupDHT(ctx, t, false)
1189

1190 1191
		addrA := dhtA.peerstore.Addrs(dhtA.self)[0]
		addrB := dhtB.peerstore.Addrs(dhtB.self)[0]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1192

1193 1194
		peerA := dhtA.self
		peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1195

1196
		errs := make(chan error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1197
		go func() {
1198 1199
			dhtA.peerstore.AddAddr(peerB, addrB, peerstore.TempAddrTTL)
			pi := peer.AddrInfo{ID: peerB}
Jeromy's avatar
Jeromy committed
1200
			err := dhtA.host.Connect(ctx, pi)
1201
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1202 1203
		}()
		go func() {
1204 1205
			dhtB.peerstore.AddAddr(peerA, addrA, peerstore.TempAddrTTL)
			pi := peer.AddrInfo{ID: peerA}
Jeromy's avatar
Jeromy committed
1206
			err := dhtB.host.Connect(ctx, pi)
1207
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1208 1209
		}()

1210
		timeout := time.After(5 * time.Second)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1211
		select {
1212 1213 1214 1215
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1216 1217 1218 1219
		case <-timeout:
			t.Fatal("Timeout received!")
		}
		select {
1220 1221 1222 1223
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1224 1225 1226 1227
		case <-timeout:
			t.Fatal("Timeout received!")
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1228 1229
		dhtA.Close()
		dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1230 1231
		dhtA.host.Close()
		dhtB.host.Close()
Steven Allen's avatar
Steven Allen committed
1232
		cancel()
Jeromy's avatar
Jeromy committed
1233
	}
1234
}
1235 1236 1237 1238 1239

func TestBadProtoMessages(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

1240
	d := setupDHT(ctx, t, false)
1241 1242 1243 1244 1245 1246

	nilrec := new(pb.Message)
	if _, err := d.handlePutValue(ctx, "testpeer", nilrec); err == nil {
		t.Fatal("should have errored on nil record")
	}
}
1247

1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
func TestAtomicPut(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	d := setupDHT(ctx, t, false)
	d.Validator = testAtomicPutValidator{}

	// fnc to put a record
	key := "testkey"
	putRecord := func(value []byte) error {
		rec := record.MakePutRecord(key, value)
		pmes := pb.NewMessage(pb.Message_PUT_VALUE, rec.Key, 0)
		pmes.Record = rec
		_, err := d.handlePutValue(ctx, "testpeer", pmes)
		return err
	}

	// put a valid record
	if err := putRecord([]byte("valid")); err != nil {
		t.Fatal("should not have errored on a valid record")
	}

	// simultaneous puts for old & new values
	values := [][]byte{[]byte("newer1"), []byte("newer7"), []byte("newer3"), []byte("newer5")}
	var wg sync.WaitGroup
	for _, v := range values {
		wg.Add(1)
		go func(v []byte) {
			defer wg.Done()
Steven Allen's avatar
Steven Allen committed
1277
			_ = putRecord(v) // we expect some of these to fail
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
		}(v)
	}
	wg.Wait()

	// get should return the newest value
	pmes := pb.NewMessage(pb.Message_GET_VALUE, []byte(key), 0)
	msg, err := d.handleGetValue(ctx, "testkey", pmes)
	if err != nil {
		t.Fatalf("should not have errored on final get, but got %+v", err)
	}
	if string(msg.GetRecord().Value) != "newer7" {
		t.Fatalf("Expected 'newer7' got '%s'", string(msg.GetRecord().Value))
	}
}

1293 1294 1295 1296 1297 1298 1299 1300 1301
func TestClientModeConnect(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	a := setupDHT(ctx, t, false)
	b := setupDHT(ctx, t, true)

	connectNoSync(t, ctx, a, b)

1302
	c := testCaseCids[0]
1303
	p := peer.ID("TestPeer")
1304
	a.ProviderManager.AddProvider(ctx, c.Hash(), p)
1305
	time.Sleep(time.Millisecond * 5) // just in case...
1306

1307
	provs, err := b.FindProviders(ctx, c)
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
	if err != nil {
		t.Fatal(err)
	}

	if len(provs) == 0 {
		t.Fatal("Expected to get a provider back")
	}

	if provs[0].ID != p {
		t.Fatal("expected it to be our test peer")
	}
Steven Allen's avatar
Steven Allen committed
1319 1320 1321 1322 1323 1324 1325 1326 1327
	if a.routingTable.Find(b.self) != "" {
		t.Fatal("DHT clients should not be added to routing tables")
	}
	if b.routingTable.Find(a.self) == "" {
		t.Fatal("DHT server should have been added to the dht client's routing table")
	}
}

func TestClientModeFindPeer(t *testing.T) {
1328
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
Steven Allen's avatar
Steven Allen committed
1329 1330 1331 1332 1333 1334
	defer cancel()

	a := setupDHT(ctx, t, false)
	b := setupDHT(ctx, t, true)
	c := setupDHT(ctx, t, true)

1335 1336
	connectNoSync(t, ctx, b, a)
	connectNoSync(t, ctx, c, a)
Steven Allen's avatar
Steven Allen committed
1337 1338

	// Can't use `connect` because b and c are only clients.
1339 1340
	wait(t, ctx, b, a)
	wait(t, ctx, c, a)
Steven Allen's avatar
Steven Allen committed
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353

	pi, err := c.FindPeer(ctx, b.self)
	if err != nil {
		t.Fatal(err)
	}
	if len(pi.Addrs) == 0 {
		t.Fatal("should have found addresses for node b")
	}

	err = c.host.Connect(ctx, pi)
	if err != nil {
		t.Fatal(err)
	}
1354
}
1355

Matt Joiner's avatar
Matt Joiner committed
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
func minInt(a, b int) int {
	if a < b {
		return a
	} else {
		return b
	}
}

func TestFindPeerQueryMinimal(t *testing.T) {
	testFindPeerQuery(t, 2, 22, 11)
}

1368
func TestFindPeerQuery(t *testing.T) {
1369 1370 1371 1372
	if detectrace.WithRace() {
		t.Skip("skipping due to race detector max goroutines")
	}

Matt Joiner's avatar
Matt Joiner committed
1373 1374 1375 1376 1377 1378 1379 1380 1381
	if testing.Short() {
		t.Skip("skipping test in short mode")
	}
	if curFileLimit() < 1024 {
		t.Skip("insufficient file descriptors available")
	}
	testFindPeerQuery(t, 20, 80, 16)
}

Aarsh Shah's avatar
Aarsh Shah committed
1382
// NOTE: You must have ATLEAST (minRTRefreshThreshold+1) test peers before using this.
Matt Joiner's avatar
Matt Joiner committed
1383 1384 1385 1386 1387
func testFindPeerQuery(t *testing.T,
	bootstrappers, // Number of nodes connected to the querying node
	leafs, // Number of nodes that might be connected to from the bootstrappers
	bootstrapperLeafConns int, // Number of connections each bootstrapper has to the leaf nodes
) {
1388 1389 1390
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

1391
	dhts := setupDHTS(t, ctx, 1+bootstrappers+leafs)
1392
	defer func() {
Matt Joiner's avatar
Matt Joiner committed
1393 1394 1395
		for _, d := range dhts {
			d.Close()
			d.host.Close()
1396 1397 1398
		}
	}()

Jeromy's avatar
Jeromy committed
1399
	mrand := rand.New(rand.NewSource(42))
1400 1401
	guy := dhts[0]
	others := dhts[1:]
Matt Joiner's avatar
Matt Joiner committed
1402 1403 1404
	for i := 0; i < bootstrappers; i++ {
		for j := 0; j < bootstrapperLeafConns; j++ {
			v := mrand.Intn(leafs)
Aarsh Shah's avatar
Aarsh Shah committed
1405
			connectNoSync(t, ctx, others[i], others[bootstrappers+v])
1406 1407 1408
		}
	}

Matt Joiner's avatar
Matt Joiner committed
1409
	for i := 0; i < bootstrappers; i++ {
Aarsh Shah's avatar
Aarsh Shah committed
1410
		connectNoSync(t, ctx, guy, others[i])
1411 1412
	}

Aarsh Shah's avatar
Aarsh Shah committed
1413 1414 1415
	// give some time for things to settle down
	waitForWellFormedTables(t, dhts, minRTRefreshThreshold, minRTRefreshThreshold, 5*time.Second)

1416 1417 1418 1419 1420 1421
	for _, d := range dhts {
		if err := <-d.RefreshRoutingTable(); err != nil {
			t.Fatal(err)
		}
	}

Matt Joiner's avatar
Matt Joiner committed
1422 1423 1424 1425
	var reachableIds []peer.ID
	for i, d := range dhts {
		lp := len(d.host.Network().Peers())
		if i != 0 && lp > 0 {
1426
			reachableIds = append(reachableIds, d.PeerID())
Matt Joiner's avatar
Matt Joiner committed
1427 1428 1429 1430
		}
	}
	t.Logf("%d reachable ids", len(reachableIds))

1431 1432 1433 1434
	val := "foobar"
	rtval := kb.ConvertKey(val)

	out, err := guy.GetClosestPeers(ctx, val)
Matt Joiner's avatar
Matt Joiner committed
1435
	require.NoError(t, err)
1436 1437 1438 1439 1440 1441

	var outpeers []peer.ID
	for p := range out {
		outpeers = append(outpeers, p)
	}

Jeromy's avatar
Jeromy committed
1442
	sort.Sort(peer.IDSlice(outpeers))
Steven Allen's avatar
Steven Allen committed
1443

1444
	exp := kb.SortClosestPeers(reachableIds, rtval)[:minInt(guy.bucketSize, len(reachableIds))]
Matt Joiner's avatar
Matt Joiner committed
1445
	t.Logf("got %d peers", len(outpeers))
1446
	got := kb.SortClosestPeers(outpeers, rtval)
Jeromy's avatar
Jeromy committed
1447

Matt Joiner's avatar
Matt Joiner committed
1448
	assert.EqualValues(t, exp, got)
1449 1450
}

1451 1452 1453 1454 1455
func TestFindClosestPeers(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	nDHTs := 30
1456
	dhts := setupDHTS(t, ctx, nDHTs)
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
			defer dhts[i].host.Close()
		}
	}()

	t.Logf("connecting %d dhts in a ring", nDHTs)
	for i := 0; i < nDHTs; i++ {
		connect(t, ctx, dhts[i], dhts[(i+1)%len(dhts)])
	}

1469 1470
	querier := dhts[1]
	peers, err := querier.GetClosestPeers(ctx, "foo")
1471 1472 1473 1474 1475 1476 1477 1478 1479
	if err != nil {
		t.Fatal(err)
	}

	var out []peer.ID
	for p := range peers {
		out = append(out, p)
	}

Adin Schmahmann's avatar
Adin Schmahmann committed
1480 1481
	if len(out) < querier.beta {
		t.Fatalf("got wrong number of peers (got %d, expected at least %d)", len(out), querier.beta)
1482 1483
	}
}
1484

1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521
func TestFixLowPeers(t *testing.T) {
	ctx := context.Background()

	dhts := setupDHTS(t, ctx, minRTRefreshThreshold+5)

	defer func() {
		for _, d := range dhts {
			d.Close()
			d.Host().Close()
		}
	}()

	mainD := dhts[0]

	// connect it to everyone else
	for _, d := range dhts[1:] {
		mainD.peerstore.AddAddrs(d.self, d.peerstore.Addrs(d.self), peerstore.TempAddrTTL)
		require.NoError(t, mainD.Host().Connect(ctx, peer.AddrInfo{ID: d.self}))
	}

	waitForWellFormedTables(t, []*IpfsDHT{mainD}, minRTRefreshThreshold, minRTRefreshThreshold+4, 5*time.Second)

	// run a refresh on all of them
	for _, d := range dhts {
		err := <-d.RefreshRoutingTable()
		require.NoError(t, err)
	}

	// now remove peers from RT so threshold gets hit
	for _, d := range dhts[3:] {
		mainD.routingTable.RemovePeer(d.self)
	}

	// but we will still get enough peers in the RT because of fix low Peers
	waitForWellFormedTables(t, []*IpfsDHT{mainD}, minRTRefreshThreshold, minRTRefreshThreshold, 5*time.Second)
}

1522 1523
func TestProvideDisabled(t *testing.T) {
	k := testCaseCids[0]
1524
	kHash := k.Hash()
1525 1526 1527 1528 1529 1530 1531
	for i := 0; i < 3; i++ {
		enabledA := (i & 0x1) > 0
		enabledB := (i & 0x2) > 0
		t.Run(fmt.Sprintf("a=%v/b=%v", enabledA, enabledB), func(t *testing.T) {
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

1532
			var (
1533
				optsA, optsB []Option
1534
			)
Adin Schmahmann's avatar
Adin Schmahmann committed
1535 1536 1537
			optsA = append(optsA, ProtocolPrefix("/provMaybeDisabled"))
			optsB = append(optsB, ProtocolPrefix("/provMaybeDisabled"))

1538
			if !enabledA {
1539
				optsA = append(optsA, DisableProviders())
1540 1541
			}
			if !enabledB {
1542
				optsB = append(optsB, DisableProviders())
1543 1544 1545 1546
			}

			dhtA := setupDHT(ctx, t, false, optsA...)
			dhtB := setupDHT(ctx, t, false, optsB...)
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567

			defer dhtA.Close()
			defer dhtB.Close()
			defer dhtA.host.Close()
			defer dhtB.host.Close()

			connect(t, ctx, dhtA, dhtB)

			err := dhtB.Provide(ctx, k, true)
			if enabledB {
				if err != nil {
					t.Fatal("put should have succeeded on node B", err)
				}
			} else {
				if err != routing.ErrNotSupported {
					t.Fatal("should not have put the value to node B", err)
				}
				_, err = dhtB.FindProviders(ctx, k)
				if err != routing.ErrNotSupported {
					t.Fatal("get should have failed on node B")
				}
1568
				provs := dhtB.ProviderManager.GetProviders(ctx, kHash)
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
				if len(provs) != 0 {
					t.Fatal("node B should not have found local providers")
				}
			}

			provs, err := dhtA.FindProviders(ctx, k)
			if enabledA {
				if len(provs) != 0 {
					t.Fatal("node A should not have found providers")
				}
			} else {
				if err != routing.ErrNotSupported {
					t.Fatal("node A should not have found providers")
				}
			}
1584
			provAddrs := dhtA.ProviderManager.GetProviders(ctx, kHash)
1585 1586 1587 1588 1589 1590 1591
			if len(provAddrs) != 0 {
				t.Fatal("node A should not have found local providers")
			}
		})
	}
}

1592 1593
func TestHandleRemotePeerProtocolChanges(t *testing.T) {
	ctx := context.Background()
1594
	os := []Option{
Adin Schmahmann's avatar
Adin Schmahmann committed
1595
		testPrefix,
1596 1597 1598
		Mode(ModeServer),
		NamespacedValidator("v", blankValidator{}),
		DisableAutoRefresh(),
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
	}

	// start host 1 that speaks dht v1
	dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
	require.NoError(t, err)
	defer dhtA.Close()

	// start host 2 that also speaks dht v1
	dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
	require.NoError(t, err)
	defer dhtB.Close()

	connect(t, ctx, dhtA, dhtB)

	// now assert both have each other in their RT
	require.True(t, waitForWellFormedTables(t, []*IpfsDHT{dhtA, dhtB}, 1, 1, 10*time.Second), "both RT should have one peer each")

	// dhtB becomes a client
	require.NoError(t, dhtB.setMode(modeClient))

	// which means that dhtA should evict it from it's RT
	require.True(t, waitForWellFormedTables(t, []*IpfsDHT{dhtA}, 0, 0, 10*time.Second), "dHTA routing table should have 0 peers")

	// dhtB becomes a server
	require.NoError(t, dhtB.setMode(modeServer))

Aarsh Shah's avatar
Aarsh Shah committed
1625
	// which means dhtA should have it in the RT again because of fixLowPeers
1626 1627 1628
	require.True(t, waitForWellFormedTables(t, []*IpfsDHT{dhtA}, 1, 1, 10*time.Second), "dHTA routing table should have 1 peers")
}

1629
func TestGetSetPluggedProtocol(t *testing.T) {
1630 1631 1632
	t.Run("PutValue/GetValue - same protocol", func(t *testing.T) {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
1633

1634
		os := []Option{
Adin Schmahmann's avatar
Adin Schmahmann committed
1635
			ProtocolPrefix("/esh"),
1636 1637 1638
			Mode(ModeServer),
			NamespacedValidator("v", blankValidator{}),
			DisableAutoRefresh(),
1639
		}
1640

Steven Allen's avatar
Steven Allen committed
1641
		dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
1642 1643 1644
		if err != nil {
			t.Fatal(err)
		}
1645

Steven Allen's avatar
Steven Allen committed
1646
		dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
1647 1648 1649
		if err != nil {
			t.Fatal(err)
		}
1650

1651
		connect(t, ctx, dhtA, dhtB)
1652

1653
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
1654
		defer cancel()
1655 1656 1657
		if err := dhtA.PutValue(ctxT, "/v/cat", []byte("meow")); err != nil {
			t.Fatal(err)
		}
1658

1659 1660 1661 1662
		value, err := dhtB.GetValue(ctxT, "/v/cat")
		if err != nil {
			t.Fatal(err)
		}
1663

1664 1665 1666 1667 1668
		if string(value) != "meow" {
			t.Fatalf("Expected 'meow' got '%s'", string(value))
		}
	})

1669 1670
	t.Run("DHT routing table for peer A won't contain B if A and B don't use same protocol", func(t *testing.T) {
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
1671 1672
		defer cancel()

1673
		dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), []Option{
Adin Schmahmann's avatar
Adin Schmahmann committed
1674
			ProtocolPrefix("/esh"),
1675 1676 1677
			Mode(ModeServer),
			NamespacedValidator("v", blankValidator{}),
			DisableAutoRefresh(),
1678
		}...)
1679 1680 1681 1682
		if err != nil {
			t.Fatal(err)
		}

1683
		dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), []Option{
Adin Schmahmann's avatar
Adin Schmahmann committed
1684
			ProtocolPrefix("/lsr"),
1685 1686 1687
			Mode(ModeServer),
			NamespacedValidator("v", blankValidator{}),
			DisableAutoRefresh(),
1688
		}...)
1689 1690 1691 1692
		if err != nil {
			t.Fatal(err)
		}

1693
		connectNoSync(t, ctx, dhtA, dhtB)
1694

1695 1696 1697 1698 1699 1700
		// We don't expect connection notifications for A to reach B (or vice-versa), given
		// that they've been configured with different protocols - but we'll give them a
		// chance, anyhow.
		time.Sleep(time.Second * 2)

		err = dhtA.PutValue(ctx, "/v/cat", []byte("meow"))
1701 1702
		if err == nil || !strings.Contains(err.Error(), "failed to find any peer in table") {
			t.Fatalf("put should not have been able to find any peers in routing table, err:'%v'", err)
1703 1704
		}

1705 1706 1707
		v, err := dhtB.GetValue(ctx, "/v/cat")
		if v != nil || err != routing.ErrNotFound {
			t.Fatalf("get should have failed from not being able to find the value, err: '%v'", err)
1708
		}
1709
	})
1710
}
1711 1712 1713 1714 1715

func TestPing(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ds := setupDHTS(t, ctx, 2)
1716
	ds[0].Host().Peerstore().AddAddrs(ds[1].PeerID(), ds[1].Host().Addrs(), peerstore.AddressTTL)
1717 1718 1719 1720 1721 1722 1723 1724
	assert.NoError(t, ds[0].Ping(context.Background(), ds[1].PeerID()))
}

func TestClientModeAtInit(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	pinger := setupDHT(ctx, t, false)
	client := setupDHT(ctx, t, true)
1725
	pinger.Host().Peerstore().AddAddrs(client.PeerID(), client.Host().Addrs(), peerstore.AddressTTL)
1726
	err := pinger.Ping(context.Background(), client.PeerID())
Steven Allen's avatar
Steven Allen committed
1727
	assert.True(t, errors.Is(err, multistream.ErrNotSupported))
1728
}
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752

func TestModeChange(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	clientOnly := setupDHT(ctx, t, true)
	clientToServer := setupDHT(ctx, t, true)
	clientOnly.Host().Peerstore().AddAddrs(clientToServer.PeerID(), clientToServer.Host().Addrs(), peerstore.AddressTTL)
	err := clientOnly.Ping(ctx, clientToServer.PeerID())
	assert.True(t, errors.Is(err, multistream.ErrNotSupported))
	err = clientToServer.setMode(modeServer)
	assert.Nil(t, err)
	err = clientOnly.Ping(ctx, clientToServer.PeerID())
	assert.Nil(t, err)
	err = clientToServer.setMode(modeClient)
	assert.Nil(t, err)
	err = clientOnly.Ping(ctx, clientToServer.PeerID())
	assert.NotNil(t, err)
}

func TestDynamicModeSwitching(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

1753 1754
	prober := setupDHT(ctx, t, true)               // our test harness
	node := setupDHT(ctx, t, true, Mode(ModeAuto)) // the node under test
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
	prober.Host().Peerstore().AddAddrs(node.PeerID(), node.Host().Addrs(), peerstore.AddressTTL)
	if _, err := prober.Host().Network().DialPeer(ctx, node.PeerID()); err != nil {
		t.Fatal(err)
	}

	emitter, err := node.host.EventBus().Emitter(new(event.EvtLocalReachabilityChanged))
	if err != nil {
		t.Fatal(err)
	}

	assertDHTClient := func() {
		err = prober.Ping(ctx, node.PeerID())
		assert.True(t, errors.Is(err, multistream.ErrNotSupported))
		if l := len(prober.RoutingTable().ListPeers()); l != 0 {
			t.Errorf("expected routing table length to be 0; instead is %d", l)
		}
	}

	assertDHTServer := func() {
		err = prober.Ping(ctx, node.PeerID())
		assert.Nil(t, err)
Aarsh Shah's avatar
Aarsh Shah committed
1776 1777
		// the node should be in the RT for the prober
		// because the prober will call fixLowPeers when the node updates it's protocols
1778 1779 1780 1781 1782
		if l := len(prober.RoutingTable().ListPeers()); l != 1 {
			t.Errorf("expected routing table length to be 1; instead is %d", l)
		}
	}

Steven Allen's avatar
Steven Allen committed
1783 1784 1785 1786
	err = emitter.Emit(event.EvtLocalReachabilityChanged{Reachability: network.ReachabilityPrivate})
	if err != nil {
		t.Fatal(err)
	}
1787 1788 1789 1790
	time.Sleep(500 * time.Millisecond)

	assertDHTClient()

Steven Allen's avatar
Steven Allen committed
1791 1792 1793 1794
	err = emitter.Emit(event.EvtLocalReachabilityChanged{Reachability: network.ReachabilityPublic})
	if err != nil {
		t.Fatal(err)
	}
1795 1796 1797 1798
	time.Sleep(500 * time.Millisecond)

	assertDHTServer()

Steven Allen's avatar
Steven Allen committed
1799 1800 1801 1802
	err = emitter.Emit(event.EvtLocalReachabilityChanged{Reachability: network.ReachabilityUnknown})
	if err != nil {
		t.Fatal(err)
	}
1803 1804 1805 1806
	time.Sleep(500 * time.Millisecond)

	assertDHTClient()
}
Adin Schmahmann's avatar
Adin Schmahmann committed
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883

func TestProtocolUpgrade(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	os := []Option{
		Mode(ModeServer),
		NamespacedValidator("v", blankValidator{}),
		DisableAutoRefresh(),
	}

	// This test verifies that we can have a node serving both old and new DHTs that will respond as a server to the old
	// DHT, but only act as a client of the new DHT. In it's capacity as a server it should also only tell queriers
	// about other DHT servers in the new DHT.

	dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
		append([]Option{testPrefix}, os...)...)
	if err != nil {
		t.Fatal(err)
	}

	dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
		append([]Option{testPrefix}, os...)...)
	if err != nil {
		t.Fatal(err)
	}

	dhtC, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
		append([]Option{testPrefix, customProtocols(kad1)}, os...)...)
	if err != nil {
		t.Fatal(err)
	}

	connect(t, ctx, dhtA, dhtB)
	connectNoSync(t, ctx, dhtA, dhtC)
	wait(t, ctx, dhtC, dhtA)

	if sz := dhtA.RoutingTable().Size(); sz != 1 {
		t.Fatalf("Expected routing table to be of size %d got %d", 1, sz)
	}

	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
	if err := dhtB.PutValue(ctxT, "/v/bat", []byte("screech")); err != nil {
		t.Fatal(err)
	}

	value, err := dhtC.GetValue(ctxT, "/v/bat")
	if err != nil {
		t.Fatal(err)
	}

	if string(value) != "screech" {
		t.Fatalf("Expected 'screech' got '%s'", string(value))
	}

	if err := dhtC.PutValue(ctxT, "/v/cat", []byte("meow")); err != nil {
		t.Fatal(err)
	}

	value, err = dhtB.GetValue(ctxT, "/v/cat")
	if err != nil {
		t.Fatal(err)
	}

	if string(value) != "meow" {
		t.Fatalf("Expected 'meow' got '%s'", string(value))
	}

	// Add record into local DHT only
	rec := record.MakePutRecord("/v/crow", []byte("caw"))
	rec.TimeReceived = u.FormatRFC3339(time.Now())
	err = dhtC.putLocal(string(rec.Key), rec)
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
1884
	_, err = dhtB.GetValue(ctxT, "/v/crow")
Adin Schmahmann's avatar
Adin Schmahmann committed
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
	switch err {
	case nil:
		t.Fatalf("should not have been able to find value for %s", "/v/crow")
	case routing.ErrNotFound:
	default:
		t.Fatal(err)
	}

	// Add record into local DHT only
	rec = record.MakePutRecord("/v/bee", []byte("buzz"))
	rec.TimeReceived = u.FormatRFC3339(time.Now())
	err = dhtB.putLocal(string(rec.Key), rec)
	if err != nil {
		t.Fatal(err)
	}

	value, err = dhtC.GetValue(ctxT, "/v/bee")
	if err != nil {
		t.Fatal(err)
	}

	if string(value) != "buzz" {
		t.Fatalf("Expected 'buzz' got '%s'", string(value))
	}
}