dht_test.go 28.6 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 33
var testCaseValues = map[string][]byte{}
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
	idB := b.self
118
	addrB := b.peerstore.Addrs(idB)
119 120
	if len(addrB) == 0 {
		t.Fatal("peers setup incorrectly: no local address")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
121
	}
122

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

func connect(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
	connectNoSync(t, ctx, a, b)
132

133 134
	// loop until connection notification has been received.
	// under high load, this may not happen as immediately as we would like.
135 136 137 138 139 140 141
	for a.routingTable.Find(b.self) == "" {
		time.Sleep(time.Millisecond * 5)
	}

	for b.routingTable.Find(a.self) == "" {
		time.Sleep(time.Millisecond * 5)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142 143
}

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

146
	ctx, cancel := context.WithCancel(ctx)
Steven Allen's avatar
Steven Allen committed
147 148
	defer cancel()

Richard Littauer's avatar
Richard Littauer committed
149
	log.Debugf("Bootstrapping DHTs...")
150 151 152 153 154 155

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

156 157 158 159
	var cfg BootstrapConfig
	cfg = DefaultBootstrapConfig
	cfg.Queries = 3

160 161 162
	start := rand.Intn(len(dhts)) // randomize to decrease bias.
	for i := range dhts {
		dht := dhts[(start+i)%len(dhts)]
163
		dht.runBootstrap(ctx, cfg)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164 165 166
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167
func TestValueGetSet(t *testing.T) {
168 169
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
170

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

Steven Allen's avatar
Steven Allen committed
173 174 175 176 177
	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
178

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

Steven Allen's avatar
Steven Allen committed
181
	t.Log("adding value on: ", dhts[0].self)
Jeromy's avatar
Jeromy committed
182 183
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
Steven Allen's avatar
Steven Allen committed
184
	err := dhts[0].PutValue(ctxT, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
185 186 187 188
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
189
	t.Log("requesting value on dhts: ", dhts[1].self)
Jeromy's avatar
Jeromy committed
190 191
	ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
	defer cancel()
Steven Allen's avatar
Steven Allen committed
192 193 194 195 196 197 198 199 200 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

	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")
233 234 235 236
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
237 238
	if string(val) != "world" {
		t.Fatalf("Expected 'world' got '%s'", string(val))
239
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
240 241
}

242 243 244 245 246 247 248 249 250 251 252 253
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()

254
	dhtA.Validator.(record.NamespacedValidator)["v"] = testValidator{}
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
	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)
}

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{}
308
	dhtB.Validator.(record.NamespacedValidator)["v"] = testValidator{}
309 310 311 312

	connect(t, ctx, dhtA, dhtB)

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

315 316 317 318
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		err := dhtA.PutValue(ctxT, "/v/hello", []byte(val))
		if err != nil {
319
			t.Error(err)
320 321 322 323 324 325
		}

		ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
		defer cancel()
		valb, err := dhtB.GetValue(ctxT, "/v/hello")
		if err != experr {
326 327 328
			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))
329 330 331 332 333 334 335 336 337 338 339 340 341
		}
	}

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

342
func TestInvalidMessageSenderTracking(t *testing.T) {
Steven Allen's avatar
Steven Allen committed
343 344 345
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

346
	dht := setupDHT(ctx, t, false)
Steven Allen's avatar
Steven Allen committed
347 348
	defer dht.Close()

349 350 351 352 353 354 355
	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
356 357 358 359
	mscnt := len(dht.strmap)
	dht.smlk.Unlock()

	if mscnt > 0 {
360 361 362 363
		t.Fatal("should have no message senders in map")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
364 365
func TestProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
366 367
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
368

369
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
370 371
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
372
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
373
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
374 375 376
		}
	}()

377 378 379
	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
380

381
	for _, k := range testCaseCids {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
382
		log.Debugf("announcing provider for %s", k)
Jeromy's avatar
Jeromy committed
383
		if err := dhts[3].Provide(ctx, k, true); err != nil {
384 385
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
386 387
	}

388 389 390 391
	// what is this timeout for? was 60ms before.
	time.Sleep(time.Millisecond * 6)

	n := 0
392
	for _, c := range testCaseCids {
393 394
		n = (n + 1) % 3

395
		log.Debugf("getting providers for %s from %d", c, n)
Jeromy's avatar
Jeromy committed
396 397
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
398
		provchan := dhts[n].FindProvidersAsync(ctxT, c, 1)
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413

		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
414 415
func TestLocalProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
416 417
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Jeromy's avatar
Jeromy committed
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449

	_, _, 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")
			}
		}
	}
}

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
// 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:
477
			log.Debugf("did not reach well-formed routing tables by %s", timeout)
478 479 480 481 482 483 484 485 486 487 488
			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.
489
	fmt.Printf("checking routing table of %d\n", len(dhts))
490 491 492 493 494 495 496
	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
497
func TestBootstrap(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
498
	// t.Skip("skipping test to debug another")
499 500 501 502
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
503 504
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
505

506
	nDHTs := 30
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
507 508 509 510
	_, _, 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
511
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
512 513 514 515 516 517 518 519
		}
	}()

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

520
	<-time.After(100 * time.Millisecond)
521 522 523 524
	// bootstrap a few times until we get good tables.
	stop := make(chan struct{})
	go func() {
		for {
525
			t.Logf("bootstrapping them so they find each other %d", nDHTs)
Jeromy's avatar
Jeromy committed
526 527
			ctxT, cancel := context.WithTimeout(ctx, 5*time.Second)
			defer cancel()
528 529 530 531 532 533 534 535 536 537 538
			bootstrap(t, ctxT, dhts)

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

539
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
540
	close(stop)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
541

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
542 543
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
544 545 546 547 548 549
		printRoutingTables(dhts)
	}
}

func TestPeriodicBootstrap(t *testing.T) {
	// t.Skip("skipping test to debug another")
550 551 552
	if ci.IsRunning() {
		t.Skip("skipping on CI. highly timing dependent")
	}
553 554 555 556
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
557 558
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
559 560 561 562 563 564 565 566 567 568

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

569
	signals := []chan time.Time{}
570

571 572 573 574
	var cfg BootstrapConfig
	cfg = DefaultBootstrapConfig
	cfg.Queries = 5

575 576 577
	// kick off periodic bootstrappers with instrumented signals.
	for _, dht := range dhts {
		s := make(chan time.Time)
578 579 580 581 582 583
		signals = append(signals, s)
		proc, err := dht.BootstrapOnSignal(cfg, s)
		if err != nil {
			t.Fatal(err)
		}
		defer proc.Close()
584 585
	}

586
	t.Logf("dhts are not connected. %d", nDHTs)
587 588 589 590 591 592 593 594 595 596 597
	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)])
	}

598
	t.Logf("DHTs are now connected to 1-2 others. %d", nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
599
	for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
600
		rtlen := dht.routingTable.Size()
601 602
		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
603
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
604
	}
605

606 607 608 609
	if u.Debug {
		printRoutingTables(dhts)
	}

610
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
611 612 613 614
	now := time.Now()
	for _, signal := range signals {
		go func(s chan time.Time) { s <- now }(signal)
	}
615 616 617

	// 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.
618
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
619 620 621

	if u.Debug {
		printRoutingTables(dhts)
622
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
623 624
}

625 626
func TestProvidesMany(t *testing.T) {
	t.Skip("this test doesn't work")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
627
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
628 629
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
630 631 632 633 634 635

	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
636
			defer dhts[i].host.Close()
637 638 639 640 641 642 643 644
		}
	}()

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

645
	<-time.After(100 * time.Millisecond)
646
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
Jeromy's avatar
Jeromy committed
647 648
	ctxT, cancel := context.WithTimeout(ctx, 20*time.Second)
	defer cancel()
649 650
	bootstrap(t, ctxT, dhts)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
651 652 653 654 655 656 657 658
	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("")
		}
659
	}
660

661
	providers := make(map[string]peer.ID)
662

663
	d := 0
664
	for _, c := range testCaseCids {
665 666
		d = (d + 1) % len(dhts)
		dht := dhts[d]
667
		providers[c.KeyString()] = dht.self
668

669
		t.Logf("announcing provider for %s", c)
Jeromy's avatar
Jeromy committed
670
		if err := dht.Provide(ctx, c, true); err != nil {
671 672
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
673 674
	}

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

678 679
	errchan := make(chan error)

Jeromy's avatar
Jeromy committed
680 681
	ctxT, cancel = context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
682 683

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

687
		expected := providers[k.KeyString()]
688

689 690 691
		provchan := dht.FindProvidersAsync(ctxT, k, 1)
		select {
		case prov := <-provchan:
692 693
			actual := prov.ID
			if actual == "" {
694
				errchan <- fmt.Errorf("Got back nil provider (%s at %s)", k, dht.self)
695 696 697
			} else if actual != expected {
				errchan <- fmt.Errorf("Got back wrong provider (%s != %s) (%s at %s)",
					expected, actual, k, dht.self)
698 699 700
			}
		case <-ctxT.Done():
			errchan <- fmt.Errorf("Did not get a provider back (%s at %s)", k, dht.self)
Jeromy's avatar
Jeromy committed
701
		}
702 703
	}

704
	for _, c := range testCaseCids {
705 706
		// everyone should be able to find it...
		for _, dht := range dhts {
707
			log.Debugf("getting providers for %s at %s", c, dht.self)
708
			wg.Add(1)
709
			go getProvider(dht, c)
710
		}
711 712 713 714 715 716 717 718 719 720
	}

	// 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
721 722 723
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
724
func TestProvidesAsync(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
725
	// t.Skip("skipping test to debug another")
726 727 728
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
729

Steven Allen's avatar
Steven Allen committed
730 731
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
732

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

741 742 743
	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
744

Jeromy's avatar
Jeromy committed
745
	err := dhts[3].Provide(ctx, testCaseCids[0], true)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
746 747 748 749 750 751
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 60)

Jeromy's avatar
Jeromy committed
752 753
	ctxT, cancel := context.WithTimeout(ctx, time.Millisecond*300)
	defer cancel()
754
	provs := dhts[0].FindProvidersAsync(ctxT, testCaseCids[0], 5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
755
	select {
Jeromy's avatar
Jeromy committed
756 757 758 759
	case p, ok := <-provs:
		if !ok {
			t.Fatal("Provider channel was closed...")
		}
760
		if p.ID == "" {
Jeromy's avatar
Jeromy committed
761 762
			t.Fatal("Got back nil provider!")
		}
763
		if p.ID != dhts[3].self {
764
			t.Fatalf("got a provider, but not the right one. %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
765
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
766
	case <-ctxT.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
767 768 769 770
		t.Fatal("Didnt get back providers")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
771
func TestLayeredGet(t *testing.T) {
772 773
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
774

775
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
776 777
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
778
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
779
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
780 781 782
		}
	}()

783 784
	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
785
	connect(t, ctx, dhts[2], dhts[3])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
786

787
	err := dhts[3].PutValue(ctx, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
788 789 790 791
	if err != nil {
		t.Fatal(err)
	}

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

Jeromy's avatar
Jeromy committed
794 795
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
796 797 798
	val, err := dhts[0].GetValue(ctxT, "/v/hello")
	if err != nil {
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
799
	}
800 801 802

	if string(val) != "world" {
		t.Error("got wrong value")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
803 804 805 806
	}
}

func TestFindPeer(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
807
	// t.Skip("skipping test to debug another")
808 809 810
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
811

Steven Allen's avatar
Steven Allen committed
812 813
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
814

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
815
	_, peers, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
816 817
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
818
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
819
			dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
820 821 822
		}
	}()

823 824 825
	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
826

Jeromy's avatar
Jeromy committed
827 828
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
829
	p, err := dhts[0].FindPeer(ctxT, peers[2])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
830 831 832 833
	if err != nil {
		t.Fatal(err)
	}

834
	if p.ID == "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
835 836 837
		t.Fatal("Failed to find peer.")
	}

838
	if p.ID != peers[2] {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
839 840 841
		t.Fatal("Didnt find expected peer.")
	}
}
842

843
func TestFindPeersConnectedToPeer(t *testing.T) {
844 845
	t.Skip("not quite correct (see note)")

846 847 848 849
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
850 851
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
852 853 854 855 856

	_, 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
857
			dhts[i].host.Close()
858 859 860 861 862
		}
	}()

	// topology:
	// 0-1, 1-2, 1-3, 2-3
863 864 865 866
	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])
867 868 869 870 871 872

	// 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
873 874
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
875
	pchan, err := dhts[0].FindPeersConnectedToPeer(ctxT, peers[2])
876 877 878 879
	if err != nil {
		t.Fatal(err)
	}

880
	// shouldFind := []peer.ID{peers[1], peers[3]}
Jeromy's avatar
Jeromy committed
881
	var found []*pstore.PeerInfo
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
	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.")
	}
}

898
func testPeerListsMatch(t *testing.T, p1, p2 []peer.ID) {
899 900 901 902 903 904 905 906 907

	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 {
908
		ids1[i] = string(p)
909 910 911
	}

	for i, p := range p2 {
912
		ids2[i] = string(p)
913 914 915 916 917 918 919 920 921 922 923 924
	}

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

925
func TestConnectCollision(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
926
	// t.Skip("skipping test to debug another")
927 928 929
	if testing.Short() {
		t.SkipNow()
	}
930 931 932
	if travisci.IsRunning() {
		t.Skip("Skipping on Travis-CI.")
	}
933

934
	runTimes := 10
935

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

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

941 942
		dhtA := setupDHT(ctx, t, false)
		dhtB := setupDHT(ctx, t, false)
943

944 945
		addrA := dhtA.peerstore.Addrs(dhtA.self)[0]
		addrB := dhtB.peerstore.Addrs(dhtB.self)[0]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
946

947 948
		peerA := dhtA.self
		peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
949

950
		errs := make(chan error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
951
		go func() {
Jeromy's avatar
Jeromy committed
952 953
			dhtA.peerstore.AddAddr(peerB, addrB, pstore.TempAddrTTL)
			pi := pstore.PeerInfo{ID: peerB}
Jeromy's avatar
Jeromy committed
954
			err := dhtA.host.Connect(ctx, pi)
955
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
956 957
		}()
		go func() {
Jeromy's avatar
Jeromy committed
958 959
			dhtB.peerstore.AddAddr(peerA, addrA, pstore.TempAddrTTL)
			pi := pstore.PeerInfo{ID: peerA}
Jeromy's avatar
Jeromy committed
960
			err := dhtB.host.Connect(ctx, pi)
961
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
962 963
		}()

964
		timeout := time.After(5 * time.Second)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
965
		select {
966 967 968 969
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
970 971 972 973
		case <-timeout:
			t.Fatal("Timeout received!")
		}
		select {
974 975 976 977
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
978 979 980 981
		case <-timeout:
			t.Fatal("Timeout received!")
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
982 983
		dhtA.Close()
		dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
984 985
		dhtA.host.Close()
		dhtB.host.Close()
Steven Allen's avatar
Steven Allen committed
986
		cancel()
Jeromy's avatar
Jeromy committed
987
	}
988
}
989 990 991 992 993

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

994
	d := setupDHT(ctx, t, false)
995 996 997 998 999 1000

	nilrec := new(pb.Message)
	if _, err := d.handlePutValue(ctx, "testpeer", nilrec); err == nil {
		t.Fatal("should have errored on nil record")
	}
}
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

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)

1011
	c := testCaseCids[0]
1012
	p := peer.ID("TestPeer")
1013 1014
	a.providers.AddProvider(ctx, c, p)
	time.Sleep(time.Millisecond * 5) // just in case...
1015

1016
	provs, err := b.FindProviders(ctx, c)
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
	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")
	}
}
1029

1030 1031 1032 1033
func TestFindPeerQuery(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

Jeromy's avatar
Jeromy committed
1034
	nDHTs := 101
1035 1036 1037 1038 1039 1040 1041 1042
	_, 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
1043
	mrand := rand.New(rand.NewSource(42))
1044 1045 1046
	guy := dhts[0]
	others := dhts[1:]
	for i := 0; i < 20; i++ {
Jeromy's avatar
Jeromy committed
1047 1048 1049
		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])
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
		}
	}

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

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

Jeromy's avatar
Jeromy committed
1060 1061 1062
	rtablePeers := guy.routingTable.NearestPeers(rtval, AlphaValue)
	if len(rtablePeers) != 3 {
		t.Fatalf("expected 3 peers back from routing table, got %d", len(rtablePeers))
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
	}

	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
1095 1096 1097 1098 1099 1100
	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))
1101 1102 1103 1104
	fmt.Println("counts: ", count, notfromrtable)
	actualclosest := kb.SortClosestPeers(allpeers[1:], rtval)
	exp := actualclosest[:20]
	got := kb.SortClosestPeers(outpeers, rtval)
Jeromy's avatar
Jeromy committed
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

	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++
1122 1123
		}
	}
Jeromy's avatar
Jeromy committed
1124
	return out
1125 1126
}

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
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)
	}
}
1159 1160

func TestGetSetPluggedProtocol(t *testing.T) {
1161 1162 1163
	t.Run("PutValue/GetValue - same protocol", func(t *testing.T) {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
1164

1165 1166 1167 1168 1169
		os := []opts.Option{
			opts.Protocols("/esh/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
		}
1170

Steven Allen's avatar
Steven Allen committed
1171
		dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
1172 1173 1174
		if err != nil {
			t.Fatal(err)
		}
1175

Steven Allen's avatar
Steven Allen committed
1176
		dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
1177 1178 1179
		if err != nil {
			t.Fatal(err)
		}
1180

1181
		connect(t, ctx, dhtA, dhtB)
1182

1183
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
1184
		defer cancel()
1185 1186 1187
		if err := dhtA.PutValue(ctxT, "/v/cat", []byte("meow")); err != nil {
			t.Fatal(err)
		}
1188

1189 1190 1191 1192
		value, err := dhtB.GetValue(ctxT, "/v/cat")
		if err != nil {
			t.Fatal(err)
		}
1193

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

1199 1200
	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)
1201 1202
		defer cancel()

Steven Allen's avatar
Steven Allen committed
1203
		dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), []opts.Option{
1204 1205 1206
			opts.Protocols("/esh/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
1207
		}...)
1208 1209 1210 1211
		if err != nil {
			t.Fatal(err)
		}

Steven Allen's avatar
Steven Allen committed
1212
		dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), []opts.Option{
1213 1214 1215
			opts.Protocols("/lsr/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
1216
		}...)
1217 1218 1219 1220
		if err != nil {
			t.Fatal(err)
		}

1221
		connectNoSync(t, ctx, dhtA, dhtB)
1222

1223 1224 1225 1226 1227 1228 1229 1230
		// 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") {
			t.Fatal("should not have been able to find any peers in routing table")
1231 1232
		}

1233 1234 1235 1236
		_, err = dhtB.GetValue(ctx, "/v/cat")
		if err == nil || !strings.Contains(err.Error(), "failed to find any peer in table") {
			t.Fatal("should not have been able to find any peers in routing table")
		}
1237
	})
1238
}