dht_test.go 34 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
	"errors"
7
	"fmt"
8
	"math/rand"
9
	"sort"
10
	"strings"
11
	"sync"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12
	"testing"
13
	"time"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
14

15 16 17
	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/libp2p/go-libp2p-core/peerstore"
	"github.com/libp2p/go-libp2p-core/routing"
18
	"github.com/multiformats/go-multistream"
19 20 21 22 23 24

	"golang.org/x/xerrors"

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

25 26
	opts "github.com/libp2p/go-libp2p-kad-dht/opts"
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
27

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

39
var testCaseCids []cid.Cid
40 41 42 43

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

		mhv := u.Hash([]byte(v))
		testCaseCids = append(testCaseCids, cid.NewCidV0(mhv))
47 48 49
	}
}

50 51 52 53 54 55 56 57 58 59
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 {
60
		if bytes.Equal(b, []byte("newer")) {
61
			index = i
62
		} else if bytes.Equal(b, []byte("valid")) {
63 64 65 66 67 68 69 70 71 72 73
			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 {
74
	if bytes.Equal(b, []byte("expired")) {
75 76 77 78 79
		return errors.New("expired")
	}
	return nil
}

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
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
}

110
func setupDHT(ctx context.Context, t *testing.T, client bool) *IpfsDHT {
111 112
	d, err := New(
		ctx,
Steven Allen's avatar
Steven Allen committed
113
		bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
114 115 116 117 118
		opts.Client(client),
		opts.NamespacedValidator("v", blankValidator{}),
	)
	if err != nil {
		t.Fatal(err)
119
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
120 121 122
	return d
}

123
func setupDHTS(t *testing.T, ctx context.Context, n int) []*IpfsDHT {
124
	addrs := make([]ma.Multiaddr, n)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125
	dhts := make([]*IpfsDHT, n)
126 127
	peers := make([]peer.ID, n)

128 129 130
	sanityAddrsMap := make(map[string]struct{})
	sanityPeersMap := make(map[string]struct{})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
131
	for i := 0; i < n; i++ {
132
		dhts[i] = setupDHT(ctx, t, false)
133 134
		peers[i] = dhts[i].PeerID()
		addrs[i] = dhts[i].host.Addrs()[0]
135 136

		if _, lol := sanityAddrsMap[addrs[i].String()]; lol {
Jakub Sztandera's avatar
Jakub Sztandera committed
137
			t.Fatal("While setting up DHTs address got duplicated.")
138 139 140 141
		} else {
			sanityAddrsMap[addrs[i].String()] = struct{}{}
		}
		if _, lol := sanityPeersMap[peers[i].String()]; lol {
Jakub Sztandera's avatar
Jakub Sztandera committed
142
			t.Fatal("While setting up DHTs peerid got duplicated.")
143 144 145
		} else {
			sanityPeersMap[peers[i].String()] = struct{}{}
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146 147
	}

148
	return dhts
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
149 150
}

151
func connectNoSync(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
152 153
	t.Helper()

154
	idB := b.self
155
	addrB := b.peerstore.Addrs(idB)
156 157
	if len(addrB) == 0 {
		t.Fatal("peers setup incorrectly: no local address")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158
	}
159

160 161
	a.peerstore.AddAddrs(idB, addrB, peerstore.TempAddrTTL)
	pi := peer.AddrInfo{ID: idB}
Jeromy's avatar
Jeromy committed
162
	if err := a.host.Connect(ctx, pi); err != nil {
163
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164
	}
165 166
}

167 168
func wait(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
	t.Helper()
169

170 171
	// loop until connection notification has been received.
	// under high load, this may not happen as immediately as we would like.
172
	for a.routingTable.Find(b.self) == "" {
173 174 175 176 177
		select {
		case <-ctx.Done():
			t.Fatal(ctx.Err())
		case <-time.After(time.Millisecond * 5):
		}
178
	}
179
}
180

181 182 183 184 185
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
186 187
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188
func bootstrap(t *testing.T, ctx context.Context, dhts []*IpfsDHT) {
189

190
	ctx, cancel := context.WithCancel(ctx)
Steven Allen's avatar
Steven Allen committed
191 192
	defer cancel()

Matt Joiner's avatar
Matt Joiner committed
193
	logger.Debugf("Bootstrapping DHTs...")
194 195 196 197 198 199

	// 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

200
	cfg := DefaultBootstrapConfig
201 202
	cfg.Queries = 3

203 204 205
	start := rand.Intn(len(dhts)) // randomize to decrease bias.
	for i := range dhts {
		dht := dhts[(start+i)%len(dhts)]
206
		dht.runBootstrap(ctx, cfg)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207 208 209
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
210
func TestValueGetSet(t *testing.T) {
211 212
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
213

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

Steven Allen's avatar
Steven Allen committed
216 217 218 219 220
	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
221

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

Steven Allen's avatar
Steven Allen committed
224
	t.Log("adding value on: ", dhts[0].self)
Jeromy's avatar
Jeromy committed
225 226
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
Steven Allen's avatar
Steven Allen committed
227
	err := dhts[0].PutValue(ctxT, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
228 229 230 231
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
232
	t.Log("requesting value on dhts: ", dhts[1].self)
Jeromy's avatar
Jeromy committed
233 234
	ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
	defer cancel()
Steven Allen's avatar
Steven Allen committed
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 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

	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))
	if vala != nil {
		t.Fatalf("offline get should have failed, got %s", string(vala))
	}
	if err != routing.ErrNotFound {
		t.Fatalf("offline get should have failed with ErrNotFound, got: %s", err)
	}

	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")
276 277 278 279
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
280 281
	if string(val) != "world" {
		t.Fatalf("Expected 'world' got '%s'", string(val))
282
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283 284
}

285 286 287 288 289 290 291 292 293 294 295 296
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()

297
	dhtA.Validator.(record.NamespacedValidator)["v"] = testValidator{}
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
	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)
}

Łukasz Magiera's avatar
Łukasz Magiera committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
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()
365
	valCh, err := dhtA.SearchValue(ctxT, "/v/hello", Quorum(-1))
366 367 368
	if err != nil {
		t.Fatal(err)
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393

	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())
	}
}

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
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))
	}

432
	sort.Slice(vals, func(i, j int) bool { return string(vals[i].Val) < string(vals[j].Val) })
433 434 435 436 437 438 439 440 441

	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))
	}
}

442 443 444 445 446 447 448 449 450 451 452 453 454
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{}
455
	dhtB.Validator.(record.NamespacedValidator)["v"] = testValidator{}
456 457 458 459

	connect(t, ctx, dhtA, dhtB)

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

462 463 464 465
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		err := dhtA.PutValue(ctxT, "/v/hello", []byte(val))
		if err != nil {
466
			t.Error(err)
467 468 469 470 471 472
		}

		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
473
			t.Errorf("Set/Get %v: Expected '%v' error but got '%v'", val, experr, err)
474 475
		} else if err == nil && string(valb) != exp {
			t.Errorf("Expected '%v' got '%s'", exp, string(valb))
476 477 478 479 480 481 482 483 484 485 486 487 488
		}
	}

	// 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)
}

489
func TestInvalidMessageSenderTracking(t *testing.T) {
Steven Allen's avatar
Steven Allen committed
490 491 492
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

493
	dht := setupDHT(ctx, t, false)
Steven Allen's avatar
Steven Allen committed
494 495
	defer dht.Close()

496
	foo := peer.ID("asdasd")
Steven Allen's avatar
Steven Allen committed
497
	_, err := dht.messageSenderForPeer(ctx, foo)
498 499 500 501 502
	if err == nil {
		t.Fatal("that shouldnt have succeeded")
	}

	dht.smlk.Lock()
Steven Allen's avatar
Steven Allen committed
503 504 505 506
	mscnt := len(dht.strmap)
	dht.smlk.Unlock()

	if mscnt > 0 {
507 508 509 510
		t.Fatal("should have no message senders in map")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
511 512
func TestProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
513 514
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
515

516
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
517 518
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
519
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
520
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
521 522 523
		}
	}()

524 525 526
	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
527

528
	for _, k := range testCaseCids {
Matt Joiner's avatar
Matt Joiner committed
529
		logger.Debugf("announcing provider for %s", k)
Jeromy's avatar
Jeromy committed
530
		if err := dhts[3].Provide(ctx, k, true); err != nil {
531 532
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
533 534
	}

535 536 537 538
	// what is this timeout for? was 60ms before.
	time.Sleep(time.Millisecond * 6)

	n := 0
539
	for _, c := range testCaseCids {
540 541
		n = (n + 1) % 3

Matt Joiner's avatar
Matt Joiner committed
542
		logger.Debugf("getting providers for %s from %d", c, n)
Jeromy's avatar
Jeromy committed
543 544
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
545
		provchan := dhts[n].FindProvidersAsync(ctxT, c, 1)
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

		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
561 562
func TestLocalProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
563 564
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Jeromy's avatar
Jeromy committed
565

566
	dhts := setupDHTS(t, ctx, 4)
Jeromy's avatar
Jeromy committed
567 568 569 570 571 572 573 574 575 576 577 578
	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
579
		logger.Debugf("announcing provider for %s", k)
Jeromy's avatar
Jeromy committed
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
		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++ {
			provs := dhts[i].providers.GetProviders(ctx, c)
			if len(provs) > 0 {
				t.Fatal("shouldnt know this")
			}
		}
	}
}

597 598 599 600 601 602 603 604 605 606
// 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 {
607
				//t.Logf("routing table for %s only has %d peers (should have >%d)", dht.self, rtlen, minPeers)
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
				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
624
			logger.Debugf("did not reach well-formed routing tables by %s", timeout)
625 626 627 628 629 630 631 632 633 634 635
			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.
636
	fmt.Printf("checking routing table of %d\n", len(dhts))
637 638 639 640 641 642 643
	for _, dht := range dhts {
		fmt.Printf("checking routing table of %s\n", dht.self)
		dht.routingTable.Print()
		fmt.Println("")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
644
func TestBootstrap(t *testing.T) {
645 646 647 648
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
649 650
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
651

652
	nDHTs := 30
653
	dhts := setupDHTS(t, ctx, nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
654 655 656
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
657
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
658 659 660 661 662 663 664 665
		}
	}()

	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)])
	}

666
	<-time.After(100 * time.Millisecond)
667 668 669 670
	// bootstrap a few times until we get good tables.
	stop := make(chan struct{})
	go func() {
		for {
671
			t.Logf("bootstrapping them so they find each other %d", nDHTs)
Jeromy's avatar
Jeromy committed
672 673
			ctxT, cancel := context.WithTimeout(ctx, 5*time.Second)
			defer cancel()
674 675 676 677 678 679 680 681 682 683 684
			bootstrap(t, ctxT, dhts)

			select {
			case <-time.After(50 * time.Millisecond):
				continue // being explicit
			case <-stop:
				return
			}
		}
	}()

685
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
686
	close(stop)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
687

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
688 689
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
690 691 692 693 694
		printRoutingTables(dhts)
	}
}

func TestPeriodicBootstrap(t *testing.T) {
695 696 697
	if ci.IsRunning() {
		t.Skip("skipping on CI. highly timing dependent")
	}
698 699 700 701
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
702 703
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
704 705

	nDHTs := 30
706
	dhts := setupDHTS(t, ctx, nDHTs)
707 708 709 710 711 712 713
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
			defer dhts[i].host.Close()
		}
	}()

714
	cfg := DefaultBootstrapConfig
715 716
	cfg.Queries = 5

717
	t.Logf("dhts are not connected. %d", nDHTs)
718 719 720 721 722 723 724 725 726 727 728
	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)])
	}

729
	t.Logf("DHTs are now connected to 1-2 others. %d", nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
730
	for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
731
		rtlen := dht.routingTable.Size()
732 733
		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
734
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
735
	}
736

737 738 739 740
	if u.Debug {
		printRoutingTables(dhts)
	}

741
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
Matt Joiner's avatar
Matt Joiner committed
742 743
	for _, dht := range dhts {
		go dht.BootstrapOnce(ctx, cfg)
744
	}
745 746 747

	// 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.
748
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
749 750 751

	if u.Debug {
		printRoutingTables(dhts)
752
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
753 754
}

755 756
func TestProvidesMany(t *testing.T) {
	t.Skip("this test doesn't work")
Steven Allen's avatar
Steven Allen committed
757 758
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
759 760

	nDHTs := 40
761
	dhts := setupDHTS(t, ctx, nDHTs)
762 763 764
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
765
			defer dhts[i].host.Close()
766 767 768 769 770 771 772 773
		}
	}()

	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)])
	}

774
	<-time.After(100 * time.Millisecond)
775
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
Jeromy's avatar
Jeromy committed
776 777
	ctxT, cancel := context.WithTimeout(ctx, 20*time.Second)
	defer cancel()
778 779
	bootstrap(t, ctxT, dhts)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
780 781 782 783 784 785 786 787
	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("")
		}
788
	}
789

790
	providers := make(map[cid.Cid]peer.ID)
791

792
	d := 0
793
	for _, c := range testCaseCids {
794 795
		d = (d + 1) % len(dhts)
		dht := dhts[d]
796
		providers[c] = dht.self
797

798
		t.Logf("announcing provider for %s", c)
Jeromy's avatar
Jeromy committed
799
		if err := dht.Provide(ctx, c, true); err != nil {
800 801
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
802 803
	}

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

807 808
	errchan := make(chan error)

Jeromy's avatar
Jeromy committed
809 810
	ctxT, cancel = context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
811 812

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

816
		expected := providers[k]
817

818 819 820
		provchan := dht.FindProvidersAsync(ctxT, k, 1)
		select {
		case prov := <-provchan:
821 822
			actual := prov.ID
			if actual == "" {
823
				errchan <- fmt.Errorf("Got back nil provider (%s at %s)", k, dht.self)
824 825 826
			} else if actual != expected {
				errchan <- fmt.Errorf("Got back wrong provider (%s != %s) (%s at %s)",
					expected, actual, k, dht.self)
827 828 829
			}
		case <-ctxT.Done():
			errchan <- fmt.Errorf("Did not get a provider back (%s at %s)", k, dht.self)
Jeromy's avatar
Jeromy committed
830
		}
831 832
	}

833
	for _, c := range testCaseCids {
834 835
		// everyone should be able to find it...
		for _, dht := range dhts {
Matt Joiner's avatar
Matt Joiner committed
836
			logger.Debugf("getting providers for %s at %s", c, dht.self)
837
			wg.Add(1)
838
			go getProvider(dht, c)
839
		}
840 841 842 843 844 845 846 847 848 849
	}

	// 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
850 851 852
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
853
func TestProvidesAsync(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
854
	// t.Skip("skipping test to debug another")
855 856 857
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
858

Steven Allen's avatar
Steven Allen committed
859 860
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
861

862
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
863 864
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
865
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
866
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
867 868 869
		}
	}()

870 871 872
	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
873

Jeromy's avatar
Jeromy committed
874
	err := dhts[3].Provide(ctx, testCaseCids[0], true)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
875 876 877 878 879 880
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 60)

Jeromy's avatar
Jeromy committed
881 882
	ctxT, cancel := context.WithTimeout(ctx, time.Millisecond*300)
	defer cancel()
883
	provs := dhts[0].FindProvidersAsync(ctxT, testCaseCids[0], 5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
884
	select {
Jeromy's avatar
Jeromy committed
885 886 887 888
	case p, ok := <-provs:
		if !ok {
			t.Fatal("Provider channel was closed...")
		}
889
		if p.ID == "" {
Jeromy's avatar
Jeromy committed
890 891
			t.Fatal("Got back nil provider!")
		}
892
		if p.ID != dhts[3].self {
893
			t.Fatalf("got a provider, but not the right one. %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
894
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
895
	case <-ctxT.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
896 897 898 899
		t.Fatal("Didnt get back providers")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
900
func TestLayeredGet(t *testing.T) {
901 902
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
903

904
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
905 906
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
907
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
908
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
909 910 911
		}
	}()

912 913
	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
914
	connect(t, ctx, dhts[2], dhts[3])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
915

916
	err := dhts[3].PutValue(ctx, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
917 918 919 920
	if err != nil {
		t.Fatal(err)
	}

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

Jeromy's avatar
Jeromy committed
923 924
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
925 926 927
	val, err := dhts[0].GetValue(ctxT, "/v/hello")
	if err != nil {
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
928
	}
929 930 931

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

935 936 937 938 939 940 941 942
func TestUnfindablePeer(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

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

943
	dhts := setupDHTS(t, ctx, 4)
944 945 946
	defer func() {
		for i := 0; i < 4; i++ {
			dhts[i].Close()
947
			dhts[i].Host().Close()
948 949 950 951 952 953 954 955
		}
	}()

	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.
956 957
	dhts[1].host.Peerstore().ClearAddrs(dhts[2].PeerID())
	dhts[1].host.Peerstore().AddAddr(dhts[2].PeerID(), dhts[0].Host().Addrs()[0], time.Minute)
958 959 960

	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
961
	_, err := dhts[0].FindPeer(ctxT, dhts[3].PeerID())
962 963 964 965 966 967 968 969
	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
970
func TestFindPeer(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
971
	// t.Skip("skipping test to debug another")
972 973 974
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
975

Steven Allen's avatar
Steven Allen committed
976 977
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
978

979
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
980 981
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
982
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
983
			dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
984 985 986
		}
	}()

987 988 989
	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
990

Jeromy's avatar
Jeromy committed
991 992
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
993
	p, err := dhts[0].FindPeer(ctxT, dhts[2].PeerID())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
994 995 996 997
	if err != nil {
		t.Fatal(err)
	}

998
	if p.ID == "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
999 1000 1001
		t.Fatal("Failed to find peer.")
	}

1002
	if p.ID != dhts[2].PeerID() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1003 1004 1005
		t.Fatal("Didnt find expected peer.")
	}
}
1006

1007
func TestFindPeersConnectedToPeer(t *testing.T) {
1008 1009
	t.Skip("not quite correct (see note)")

1010 1011 1012 1013
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
1014 1015
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
1016

1017
	dhts := setupDHTS(t, ctx, 4)
1018 1019 1020
	defer func() {
		for i := 0; i < 4; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1021
			dhts[i].host.Close()
1022 1023 1024 1025 1026
		}
	}()

	// topology:
	// 0-1, 1-2, 1-3, 2-3
1027 1028 1029 1030
	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
	connect(t, ctx, dhts[1], dhts[3])
	connect(t, ctx, dhts[2], dhts[3])
1031 1032 1033 1034 1035 1036

	// fmt.Println("0 is", peers[0])
	// fmt.Println("1 is", peers[1])
	// fmt.Println("2 is", peers[2])
	// fmt.Println("3 is", peers[3])

Jeromy's avatar
Jeromy committed
1037 1038
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
1039
	pchan, err := dhts[0].FindPeersConnectedToPeer(ctxT, dhts[2].PeerID())
1040 1041 1042 1043
	if err != nil {
		t.Fatal(err)
	}

1044
	// shouldFind := []peer.ID{peers[1], peers[3]}
1045
	var found []*peer.AddrInfo
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
	for nextp := range pchan {
		found = append(found, nextp)
	}

	// fmt.Printf("querying 0 (%s) FindPeersConnectedToPeer 2 (%s)\n", peers[0], peers[2])
	// fmt.Println("should find 1, 3", shouldFind)
	// fmt.Println("found", found)

	// testPeerListsMatch(t, shouldFind, found)

Matt Joiner's avatar
Matt Joiner committed
1056
	logger.Warning("TestFindPeersConnectedToPeer is not quite correct")
1057 1058 1059 1060 1061
	if len(found) == 0 {
		t.Fatal("didn't find any peers.")
	}
}

1062
func TestConnectCollision(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1063
	// t.Skip("skipping test to debug another")
1064 1065 1066
	if testing.Short() {
		t.SkipNow()
	}
1067 1068 1069
	if travisci.IsRunning() {
		t.Skip("Skipping on Travis-CI.")
	}
1070

1071
	runTimes := 10
1072

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

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

1078 1079
		dhtA := setupDHT(ctx, t, false)
		dhtB := setupDHT(ctx, t, false)
1080

1081 1082
		addrA := dhtA.peerstore.Addrs(dhtA.self)[0]
		addrB := dhtB.peerstore.Addrs(dhtB.self)[0]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1083

1084 1085
		peerA := dhtA.self
		peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1086

1087
		errs := make(chan error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1088
		go func() {
1089 1090
			dhtA.peerstore.AddAddr(peerB, addrB, peerstore.TempAddrTTL)
			pi := peer.AddrInfo{ID: peerB}
Jeromy's avatar
Jeromy committed
1091
			err := dhtA.host.Connect(ctx, pi)
1092
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1093 1094
		}()
		go func() {
1095 1096
			dhtB.peerstore.AddAddr(peerA, addrA, peerstore.TempAddrTTL)
			pi := peer.AddrInfo{ID: peerA}
Jeromy's avatar
Jeromy committed
1097
			err := dhtB.host.Connect(ctx, pi)
1098
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1099 1100
		}()

1101
		timeout := time.After(5 * time.Second)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1102
		select {
1103 1104 1105 1106
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1107 1108 1109 1110
		case <-timeout:
			t.Fatal("Timeout received!")
		}
		select {
1111 1112 1113 1114
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1115 1116 1117 1118
		case <-timeout:
			t.Fatal("Timeout received!")
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1119 1120
		dhtA.Close()
		dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1121 1122
		dhtA.host.Close()
		dhtB.host.Close()
Steven Allen's avatar
Steven Allen committed
1123
		cancel()
Jeromy's avatar
Jeromy committed
1124
	}
1125
}
1126 1127 1128 1129 1130

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

1131
	d := setupDHT(ctx, t, false)
1132 1133 1134 1135 1136 1137

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

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
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()
			putRecord(v)
		}(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))
	}
}

1184 1185 1186 1187 1188 1189 1190 1191 1192
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)

1193
	c := testCaseCids[0]
1194
	p := peer.ID("TestPeer")
1195 1196
	a.providers.AddProvider(ctx, c, p)
	time.Sleep(time.Millisecond * 5) // just in case...
1197

1198
	provs, err := b.FindProviders(ctx, c)
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
	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
1210 1211 1212 1213 1214 1215 1216 1217 1218
	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) {
1219
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
Steven Allen's avatar
Steven Allen committed
1220 1221 1222 1223 1224 1225
	defer cancel()

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

1226 1227
	connectNoSync(t, ctx, b, a)
	connectNoSync(t, ctx, c, a)
Steven Allen's avatar
Steven Allen committed
1228 1229

	// Can't use `connect` because b and c are only clients.
1230 1231
	wait(t, ctx, b, a)
	wait(t, ctx, c, a)
Steven Allen's avatar
Steven Allen committed
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244

	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)
	}
1245
}
1246

Matt Joiner's avatar
Matt Joiner committed
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
func minInt(a, b int) int {
	if a < b {
		return a
	} else {
		return b
	}
}

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

1259
func TestFindPeerQuery(t *testing.T) {
Matt Joiner's avatar
Matt Joiner committed
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
	if testing.Short() {
		t.Skip("skipping test in short mode")
	}
	if curFileLimit() < 1024 {
		t.Skip("insufficient file descriptors available")
	}
	testFindPeerQuery(t, 20, 80, 16)
}

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
) {
1274 1275 1276
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

1277
	dhts := setupDHTS(t, ctx, 1+bootstrappers+leafs)
1278
	defer func() {
Matt Joiner's avatar
Matt Joiner committed
1279 1280 1281
		for _, d := range dhts {
			d.Close()
			d.host.Close()
1282 1283 1284
		}
	}()

Jeromy's avatar
Jeromy committed
1285
	mrand := rand.New(rand.NewSource(42))
1286 1287
	guy := dhts[0]
	others := dhts[1:]
Matt Joiner's avatar
Matt Joiner committed
1288 1289 1290 1291
	for i := 0; i < bootstrappers; i++ {
		for j := 0; j < bootstrapperLeafConns; j++ {
			v := mrand.Intn(leafs)
			connect(t, ctx, others[i], others[bootstrappers+v])
1292 1293 1294
		}
	}

Matt Joiner's avatar
Matt Joiner committed
1295
	for i := 0; i < bootstrappers; i++ {
1296 1297 1298
		connect(t, ctx, guy, others[i])
	}

Matt Joiner's avatar
Matt Joiner committed
1299 1300 1301 1302 1303
	var reachableIds []peer.ID
	for i, d := range dhts {
		lp := len(d.host.Network().Peers())
		//t.Log(i, lp)
		if i != 0 && lp > 0 {
1304
			reachableIds = append(reachableIds, d.PeerID())
Matt Joiner's avatar
Matt Joiner committed
1305 1306 1307 1308
		}
	}
	t.Logf("%d reachable ids", len(reachableIds))

1309 1310 1311
	val := "foobar"
	rtval := kb.ConvertKey(val)

Jeromy's avatar
Jeromy committed
1312
	rtablePeers := guy.routingTable.NearestPeers(rtval, AlphaValue)
Matt Joiner's avatar
Matt Joiner committed
1313
	assert.Len(t, rtablePeers, minInt(bootstrappers, AlphaValue))
1314

Matt Joiner's avatar
Matt Joiner committed
1315
	assert.Len(t, guy.host.Network().Peers(), bootstrappers)
1316 1317

	out, err := guy.GetClosestPeers(ctx, val)
Matt Joiner's avatar
Matt Joiner committed
1318
	require.NoError(t, err)
1319 1320 1321 1322 1323 1324

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

Jeromy's avatar
Jeromy committed
1325
	sort.Sort(peer.IDSlice(outpeers))
Steven Allen's avatar
Steven Allen committed
1326

Matt Joiner's avatar
Matt Joiner committed
1327 1328
	exp := kb.SortClosestPeers(reachableIds, rtval)[:minInt(KValue, len(reachableIds))]
	t.Logf("got %d peers", len(outpeers))
1329
	got := kb.SortClosestPeers(outpeers, rtval)
Jeromy's avatar
Jeromy committed
1330

Matt Joiner's avatar
Matt Joiner committed
1331
	assert.EqualValues(t, exp, got)
1332 1333
}

1334 1335 1336 1337 1338
func TestFindClosestPeers(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	nDHTs := 30
1339
	dhts := setupDHTS(t, ctx, nDHTs)
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
	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)])
	}

	peers, err := dhts[1].GetClosestPeers(ctx, "foo")
	if err != nil {
		t.Fatal(err)
	}

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

	if len(out) != KValue {
		t.Fatalf("got wrong number of peers (got %d, expected %d)", len(out), KValue)
	}
}
1366 1367

func TestGetSetPluggedProtocol(t *testing.T) {
1368 1369 1370
	t.Run("PutValue/GetValue - same protocol", func(t *testing.T) {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
1371

1372 1373 1374 1375 1376
		os := []opts.Option{
			opts.Protocols("/esh/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
		}
1377

Steven Allen's avatar
Steven Allen committed
1378
		dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
1379 1380 1381
		if err != nil {
			t.Fatal(err)
		}
1382

Steven Allen's avatar
Steven Allen committed
1383
		dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
1384 1385 1386
		if err != nil {
			t.Fatal(err)
		}
1387

1388
		connect(t, ctx, dhtA, dhtB)
1389

1390
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
1391
		defer cancel()
1392 1393 1394
		if err := dhtA.PutValue(ctxT, "/v/cat", []byte("meow")); err != nil {
			t.Fatal(err)
		}
1395

1396 1397 1398 1399
		value, err := dhtB.GetValue(ctxT, "/v/cat")
		if err != nil {
			t.Fatal(err)
		}
1400

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

1406 1407
	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)
1408 1409
		defer cancel()

Steven Allen's avatar
Steven Allen committed
1410
		dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), []opts.Option{
1411 1412 1413
			opts.Protocols("/esh/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
1414
		}...)
1415 1416 1417 1418
		if err != nil {
			t.Fatal(err)
		}

Steven Allen's avatar
Steven Allen committed
1419
		dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), []opts.Option{
1420 1421 1422
			opts.Protocols("/lsr/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
1423
		}...)
1424 1425 1426 1427
		if err != nil {
			t.Fatal(err)
		}

1428
		connectNoSync(t, ctx, dhtA, dhtB)
1429

1430 1431 1432 1433 1434 1435 1436
		// 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"))
		if err == nil || !strings.Contains(err.Error(), "failed to find any peer in table") {
1437
			t.Fatalf("put should not have been able to find any peers in routing table, err:'%v'", err)
1438 1439
		}

1440 1441
		_, err = dhtB.GetValue(ctx, "/v/cat")
		if err == nil || !strings.Contains(err.Error(), "failed to find any peer in table") {
1442
			t.Fatalf("get should not have been able to find any peers in routing table, err:'%v'", err)
1443
		}
1444
	})
1445
}
1446 1447 1448 1449 1450

func TestPing(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ds := setupDHTS(t, ctx, 2)
1451
	ds[0].Host().Peerstore().AddAddrs(ds[1].PeerID(), ds[1].Host().Addrs(), peerstore.AddressTTL)
1452 1453 1454 1455 1456 1457 1458 1459
	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)
1460
	pinger.Host().Peerstore().AddAddrs(client.PeerID(), client.Host().Addrs(), peerstore.AddressTTL)
1461 1462 1463
	err := pinger.Ping(context.Background(), client.PeerID())
	assert.True(t, xerrors.Is(err, multistream.ErrNotSupported))
}