dht_test.go 41.1 KB
Newer Older
1 2
package dht

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

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

	"golang.org/x/xerrors"

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

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

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

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

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

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

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

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

type testValidator struct{}

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

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
type testAtomicPutValidator struct {
	testValidator
}

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

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

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

130
func setupDHT(ctx context.Context, t *testing.T, client bool, options ...opts.Option) *IpfsDHT {
131 132
	d, err := New(
		ctx,
Steven Allen's avatar
Steven Allen committed
133
		bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
134 135 136 137 138
		append([]opts.Option{
			opts.Client(client),
			opts.NamespacedValidator("v", blankValidator{}),
			opts.DisableAutoRefresh(),
		}, options...)...,
139 140 141
	)
	if err != nil {
		t.Fatal(err)
142
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143 144 145
	return d
}

146
func setupDHTS(t *testing.T, ctx context.Context, n int) []*IpfsDHT {
147
	addrs := make([]ma.Multiaddr, n)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148
	dhts := make([]*IpfsDHT, n)
149 150
	peers := make([]peer.ID, n)

151 152 153
	sanityAddrsMap := make(map[string]struct{})
	sanityPeersMap := make(map[string]struct{})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
154
	for i := 0; i < n; i++ {
155
		dhts[i] = setupDHT(ctx, t, false)
156 157
		peers[i] = dhts[i].PeerID()
		addrs[i] = dhts[i].host.Addrs()[0]
158 159

		if _, lol := sanityAddrsMap[addrs[i].String()]; lol {
Jakub Sztandera's avatar
Jakub Sztandera committed
160
			t.Fatal("While setting up DHTs address got duplicated.")
161 162 163 164
		} else {
			sanityAddrsMap[addrs[i].String()] = struct{}{}
		}
		if _, lol := sanityPeersMap[peers[i].String()]; lol {
Jakub Sztandera's avatar
Jakub Sztandera committed
165
			t.Fatal("While setting up DHTs peerid got duplicated.")
166 167 168
		} else {
			sanityPeersMap[peers[i].String()] = struct{}{}
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
169 170
	}

171
	return dhts
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
172 173
}

174
func connectNoSync(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
175 176
	t.Helper()

177
	idB := b.self
178
	addrB := b.peerstore.Addrs(idB)
179 180
	if len(addrB) == 0 {
		t.Fatal("peers setup incorrectly: no local address")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
181
	}
182

183 184
	a.peerstore.AddAddrs(idB, addrB, peerstore.TempAddrTTL)
	pi := peer.AddrInfo{ID: idB}
Jeromy's avatar
Jeromy committed
185
	if err := a.host.Connect(ctx, pi); err != nil {
186
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
187
	}
188 189
}

190 191
func wait(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
	t.Helper()
192

193 194
	// loop until connection notification has been received.
	// under high load, this may not happen as immediately as we would like.
195
	for a.routingTable.Find(b.self) == "" {
196 197 198 199 200
		select {
		case <-ctx.Done():
			t.Fatal(ctx.Err())
		case <-time.After(time.Millisecond * 5):
		}
201
	}
202
}
203

204 205 206 207 208
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
209 210
}

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

215
	logger.Debugf("refreshing DHTs routing tables...")
216 217 218 219 220 221 222 223 224

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

	start := rand.Intn(len(dhts)) // randomize to decrease bias.
	for i := range dhts {
		dht := dhts[(start+i)%len(dhts)]
225 226 227 228 229 230 231 232
		select {
		case err := <-dht.RefreshRoutingTable():
			if err != nil {
				t.Error(err)
			}
		case <-ctx.Done():
			return
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
233 234 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 276
// Check to make sure we always signal the RefreshRoutingTable channel.
func TestRefreshMultiple(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
277
func TestValueGetSet(t *testing.T) {
278 279
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
280

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

Steven Allen's avatar
Steven Allen committed
283 284 285 286 287
	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
288

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

Steven Allen's avatar
Steven Allen committed
291
	t.Log("adding value on: ", dhts[0].self)
Jeromy's avatar
Jeromy committed
292 293
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
Steven Allen's avatar
Steven Allen committed
294
	err := dhts[0].PutValue(ctxT, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
295 296 297 298
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
299
	t.Log("requesting value on dhts: ", dhts[1].self)
Jeromy's avatar
Jeromy committed
300 301
	ctxT, cancel = context.WithTimeout(ctx, time.Second*2)
	defer cancel()
Steven Allen's avatar
Steven Allen committed
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 338 339 340 341 342

	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")
343 344 345 346
	if err != nil {
		t.Fatal(err)
	}

Steven Allen's avatar
Steven Allen committed
347 348
	if string(val) != "world" {
		t.Fatalf("Expected 'world' got '%s'", string(val))
349
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
350 351
}

352 353 354 355 356 357 358 359 360 361 362 363
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()

364
	dhtA.Validator.(record.NamespacedValidator)["v"] = testValidator{}
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 398 399 400 401 402 403 404
	dhtB.Validator.(record.NamespacedValidator)["v"] = blankValidator{}

	connect(t, ctx, dhtA, dhtB)

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

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

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

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

Aarsh Shah's avatar
Aarsh Shah committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
func TestContextShutDown(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dht := setupDHT(ctx, t, false)

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

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

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

Łukasz Magiera's avatar
Łukasz Magiera committed
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
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()
456
	valCh, err := dhtA.SearchValue(ctxT, "/v/hello", Quorum(-1))
457 458 459
	if err != nil {
		t.Fatal(err)
	}
Łukasz Magiera's avatar
Łukasz Magiera committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

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

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
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))
	}

523
	sort.Slice(vals, func(i, j int) bool { return string(vals[i].Val) < string(vals[j].Val) })
524 525 526 527 528 529 530 531 532

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

533 534 535 536 537 538 539 540 541 542 543 544 545
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{}
546
	dhtB.Validator.(record.NamespacedValidator)["v"] = testValidator{}
547 548 549 550

	connect(t, ctx, dhtA, dhtB)

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

553 554 555 556
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
		err := dhtA.PutValue(ctxT, "/v/hello", []byte(val))
		if err != nil {
557
			t.Error(err)
558 559 560 561 562 563
		}

		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
564
			t.Errorf("Set/Get %v: Expected '%v' error but got '%v'", val, experr, err)
565 566
		} else if err == nil && string(valb) != exp {
			t.Errorf("Expected '%v' got '%s'", exp, string(valb))
567 568 569 570 571 572 573 574 575 576 577 578 579
		}
	}

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

580
func TestInvalidMessageSenderTracking(t *testing.T) {
Steven Allen's avatar
Steven Allen committed
581 582 583
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

584
	dht := setupDHT(ctx, t, false)
Steven Allen's avatar
Steven Allen committed
585 586
	defer dht.Close()

587
	foo := peer.ID("asdasd")
Steven Allen's avatar
Steven Allen committed
588
	_, err := dht.messageSenderForPeer(ctx, foo)
589 590 591 592 593
	if err == nil {
		t.Fatal("that shouldnt have succeeded")
	}

	dht.smlk.Lock()
Steven Allen's avatar
Steven Allen committed
594 595 596 597
	mscnt := len(dht.strmap)
	dht.smlk.Unlock()

	if mscnt > 0 {
598 599 600 601
		t.Fatal("should have no message senders in map")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
602 603
func TestProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Steven Allen's avatar
Steven Allen committed
604 605
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
606

607
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
608 609
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
610
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
611
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
612 613 614
		}
	}()

615 616 617
	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
618

619
	for _, k := range testCaseCids {
Matt Joiner's avatar
Matt Joiner committed
620
		logger.Debugf("announcing provider for %s", k)
Jeromy's avatar
Jeromy committed
621
		if err := dhts[3].Provide(ctx, k, true); err != nil {
622 623
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
624 625
	}

626 627 628 629
	// what is this timeout for? was 60ms before.
	time.Sleep(time.Millisecond * 6)

	n := 0
630
	for _, c := range testCaseCids {
631 632
		n = (n + 1) % 3

Matt Joiner's avatar
Matt Joiner committed
633
		logger.Debugf("getting providers for %s from %d", c, n)
Jeromy's avatar
Jeromy committed
634 635
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
		defer cancel()
636
		provchan := dhts[n].FindProvidersAsync(ctxT, c, 1)
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651

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

657
	dhts := setupDHTS(t, ctx, 4)
Jeromy's avatar
Jeromy committed
658 659 660 661 662 663 664 665 666 667 668 669
	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
670
		logger.Debugf("announcing provider for %s", k)
Jeromy's avatar
Jeromy committed
671 672 673 674 675 676 677 678 679
		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++ {
680
			provs := dhts[i].providers.GetProviders(ctx, c.Hash())
Jeromy's avatar
Jeromy committed
681 682 683 684 685 686 687
			if len(provs) > 0 {
				t.Fatal("shouldnt know this")
			}
		}
	}
}

688 689 690 691 692 693 694 695 696 697
// 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 {
698
				//t.Logf("routing table for %s only has %d peers (should have >%d)", dht.self, rtlen, minPeers)
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
				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
715
			logger.Debugf("did not reach well-formed routing tables by %s", timeout)
716 717 718 719 720 721 722 723 724 725 726
			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.
727
	fmt.Printf("checking routing table of %d\n", len(dhts))
728 729 730 731 732 733 734
	for _, dht := range dhts {
		fmt.Printf("checking routing table of %s\n", dht.self)
		dht.routingTable.Print()
		fmt.Println("")
	}
}

735
func TestRefresh(t *testing.T) {
736 737 738 739
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
740 741
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
742

743
	nDHTs := 30
744
	dhts := setupDHTS(t, ctx, nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
745 746 747
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
748
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
749 750 751 752 753 754 755 756
		}
	}()

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

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

763
	go func() {
Steven Allen's avatar
Steven Allen committed
764
		for ctxT.Err() == nil {
765 766
			bootstrap(t, ctxT, dhts)

Steven Allen's avatar
Steven Allen committed
767
			// wait a bit.
768 769 770
			select {
			case <-time.After(50 * time.Millisecond):
				continue // being explicit
Steven Allen's avatar
Steven Allen committed
771
			case <-ctxT.Done():
772 773 774 775 776
				return
			}
		}
	}()

777
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
Steven Allen's avatar
Steven Allen committed
778
	cancelT()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
779

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
780 781
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
782 783 784 785
		printRoutingTables(dhts)
	}
}

786
func TestRefreshBelowMinRTThreshold(t *testing.T) {
Aarsh Shah's avatar
Aarsh Shah committed
787
	ctx := context.Background()
788 789 790 791 792 793 794 795 796 797 798 799

	// enable auto bootstrap on A
	dhtA, err := New(
		ctx,
		bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)),
		opts.Client(false),
		opts.NamespacedValidator("v", blankValidator{}),
	)
	if err != nil {
		t.Fatal(err)
	}

Aarsh Shah's avatar
Aarsh Shah committed
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
	dhtB := setupDHT(ctx, t, false)
	dhtC := setupDHT(ctx, t, false)

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

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

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

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

	// we ONLY init bootstrap on A
818
	dhtA.RefreshRoutingTable()
Aarsh Shah's avatar
Aarsh Shah committed
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
	// and wait for one round to complete i.e. A should be connected to both B & C
	waitForWellFormedTables(t, []*IpfsDHT{dhtA}, 2, 2, 20*time.Second)

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

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

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

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

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

846 847 848 849 850 851
// Check to make sure we re-fill the routing table from connected peers when it
// completely empties.
func TestEmptyTable(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

852
	nDHTs := 50
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
	dhts := setupDHTS(t, ctx, nDHTs)
	defer func() {
		for _, dht := range dhts {
			dht.Close()
			defer dht.host.Close()
		}
	}()

	t.Logf("dhts are not connected. %d", nDHTs)
	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 := 1; i < nDHTs; i++ {
		connectNoSync(t, ctx, dhts[0], dhts[i])
	}

	// Wait till the routing table stabilizes.
	oldSize := dhts[0].routingTable.Size()
	for {
		time.Sleep(time.Millisecond)
		newSize := dhts[0].routingTable.Size()
		if oldSize == newSize {
			break
		}
		oldSize = newSize
	}

884 885 886 887
	// remove any one peer from the RT so we don't  end up disconnecting all of them if the RT
	// already has all peers we are connected to
	dhts[0].routingTable.Remove(dhts[0].routingTable.ListPeers()[0])

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
	if u.Debug {
		printRoutingTables(dhts[:1])
	}

	// Disconnect from all peers that _were_ in the routing table.
	routingTablePeers := make(map[peer.ID]bool, nDHTs)
	for _, p := range dhts[0].RoutingTable().ListPeers() {
		routingTablePeers[p] = true
	}

	oldDHTs := dhts[1:]
	dhts = dhts[:1]
	for _, dht := range oldDHTs {
		if routingTablePeers[dht.Host().ID()] {
			dhts[0].Host().Network().ClosePeer(dht.host.ID())
			dht.Close()
			dht.host.Close()
		} else {
			dhts = append(dhts, dht)
		}
	}

	// we should now _re-add_ some peers to the routing table
	for i := 0; i < 100; i++ {
		if dhts[0].routingTable.Size() > 0 {
			return
		}
		time.Sleep(time.Millisecond)
	}
	if u.Debug {
		printRoutingTables(dhts[:1])
	}
	t.Fatal("routing table shouldn't have been empty")
}

923
func TestPeriodicRefresh(t *testing.T) {
924 925 926
	if ci.IsRunning() {
		t.Skip("skipping on CI. highly timing dependent")
	}
927 928 929 930
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
931 932
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
933 934

	nDHTs := 30
935
	dhts := setupDHTS(t, ctx, nDHTs)
936 937 938 939 940 941 942
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
			defer dhts[i].host.Close()
		}
	}()

943
	t.Logf("dhts are not connected. %d", nDHTs)
944 945 946 947 948 949 950 951 952 953 954
	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)])
	}

955
	t.Logf("DHTs are now connected to 1-2 others. %d", nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
956
	for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
957
		rtlen := dht.routingTable.Size()
958 959
		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
960
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
961
	}
962

963 964 965 966
	if u.Debug {
		printRoutingTables(dhts)
	}

967
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
Matt Joiner's avatar
Matt Joiner committed
968
	for _, dht := range dhts {
969
		dht.RefreshRoutingTable()
970
	}
971 972 973

	// 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.
974
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
975 976 977

	if u.Debug {
		printRoutingTables(dhts)
978
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
979 980
}

981 982
func TestProvidesMany(t *testing.T) {
	t.Skip("this test doesn't work")
Steven Allen's avatar
Steven Allen committed
983 984
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
985 986

	nDHTs := 40
987
	dhts := setupDHTS(t, ctx, nDHTs)
988 989 990
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
991
			defer dhts[i].host.Close()
992 993 994 995 996 997 998 999
		}
	}()

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

1000
	<-time.After(100 * time.Millisecond)
1001
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
Jeromy's avatar
Jeromy committed
1002 1003
	ctxT, cancel := context.WithTimeout(ctx, 20*time.Second)
	defer cancel()
1004 1005
	bootstrap(t, ctxT, dhts)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1006 1007 1008 1009 1010 1011 1012 1013
	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("")
		}
1014
	}
1015

1016
	providers := make(map[cid.Cid]peer.ID)
1017

1018
	d := 0
1019
	for _, c := range testCaseCids {
1020 1021
		d = (d + 1) % len(dhts)
		dht := dhts[d]
1022
		providers[c] = dht.self
1023

1024
		t.Logf("announcing provider for %s", c)
Jeromy's avatar
Jeromy committed
1025
		if err := dht.Provide(ctx, c, true); err != nil {
1026 1027
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1028 1029
	}

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

1033 1034
	errchan := make(chan error)

Jeromy's avatar
Jeromy committed
1035 1036
	ctxT, cancel = context.WithTimeout(ctx, 5*time.Second)
	defer cancel()
1037 1038

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

1042
		expected := providers[k]
1043

1044 1045 1046
		provchan := dht.FindProvidersAsync(ctxT, k, 1)
		select {
		case prov := <-provchan:
1047 1048
			actual := prov.ID
			if actual == "" {
1049
				errchan <- fmt.Errorf("Got back nil provider (%s at %s)", k, dht.self)
1050 1051 1052
			} else if actual != expected {
				errchan <- fmt.Errorf("Got back wrong provider (%s != %s) (%s at %s)",
					expected, actual, k, dht.self)
1053 1054 1055
			}
		case <-ctxT.Done():
			errchan <- fmt.Errorf("Did not get a provider back (%s at %s)", k, dht.self)
Jeromy's avatar
Jeromy committed
1056
		}
1057 1058
	}

1059
	for _, c := range testCaseCids {
1060 1061
		// everyone should be able to find it...
		for _, dht := range dhts {
Matt Joiner's avatar
Matt Joiner committed
1062
			logger.Debugf("getting providers for %s at %s", c, dht.self)
1063
			wg.Add(1)
1064
			go getProvider(dht, c)
1065
		}
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
	}

	// 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
1076 1077 1078
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1079
func TestProvidesAsync(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1080
	// t.Skip("skipping test to debug another")
1081 1082 1083
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1084

Steven Allen's avatar
Steven Allen committed
1085 1086
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1087

1088
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1089 1090
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1091
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1092
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1093 1094 1095
		}
	}()

1096 1097 1098
	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
1099

Jeromy's avatar
Jeromy committed
1100
	err := dhts[3].Provide(ctx, testCaseCids[0], true)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1101 1102 1103 1104 1105 1106
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 60)

Jeromy's avatar
Jeromy committed
1107 1108
	ctxT, cancel := context.WithTimeout(ctx, time.Millisecond*300)
	defer cancel()
1109
	provs := dhts[0].FindProvidersAsync(ctxT, testCaseCids[0], 5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1110
	select {
Jeromy's avatar
Jeromy committed
1111 1112 1113 1114
	case p, ok := <-provs:
		if !ok {
			t.Fatal("Provider channel was closed...")
		}
1115
		if p.ID == "" {
Jeromy's avatar
Jeromy committed
1116 1117
			t.Fatal("Got back nil provider!")
		}
1118
		if p.ID != dhts[3].self {
1119
			t.Fatalf("got a provider, but not the right one. %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1120
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1121
	case <-ctxT.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1122 1123 1124 1125
		t.Fatal("Didnt get back providers")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1126
func TestLayeredGet(t *testing.T) {
1127 1128
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
1129

1130
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1131 1132
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1133
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1134
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1135 1136 1137
		}
	}()

1138 1139
	connect(t, ctx, dhts[0], dhts[1])
	connect(t, ctx, dhts[1], dhts[2])
1140
	connect(t, ctx, dhts[2], dhts[3])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1141

1142
	err := dhts[3].PutValue(ctx, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1143 1144 1145 1146
	if err != nil {
		t.Fatal(err)
	}

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

Jeromy's avatar
Jeromy committed
1149 1150
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
1151 1152 1153
	val, err := dhts[0].GetValue(ctxT, "/v/hello")
	if err != nil {
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1154
	}
1155 1156 1157

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

1161 1162 1163 1164 1165 1166 1167 1168
func TestUnfindablePeer(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

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

1169
	dhts := setupDHTS(t, ctx, 4)
1170 1171 1172
	defer func() {
		for i := 0; i < 4; i++ {
			dhts[i].Close()
1173
			dhts[i].Host().Close()
1174 1175 1176 1177 1178 1179 1180 1181
		}
	}()

	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.
1182 1183
	dhts[1].host.Peerstore().ClearAddrs(dhts[2].PeerID())
	dhts[1].host.Peerstore().AddAddr(dhts[2].PeerID(), dhts[0].Host().Addrs()[0], time.Minute)
1184 1185 1186

	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
1187
	_, err := dhts[0].FindPeer(ctxT, dhts[3].PeerID())
1188 1189 1190 1191 1192 1193 1194 1195
	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
1196
func TestFindPeer(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1197
	// t.Skip("skipping test to debug another")
1198 1199 1200
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1201

Steven Allen's avatar
Steven Allen committed
1202 1203
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1204

1205
	dhts := setupDHTS(t, ctx, 4)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1206 1207
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1208
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1209
			dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1210 1211 1212
		}
	}()

1213 1214 1215
	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
1216

Jeromy's avatar
Jeromy committed
1217 1218
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
1219
	p, err := dhts[0].FindPeer(ctxT, dhts[2].PeerID())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1220 1221 1222 1223
	if err != nil {
		t.Fatal(err)
	}

1224
	if p.ID == "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1225 1226 1227
		t.Fatal("Failed to find peer.")
	}

1228
	if p.ID != dhts[2].PeerID() {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1229 1230 1231
		t.Fatal("Didnt find expected peer.")
	}
}
1232

1233
func TestFindPeersConnectedToPeer(t *testing.T) {
1234 1235
	t.Skip("not quite correct (see note)")

1236 1237 1238 1239
	if testing.Short() {
		t.SkipNow()
	}

Steven Allen's avatar
Steven Allen committed
1240 1241
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
1242

1243
	dhts := setupDHTS(t, ctx, 4)
1244 1245 1246
	defer func() {
		for i := 0; i < 4; i++ {
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1247
			dhts[i].host.Close()
1248 1249 1250 1251 1252
		}
	}()

	// topology:
	// 0-1, 1-2, 1-3, 2-3
1253 1254 1255 1256
	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])
1257 1258 1259 1260 1261 1262

	// 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
1263 1264
	ctxT, cancel := context.WithTimeout(ctx, time.Second)
	defer cancel()
1265
	pchan, err := dhts[0].FindPeersConnectedToPeer(ctxT, dhts[2].PeerID())
1266 1267 1268 1269
	if err != nil {
		t.Fatal(err)
	}

1270
	// shouldFind := []peer.ID{peers[1], peers[3]}
1271
	var found []*peer.AddrInfo
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
	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
1282
	logger.Warning("TestFindPeersConnectedToPeer is not quite correct")
1283 1284 1285 1286 1287
	if len(found) == 0 {
		t.Fatal("didn't find any peers.")
	}
}

1288
func TestConnectCollision(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1289
	// t.Skip("skipping test to debug another")
1290 1291 1292
	if testing.Short() {
		t.SkipNow()
	}
1293 1294 1295
	if travisci.IsRunning() {
		t.Skip("Skipping on Travis-CI.")
	}
1296

1297
	runTimes := 10
1298

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

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

1304 1305
		dhtA := setupDHT(ctx, t, false)
		dhtB := setupDHT(ctx, t, false)
1306

1307 1308
		addrA := dhtA.peerstore.Addrs(dhtA.self)[0]
		addrB := dhtB.peerstore.Addrs(dhtB.self)[0]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1309

1310 1311
		peerA := dhtA.self
		peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1312

1313
		errs := make(chan error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1314
		go func() {
1315 1316
			dhtA.peerstore.AddAddr(peerB, addrB, peerstore.TempAddrTTL)
			pi := peer.AddrInfo{ID: peerB}
Jeromy's avatar
Jeromy committed
1317
			err := dhtA.host.Connect(ctx, pi)
1318
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1319 1320
		}()
		go func() {
1321 1322
			dhtB.peerstore.AddAddr(peerA, addrA, peerstore.TempAddrTTL)
			pi := peer.AddrInfo{ID: peerA}
Jeromy's avatar
Jeromy committed
1323
			err := dhtB.host.Connect(ctx, pi)
1324
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1325 1326
		}()

1327
		timeout := time.After(5 * time.Second)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1328
		select {
1329 1330 1331 1332
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1333 1334 1335 1336
		case <-timeout:
			t.Fatal("Timeout received!")
		}
		select {
1337 1338 1339 1340
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1341 1342 1343 1344
		case <-timeout:
			t.Fatal("Timeout received!")
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1345 1346
		dhtA.Close()
		dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1347 1348
		dhtA.host.Close()
		dhtB.host.Close()
Steven Allen's avatar
Steven Allen committed
1349
		cancel()
Jeromy's avatar
Jeromy committed
1350
	}
1351
}
1352 1353 1354 1355 1356

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

1357
	d := setupDHT(ctx, t, false)
1358 1359 1360 1361 1362 1363

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

1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
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))
	}
}

1410 1411 1412 1413 1414 1415 1416 1417 1418
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)

1419
	c := testCaseCids[0]
1420
	p := peer.ID("TestPeer")
1421
	a.providers.AddProvider(ctx, c.Hash(), p)
1422
	time.Sleep(time.Millisecond * 5) // just in case...
1423

1424
	provs, err := b.FindProviders(ctx, c)
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
	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
1436 1437 1438 1439 1440 1441 1442 1443 1444
	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) {
1445
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
Steven Allen's avatar
Steven Allen committed
1446 1447 1448 1449 1450 1451
	defer cancel()

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

1452 1453
	connectNoSync(t, ctx, b, a)
	connectNoSync(t, ctx, c, a)
Steven Allen's avatar
Steven Allen committed
1454 1455

	// Can't use `connect` because b and c are only clients.
1456 1457
	wait(t, ctx, b, a)
	wait(t, ctx, c, a)
Steven Allen's avatar
Steven Allen committed
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470

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

Matt Joiner's avatar
Matt Joiner committed
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
func minInt(a, b int) int {
	if a < b {
		return a
	} else {
		return b
	}
}

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

1485
func TestFindPeerQuery(t *testing.T) {
Matt Joiner's avatar
Matt Joiner committed
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
	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
) {
1500 1501 1502
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

1503
	dhts := setupDHTS(t, ctx, 1+bootstrappers+leafs)
1504
	defer func() {
Matt Joiner's avatar
Matt Joiner committed
1505 1506 1507
		for _, d := range dhts {
			d.Close()
			d.host.Close()
1508 1509 1510
		}
	}()

Jeromy's avatar
Jeromy committed
1511
	mrand := rand.New(rand.NewSource(42))
1512 1513
	guy := dhts[0]
	others := dhts[1:]
Matt Joiner's avatar
Matt Joiner committed
1514 1515 1516 1517
	for i := 0; i < bootstrappers; i++ {
		for j := 0; j < bootstrapperLeafConns; j++ {
			v := mrand.Intn(leafs)
			connect(t, ctx, others[i], others[bootstrappers+v])
1518 1519 1520
		}
	}

Matt Joiner's avatar
Matt Joiner committed
1521
	for i := 0; i < bootstrappers; i++ {
1522 1523 1524
		connect(t, ctx, guy, others[i])
	}

Matt Joiner's avatar
Matt Joiner committed
1525 1526 1527 1528 1529
	var reachableIds []peer.ID
	for i, d := range dhts {
		lp := len(d.host.Network().Peers())
		//t.Log(i, lp)
		if i != 0 && lp > 0 {
1530
			reachableIds = append(reachableIds, d.PeerID())
Matt Joiner's avatar
Matt Joiner committed
1531 1532 1533 1534
		}
	}
	t.Logf("%d reachable ids", len(reachableIds))

1535 1536 1537
	val := "foobar"
	rtval := kb.ConvertKey(val)

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

Matt Joiner's avatar
Matt Joiner committed
1541
	assert.Len(t, guy.host.Network().Peers(), bootstrappers)
1542 1543

	out, err := guy.GetClosestPeers(ctx, val)
Matt Joiner's avatar
Matt Joiner committed
1544
	require.NoError(t, err)
1545 1546 1547 1548 1549 1550

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

Jeromy's avatar
Jeromy committed
1551
	sort.Sort(peer.IDSlice(outpeers))
Steven Allen's avatar
Steven Allen committed
1552

Matt Joiner's avatar
Matt Joiner committed
1553 1554
	exp := kb.SortClosestPeers(reachableIds, rtval)[:minInt(KValue, len(reachableIds))]
	t.Logf("got %d peers", len(outpeers))
1555
	got := kb.SortClosestPeers(outpeers, rtval)
Jeromy's avatar
Jeromy committed
1556

Matt Joiner's avatar
Matt Joiner committed
1557
	assert.EqualValues(t, exp, got)
1558 1559
}

1560 1561 1562 1563 1564
func TestFindClosestPeers(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	nDHTs := 30
1565
	dhts := setupDHTS(t, ctx, nDHTs)
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
	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)
	}
}
1592

1593 1594
func TestProvideDisabled(t *testing.T) {
	k := testCaseCids[0]
1595
	kHash := k.Hash()
1596 1597 1598 1599 1600 1601 1602
	for i := 0; i < 3; i++ {
		enabledA := (i & 0x1) > 0
		enabledB := (i & 0x2) > 0
		t.Run(fmt.Sprintf("a=%v/b=%v", enabledA, enabledB), func(t *testing.T) {
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()

1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
			var (
				optsA, optsB []opts.Option
			)
			if !enabledA {
				optsA = append(optsA, opts.DisableProviders())
			}
			if !enabledB {
				optsB = append(optsB, opts.DisableProviders())
			}

			dhtA := setupDHT(ctx, t, false, optsA...)
			dhtB := setupDHT(ctx, t, false, optsB...)
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635

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

			connect(t, ctx, dhtA, dhtB)

			err := dhtB.Provide(ctx, k, true)
			if enabledB {
				if err != nil {
					t.Fatal("put should have succeeded on node B", err)
				}
			} else {
				if err != routing.ErrNotSupported {
					t.Fatal("should not have put the value to node B", err)
				}
				_, err = dhtB.FindProviders(ctx, k)
				if err != routing.ErrNotSupported {
					t.Fatal("get should have failed on node B")
				}
1636
				provs := dhtB.providers.GetProviders(ctx, kHash)
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
				if len(provs) != 0 {
					t.Fatal("node B should not have found local providers")
				}
			}

			provs, err := dhtA.FindProviders(ctx, k)
			if enabledA {
				if len(provs) != 0 {
					t.Fatal("node A should not have found providers")
				}
			} else {
				if err != routing.ErrNotSupported {
					t.Fatal("node A should not have found providers")
				}
			}
1652
			provAddrs := dhtA.providers.GetProviders(ctx, kHash)
1653 1654 1655 1656 1657 1658 1659
			if len(provAddrs) != 0 {
				t.Fatal("node A should not have found local providers")
			}
		})
	}
}

1660
func TestGetSetPluggedProtocol(t *testing.T) {
1661 1662 1663
	t.Run("PutValue/GetValue - same protocol", func(t *testing.T) {
		ctx, cancel := context.WithCancel(context.Background())
		defer cancel()
1664

1665 1666 1667 1668
		os := []opts.Option{
			opts.Protocols("/esh/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
1669
			opts.DisableAutoRefresh(),
1670
		}
1671

Steven Allen's avatar
Steven Allen committed
1672
		dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
1673 1674 1675
		if err != nil {
			t.Fatal(err)
		}
1676

Steven Allen's avatar
Steven Allen committed
1677
		dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), os...)
1678 1679 1680
		if err != nil {
			t.Fatal(err)
		}
1681

1682
		connect(t, ctx, dhtA, dhtB)
1683

1684
		ctxT, cancel := context.WithTimeout(ctx, time.Second)
1685
		defer cancel()
1686 1687 1688
		if err := dhtA.PutValue(ctxT, "/v/cat", []byte("meow")); err != nil {
			t.Fatal(err)
		}
1689

1690 1691 1692 1693
		value, err := dhtB.GetValue(ctxT, "/v/cat")
		if err != nil {
			t.Fatal(err)
		}
1694

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

1700 1701
	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)
1702 1703
		defer cancel()

Steven Allen's avatar
Steven Allen committed
1704
		dhtA, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), []opts.Option{
1705 1706 1707
			opts.Protocols("/esh/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
1708
			opts.DisableAutoRefresh(),
1709
		}...)
1710 1711 1712 1713
		if err != nil {
			t.Fatal(err)
		}

Steven Allen's avatar
Steven Allen committed
1714
		dhtB, err := New(ctx, bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport)), []opts.Option{
1715 1716 1717
			opts.Protocols("/lsr/dht"),
			opts.Client(false),
			opts.NamespacedValidator("v", blankValidator{}),
1718
			opts.DisableAutoRefresh(),
1719
		}...)
1720 1721 1722 1723
		if err != nil {
			t.Fatal(err)
		}

1724
		connectNoSync(t, ctx, dhtA, dhtB)
1725

1726 1727 1728 1729 1730 1731 1732
		// 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") {
1733
			t.Fatalf("put should not have been able to find any peers in routing table, err:'%v'", err)
1734 1735
		}

1736 1737
		_, err = dhtB.GetValue(ctx, "/v/cat")
		if err == nil || !strings.Contains(err.Error(), "failed to find any peer in table") {
1738
			t.Fatalf("get should not have been able to find any peers in routing table, err:'%v'", err)
1739
		}
1740
	})
1741
}
1742 1743 1744 1745 1746

func TestPing(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ds := setupDHTS(t, ctx, 2)
1747
	ds[0].Host().Peerstore().AddAddrs(ds[1].PeerID(), ds[1].Host().Addrs(), peerstore.AddressTTL)
1748 1749 1750 1751 1752 1753 1754 1755
	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)
1756
	pinger.Host().Peerstore().AddAddrs(client.PeerID(), client.Host().Addrs(), peerstore.AddressTTL)
1757 1758 1759
	err := pinger.Ping(context.Background(), client.PeerID())
	assert.True(t, xerrors.Is(err, multistream.ErrNotSupported))
}