dht_test.go 31.5 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
	opts "github.com/libp2p/go-libp2p-kad-dht/opts"
16 17
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"

18
	cid "github.com/ipfs/go-cid"
19
	u "github.com/ipfs/go-ipfs-util"
20
	kb "github.com/libp2p/go-libp2p-kbucket"
21 22
	peer "github.com/libp2p/go-libp2p-peer"
	pstore "github.com/libp2p/go-libp2p-peerstore"
George Antoniadis's avatar
George Antoniadis committed
23
	record "github.com/libp2p/go-libp2p-record"
24
	routing "github.com/libp2p/go-libp2p-routing"
Steven Allen's avatar
Steven Allen committed
25
	swarmt "github.com/libp2p/go-libp2p-swarm/testing"
Jeromy's avatar
Jeromy committed
26
	bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
George Antoniadis's avatar
George Antoniadis committed
27 28
	ci "github.com/libp2p/go-testutil/ci"
	travisci "github.com/libp2p/go-testutil/ci/travis"
29
	ma "github.com/multiformats/go-multiaddr"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30 31
)

32
var testCaseValues = map[string][]byte{}
33
var testCaseCids []cid.Cid
34 35 36 37

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

		mhv := u.Hash([]byte(v))
		testCaseCids = append(testCaseCids, cid.NewCidV0(mhv))
41 42 43
	}
}

44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
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 {
		if bytes.Compare(b, []byte("newer")) == 0 {
			index = i
		} else if bytes.Compare(b, []byte("valid")) == 0 {
			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 {
	if bytes.Compare(b, []byte("expired")) == 0 {
		return errors.New("expired")
	}
	return nil
}

74
func setupDHT(ctx context.Context, t *testing.T, client bool) *IpfsDHT {
75 76
	d, err := New(
		ctx,
Steven Allen's avatar
Steven Allen committed
77
		bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
78 79 80
		opts.Client(client),
		opts.NamespacedValidator("v", blankValidator{}),
	)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
81

82 83
	if err != nil {
		t.Fatal(err)
84
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
85 86 87
	return d
}

88 89
func setupDHTS(ctx context.Context, n int, t *testing.T) ([]ma.Multiaddr, []peer.ID, []*IpfsDHT) {
	addrs := make([]ma.Multiaddr, n)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
90
	dhts := make([]*IpfsDHT, n)
91 92
	peers := make([]peer.ID, n)

93 94 95
	sanityAddrsMap := make(map[string]struct{})
	sanityPeersMap := make(map[string]struct{})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96
	for i := 0; i < n; i++ {
97
		dhts[i] = setupDHT(ctx, t, false)
98
		peers[i] = dhts[i].self
99
		addrs[i] = dhts[i].peerstore.Addrs(dhts[i].self)[0]
100 101

		if _, lol := sanityAddrsMap[addrs[i].String()]; lol {
Jakub Sztandera's avatar
Jakub Sztandera committed
102
			t.Fatal("While setting up DHTs address got duplicated.")
103 104 105 106
		} else {
			sanityAddrsMap[addrs[i].String()] = struct{}{}
		}
		if _, lol := sanityPeersMap[peers[i].String()]; lol {
Jakub Sztandera's avatar
Jakub Sztandera committed
107
			t.Fatal("While setting up DHTs peerid got duplicated.")
108 109 110
		} else {
			sanityPeersMap[peers[i].String()] = struct{}{}
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111 112 113 114 115
	}

	return addrs, peers, dhts
}

116
func connectNoSync(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
117 118
	t.Helper()

119
	idB := b.self
120
	addrB := b.peerstore.Addrs(idB)
121 122
	if len(addrB) == 0 {
		t.Fatal("peers setup incorrectly: no local address")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123
	}
124

Jeromy's avatar
Jeromy committed
125 126
	a.peerstore.AddAddrs(idB, addrB, pstore.TempAddrTTL)
	pi := pstore.PeerInfo{ID: idB}
Jeromy's avatar
Jeromy committed
127
	if err := a.host.Connect(ctx, pi); err != nil {
128
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129
	}
130 131
}

132 133
func wait(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
	t.Helper()
134

135 136
	// loop until connection notification has been received.
	// under high load, this may not happen as immediately as we would like.
137
	for a.routingTable.Find(b.self) == "" {
138 139 140 141 142
		select {
		case <-ctx.Done():
			t.Fatal(ctx.Err())
		case <-time.After(time.Millisecond * 5):
		}
143
	}
144
}
145

146 147 148 149 150
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
151 152
}

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

155
	ctx, cancel := context.WithCancel(ctx)
Steven Allen's avatar
Steven Allen committed
156 157
	defer cancel()

Richard Littauer's avatar
Richard Littauer committed
158
	log.Debugf("Bootstrapping DHTs...")
159 160 161 162 163 164

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

165 166 167 168
	var cfg BootstrapConfig
	cfg = DefaultBootstrapConfig
	cfg.Queries = 3

169 170 171
	start := rand.Intn(len(dhts)) // randomize to decrease bias.
	for i := range dhts {
		dht := dhts[(start+i)%len(dhts)]
172
		dht.runBootstrap(ctx, cfg)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173 174 175
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176
func TestValueGetSet(t *testing.T) {
177 178
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
179

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

Steven Allen's avatar
Steven Allen committed
182 183 184 185 186
	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
187

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

Steven Allen's avatar
Steven Allen committed
190
	t.Log("adding value on: ", dhts[0].self)
Jeromy's avatar
Jeromy committed
191 192
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
Steven Allen's avatar
Steven Allen committed
193
	err := dhts[0].PutValue(ctxT, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194 195 196 197
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
198
	t.Log("requesting value on dhts: ", dhts[1].self)
Jeromy's avatar
Jeromy committed
199 200
	ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
	defer cancel()
Steven Allen's avatar
Steven Allen committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

	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")
242 243 244 245
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
246 247
	if string(val) != "world" {
		t.Fatalf("Expected 'world' got '%s'", string(val))
248
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
249 250
}

251 252 253 254 255 256 257 258 259 260 261 262
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()

263
	dhtA.Validator.(record.NamespacedValidator)["v"] = testValidator{}
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
	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
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
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()
331
	valCh, err := dhtA.SearchValue(ctxT, "/v/hello", Quorum(-1))
332 333 334
	if err != nil {
		t.Fatal(err)
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359

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

360 361 362 363 364 365 366 367 368 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 394 395 396 397
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))
	}

398
	sort.Slice(vals, func(i, j int) bool { return string(vals[i].Val) < string(vals[j].Val) })
399 400 401 402 403 404 405 406 407

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

408 409 410 411 412 413 414 415 416 417 418 419 420
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{}
421
	dhtB.Validator.(record.NamespacedValidator)["v"] = testValidator{}
422 423 424 425

	connect(t, ctx, dhtA, dhtB)

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

428 429 430 431
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		err := dhtA.PutValue(ctxT, "/v/hello", []byte(val))
		if err != nil {
432
			t.Error(err)
433 434 435 436 437 438
		}

		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
439
			t.Errorf("Set/Get %v: Expected '%v' error but got '%v'", val, experr, err)
440 441
		} else if err == nil && string(valb) != exp {
			t.Errorf("Expected '%v' got '%s'", exp, string(valb))
442 443 444 445 446 447 448 449 450 451 452 453 454
		}
	}

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

455
func TestInvalidMessageSenderTracking(t *testing.T) {
Steven Allen's avatar
Steven Allen committed
456 457 458
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

459
	dht := setupDHT(ctx, t, false)
Steven Allen's avatar
Steven Allen committed
460 461
	defer dht.Close()

462 463 464 465 466 467 468
	foo := peer.ID("asdasd")
	_, err := dht.messageSenderForPeer(foo)
	if err == nil {
		t.Fatal("that shouldnt have succeeded")
	}

	dht.smlk.Lock()
Steven Allen's avatar
Steven Allen committed
469 470 471 472
	mscnt := len(dht.strmap)
	dht.smlk.Unlock()

	if mscnt > 0 {
473 474 475 476
		t.Fatal("should have no message senders in map")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
477 478
func TestProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
479 480
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
481

482
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
483 484
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
485
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
486
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
487 488 489
		}
	}()

490 491 492
	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
493

494
	for _, k := range testCaseCids {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
495
		log.Debugf("announcing provider for %s", k)
Jeromy's avatar
Jeromy committed
496
		if err := dhts[3].Provide(ctx, k, true); err != nil {
497 498
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
499 500
	}

501 502 503 504
	// what is this timeout for? was 60ms before.
	time.Sleep(time.Millisecond * 6)

	n := 0
505
	for _, c := range testCaseCids {
506 507
		n = (n + 1) % 3

508
		log.Debugf("getting providers for %s from %d", c, n)
Jeromy's avatar
Jeromy committed
509 510
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
511
		provchan := dhts[n].FindProvidersAsync(ctxT, c, 1)
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526

		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
527 528
func TestLocalProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
529 530
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Jeromy's avatar
Jeromy committed
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

	_, _, dhts := setupDHTS(ctx, 4, t)
	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 {
		log.Debugf("announcing provider for %s", k)
		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")
			}
		}
	}
}

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
// 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 {
				t.Logf("routing table for %s only has %d peers (should have >%d)", dht.self, rtlen, minPeers)
				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:
590
			log.Debugf("did not reach well-formed routing tables by %s", timeout)
591 592 593 594 595 596 597 598 599 600 601
			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.
602
	fmt.Printf("checking routing table of %d\n", len(dhts))
603 604 605 606 607 608 609
	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
610
func TestBootstrap(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
611
	// t.Skip("skipping test to debug another")
612 613 614 615
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
616 617
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
618

619
	nDHTs := 30
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
620 621 622 623
	_, _, dhts := setupDHTS(ctx, nDHTs, t)
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
624
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
625 626 627 628 629 630 631 632
		}
	}()

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

633
	<-time.After(100 * time.Millisecond)
634 635 636 637
	// bootstrap a few times until we get good tables.
	stop := make(chan struct{})
	go func() {
		for {
638
			t.Logf("bootstrapping them so they find each other %d", nDHTs)
Jeromy's avatar
Jeromy committed
639 640
			ctxT, cancel := context.WithTimeout(ctx, 5*time.Second)
			defer cancel()
641 642 643 644 645 646 647 648 649 650 651
			bootstrap(t, ctxT, dhts)

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

652
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
653
	close(stop)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
654

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
655 656
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
657 658 659 660 661 662
		printRoutingTables(dhts)
	}
}

func TestPeriodicBootstrap(t *testing.T) {
	// t.Skip("skipping test to debug another")
663 664 665
	if ci.IsRunning() {
		t.Skip("skipping on CI. highly timing dependent")
	}
666 667 668 669
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
670 671
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
672 673 674 675 676 677 678 679 680 681

	nDHTs := 30
	_, _, dhts := setupDHTS(ctx, nDHTs, t)
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
			defer dhts[i].host.Close()
		}
	}()

682 683 684 685
	var cfg BootstrapConfig
	cfg = DefaultBootstrapConfig
	cfg.Queries = 5

686
	t.Logf("dhts are not connected. %d", nDHTs)
687 688 689 690 691 692 693 694 695 696 697
	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)])
	}

698
	t.Logf("DHTs are now connected to 1-2 others. %d", nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
699
	for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
700
		rtlen := dht.routingTable.Size()
701 702
		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
703
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
704
	}
705

706 707 708 709
	if u.Debug {
		printRoutingTables(dhts)
	}

710
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
Matt Joiner's avatar
Matt Joiner committed
711 712
	for _, dht := range dhts {
		go dht.BootstrapOnce(ctx, cfg)
713
	}
714 715 716

	// 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.
717
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
718 719 720

	if u.Debug {
		printRoutingTables(dhts)
721
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
722 723
}

724 725
func TestProvidesMany(t *testing.T) {
	t.Skip("this test doesn't work")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
726
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
727 728
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
729 730 731 732 733 734

	nDHTs := 40
	_, _, dhts := setupDHTS(ctx, nDHTs, t)
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
735
			defer dhts[i].host.Close()
736 737 738 739 740 741 742 743
		}
	}()

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

744
	<-time.After(100 * time.Millisecond)
745
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
Jeromy's avatar
Jeromy committed
746 747
	ctxT, cancel := context.WithTimeout(ctx, 20*time.Second)
	defer cancel()
748 749
	bootstrap(t, ctxT, dhts)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
750 751 752 753 754 755 756 757
	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("")
		}
758
	}
759

760
	providers := make(map[string]peer.ID)
761

762
	d := 0
763
	for _, c := range testCaseCids {
764 765
		d = (d + 1) % len(dhts)
		dht := dhts[d]
766
		providers[c.KeyString()] = dht.self
767

768
		t.Logf("announcing provider for %s", c)
Jeromy's avatar
Jeromy committed
769
		if err := dht.Provide(ctx, c, true); err != nil {
770 771
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
772 773
	}

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

777 778
	errchan := make(chan error)

Jeromy's avatar
Jeromy committed
779 780
	ctxT, cancel = context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
781 782

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

786
		expected := providers[k.KeyString()]
787

788 789 790
		provchan := dht.FindProvidersAsync(ctxT, k, 1)
		select {
		case prov := <-provchan:
791 792
			actual := prov.ID
			if actual == "" {
793
				errchan <- fmt.Errorf("Got back nil provider (%s at %s)", k, dht.self)
794 795 796
			} else if actual != expected {
				errchan <- fmt.Errorf("Got back wrong provider (%s != %s) (%s at %s)",
					expected, actual, k, dht.self)
797 798 799
			}
		case <-ctxT.Done():
			errchan <- fmt.Errorf("Did not get a provider back (%s at %s)", k, dht.self)
Jeromy's avatar
Jeromy committed
800
		}
801 802
	}

803
	for _, c := range testCaseCids {
804 805
		// everyone should be able to find it...
		for _, dht := range dhts {
806
			log.Debugf("getting providers for %s at %s", c, dht.self)
807
			wg.Add(1)
808
			go getProvider(dht, c)
809
		}
810 811 812 813 814 815 816 817 818 819
	}

	// 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
820 821 822
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
823
func TestProvidesAsync(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
824
	// t.Skip("skipping test to debug another")
825 826 827
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
828

Steven Allen's avatar
Steven Allen committed
829 830
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
831

832
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
833 834
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
835
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
836
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
837 838 839
		}
	}()

840 841 842
	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
843

Jeromy's avatar
Jeromy committed
844
	err := dhts[3].Provide(ctx, testCaseCids[0], true)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
845 846 847 848 849 850
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 60)

Jeromy's avatar
Jeromy committed
851 852
	ctxT, cancel := context.WithTimeout(ctx, time.Millisecond*300)
	defer cancel()
853
	provs := dhts[0].FindProvidersAsync(ctxT, testCaseCids[0], 5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
854
	select {
Jeromy's avatar
Jeromy committed
855 856 857 858
	case p, ok := <-provs:
		if !ok {
			t.Fatal("Provider channel was closed...")
		}
859
		if p.ID == "" {
Jeromy's avatar
Jeromy committed
860 861
			t.Fatal("Got back nil provider!")
		}
862
		if p.ID != dhts[3].self {
863
			t.Fatalf("got a provider, but not the right one. %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
864
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
865
	case <-ctxT.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
866 867 868 869
		t.Fatal("Didnt get back providers")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
870
func TestLayeredGet(t *testing.T) {
871 872
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
873

874
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
875 876
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
877
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
878
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
879 880 881
		}
	}()

882 883
	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
884
	connect(t, ctx, dhts[2], dhts[3])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
885

886
	err := dhts[3].PutValue(ctx, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
887 888 889 890
	if err != nil {
		t.Fatal(err)
	}

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

Jeromy's avatar
Jeromy committed
893 894
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
895 896 897
	val, err := dhts[0].GetValue(ctxT, "/v/hello")
	if err != nil {
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
898
	}
899 900 901

	if string(val) != "world" {
		t.Error("got wrong value")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
902 903 904 905
	}
}

func TestFindPeer(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
906
	// t.Skip("skipping test to debug another")
907 908 909
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
910

Steven Allen's avatar
Steven Allen committed
911 912
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
913

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
914
	_, peers, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
915 916
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
917
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
918
			dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
919 920 921
		}
	}()

922 923 924
	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
925

Jeromy's avatar
Jeromy committed
926 927
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
928
	p, err := dhts[0].FindPeer(ctxT, peers[2])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
929 930 931 932
	if err != nil {
		t.Fatal(err)
	}

933
	if p.ID == "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
934 935 936
		t.Fatal("Failed to find peer.")
	}

937
	if p.ID != peers[2] {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
938 939 940
		t.Fatal("Didnt find expected peer.")
	}
}
941

942
func TestFindPeersConnectedToPeer(t *testing.T) {
943 944
	t.Skip("not quite correct (see note)")

945 946 947 948
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
949 950
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
951 952 953 954 955

	_, peers, dhts := setupDHTS(ctx, 4, t)
	defer func() {
		for i := 0; i < 4; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
956
			dhts[i].host.Close()
957 958 959 960 961
		}
	}()

	// topology:
	// 0-1, 1-2, 1-3, 2-3
962 963 964 965
	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])
966 967 968 969 970 971

	// 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
972 973
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
974
	pchan, err := dhts[0].FindPeersConnectedToPeer(ctxT, peers[2])
975 976 977 978
	if err != nil {
		t.Fatal(err)
	}

979
	// shouldFind := []peer.ID{peers[1], peers[3]}
Jeromy's avatar
Jeromy committed
980
	var found []*pstore.PeerInfo
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
	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)

	log.Warning("TestFindPeersConnectedToPeer is not quite correct")
	if len(found) == 0 {
		t.Fatal("didn't find any peers.")
	}
}

997
func testPeerListsMatch(t *testing.T, p1, p2 []peer.ID) {
998 999 1000 1001 1002 1003 1004 1005 1006

	if len(p1) != len(p2) {
		t.Fatal("did not find as many peers as should have", p1, p2)
	}

	ids1 := make([]string, len(p1))
	ids2 := make([]string, len(p2))

	for i, p := range p1 {
1007
		ids1[i] = string(p)
1008 1009 1010
	}

	for i, p := range p2 {
1011
		ids2[i] = string(p)
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
	}

	sort.Sort(sort.StringSlice(ids1))
	sort.Sort(sort.StringSlice(ids2))

	for i := range ids1 {
		if ids1[i] != ids2[i] {
			t.Fatal("Didnt find expected peer", ids1[i], ids2)
		}
	}
}

1024
func TestConnectCollision(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1025
	// t.Skip("skipping test to debug another")
1026 1027 1028
	if testing.Short() {
		t.SkipNow()
	}
1029 1030 1031
	if travisci.IsRunning() {
		t.Skip("Skipping on Travis-CI.")
	}
1032

1033
	runTimes := 10
1034

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1035
	for rtime := 0; rtime < runTimes; rtime++ {
rht's avatar
rht committed
1036
		log.Info("Running Time: ", rtime)
1037

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

1040 1041
		dhtA := setupDHT(ctx, t, false)
		dhtB := setupDHT(ctx, t, false)
1042

1043 1044
		addrA := dhtA.peerstore.Addrs(dhtA.self)[0]
		addrB := dhtB.peerstore.Addrs(dhtB.self)[0]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1045

1046 1047
		peerA := dhtA.self
		peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1048

1049
		errs := make(chan error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1050
		go func() {
Jeromy's avatar
Jeromy committed
1051 1052
			dhtA.peerstore.AddAddr(peerB, addrB, pstore.TempAddrTTL)
			pi := pstore.PeerInfo{ID: peerB}
Jeromy's avatar
Jeromy committed
1053
			err := dhtA.host.Connect(ctx, pi)
1054
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1055 1056
		}()
		go func() {
Jeromy's avatar
Jeromy committed
1057 1058
			dhtB.peerstore.AddAddr(peerA, addrA, pstore.TempAddrTTL)
			pi := pstore.PeerInfo{ID: peerA}
Jeromy's avatar
Jeromy committed
1059
			err := dhtB.host.Connect(ctx, pi)
1060
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1061 1062
		}()

1063
		timeout := time.After(5 * time.Second)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1064
		select {
1065 1066 1067 1068
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1069 1070 1071 1072
		case <-timeout:
			t.Fatal("Timeout received!")
		}
		select {
1073 1074 1075 1076
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1077 1078 1079 1080
		case <-timeout:
			t.Fatal("Timeout received!")
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1081 1082
		dhtA.Close()
		dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1083 1084
		dhtA.host.Close()
		dhtB.host.Close()
Steven Allen's avatar
Steven Allen committed
1085
		cancel()
Jeromy's avatar
Jeromy committed
1086
	}
1087
}
1088 1089 1090 1091 1092

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

1093
	d := setupDHT(ctx, t, false)
1094 1095 1096 1097 1098 1099

	nilrec := new(pb.Message)
	if _, err := d.handlePutValue(ctx, "testpeer", nilrec); err == nil {
		t.Fatal("should have errored on nil record")
	}
}
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109

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)

1110
	c := testCaseCids[0]
1111
	p := peer.ID("TestPeer")
1112 1113
	a.providers.AddProvider(ctx, c, p)
	time.Sleep(time.Millisecond * 5) // just in case...
1114

1115
	provs, err := b.FindProviders(ctx, c)
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
	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
1127 1128 1129 1130 1131 1132 1133 1134 1135
	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) {
1136
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
Steven Allen's avatar
Steven Allen committed
1137 1138 1139 1140 1141 1142
	defer cancel()

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

1143 1144
	connectNoSync(t, ctx, b, a)
	connectNoSync(t, ctx, c, a)
Steven Allen's avatar
Steven Allen committed
1145 1146

	// Can't use `connect` because b and c are only clients.
1147 1148
	wait(t, ctx, b, a)
	wait(t, ctx, c, a)
Steven Allen's avatar
Steven Allen committed
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

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

1164 1165 1166 1167
func TestFindPeerQuery(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

Jeromy's avatar
Jeromy committed
1168
	nDHTs := 101
1169 1170 1171 1172 1173 1174 1175 1176
	_, allpeers, dhts := setupDHTS(ctx, nDHTs, t)
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
			defer dhts[i].host.Close()
		}
	}()

Jeromy's avatar
Jeromy committed
1177
	mrand := rand.New(rand.NewSource(42))
1178 1179 1180
	guy := dhts[0]
	others := dhts[1:]
	for i := 0; i < 20; i++ {
Jeromy's avatar
Jeromy committed
1181 1182 1183
		for j := 0; j < 16; j++ { // 16, high enough to probably not have any partitions
			v := mrand.Intn(80)
			connect(t, ctx, others[i], others[20+v])
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
		}
	}

	for i := 0; i < 20; i++ {
		connect(t, ctx, guy, others[i])
	}

	val := "foobar"
	rtval := kb.ConvertKey(val)

Jeromy's avatar
Jeromy committed
1194 1195 1196
	rtablePeers := guy.routingTable.NearestPeers(rtval, AlphaValue)
	if len(rtablePeers) != 3 {
		t.Fatalf("expected 3 peers back from routing table, got %d", len(rtablePeers))
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
	}

	netpeers := guy.host.Network().Peers()
	if len(netpeers) != 20 {
		t.Fatalf("expected 20 peers to be connected, got %d", len(netpeers))
	}

	rtableset := make(map[peer.ID]bool)
	for _, p := range rtablePeers {
		rtableset[p] = true
	}

	out, err := guy.GetClosestPeers(ctx, val)
	if err != nil {
		t.Fatal(err)
	}

	var notfromrtable int
	var count int
	var outpeers []peer.ID
	for p := range out {
		count++
		if !rtableset[p] {
			notfromrtable++
		}
		outpeers = append(outpeers, p)
	}

	if notfromrtable == 0 {
		t.Fatal("got entirely peers from our routing table")
	}

Jeromy's avatar
Jeromy committed
1229 1230 1231 1232 1233 1234
	if count != 20 {
		t.Fatal("should have only gotten 20 peers from getclosestpeers call")
	}

	sort.Sort(peer.IDSlice(allpeers[1:]))
	sort.Sort(peer.IDSlice(outpeers))
Steven Allen's avatar
Steven Allen committed
1235

1236 1237 1238
	actualclosest := kb.SortClosestPeers(allpeers[1:], rtval)
	exp := actualclosest[:20]
	got := kb.SortClosestPeers(outpeers, rtval)
Jeromy's avatar
Jeromy committed
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

	diffp := countDiffPeers(exp, got)
	if diffp > 0 {
		// could be a partition created during setup
		t.Fatal("didnt get expected closest peers")
	}
}

func countDiffPeers(a, b []peer.ID) int {
	s := make(map[peer.ID]bool)
	for _, p := range a {
		s[p] = true
	}
	var out int
	for _, p := range b {
		if !s[p] {
			out++
1256 1257
		}
	}
Jeromy's avatar
Jeromy committed
1258
	return out
1259 1260
}

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
func TestFindClosestPeers(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	nDHTs := 30
	_, _, dhts := setupDHTS(ctx, nDHTs, t)
	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)
	}
}
1293 1294

func TestGetSetPluggedProtocol(t *testing.T) {
1295 1296 1297
	t.Run("PutValue/GetValue - same protocol", func(t *testing.T) {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
1298

1299 1300 1301 1302 1303
		os := []opts.Option{
			opts.Protocols("/esh/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
		}
1304

Steven Allen's avatar
Steven Allen committed
1305
		dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
1306 1307 1308
		if err != nil {
			t.Fatal(err)
		}
1309

Steven Allen's avatar
Steven Allen committed
1310
		dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
1311 1312 1313
		if err != nil {
			t.Fatal(err)
		}
1314

1315
		connect(t, ctx, dhtA, dhtB)
1316

1317
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
1318
		defer cancel()
1319 1320 1321
		if err := dhtA.PutValue(ctxT, "/v/cat", []byte("meow")); err != nil {
			t.Fatal(err)
		}
1322

1323 1324 1325 1326
		value, err := dhtB.GetValue(ctxT, "/v/cat")
		if err != nil {
			t.Fatal(err)
		}
1327

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

1333 1334
	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)
1335 1336
		defer cancel()

Steven Allen's avatar
Steven Allen committed
1337
		dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), []opts.Option{
1338 1339 1340
			opts.Protocols("/esh/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
1341
		}...)
1342 1343 1344 1345
		if err != nil {
			t.Fatal(err)
		}

Steven Allen's avatar
Steven Allen committed
1346
		dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), []opts.Option{
1347 1348 1349
			opts.Protocols("/lsr/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
1350
		}...)
1351 1352 1353 1354
		if err != nil {
			t.Fatal(err)
		}

1355
		connectNoSync(t, ctx, dhtA, dhtB)
1356

1357 1358 1359 1360 1361 1362 1363
		// 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") {
1364
			t.Fatalf("put should not have been able to find any peers in routing table, err:'%v'", err)
1365 1366
		}

1367 1368
		_, err = dhtB.GetValue(ctx, "/v/cat")
		if err == nil || !strings.Contains(err.Error(), "failed to find any peer in table") {
1369
			t.Fatalf("get should not have been able to find any peers in routing table, err:'%v'", err)
1370
		}
1371
	})
1372
}