dht_test.go 19.3 KB
Newer Older
1 2
package dht

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
3
import (
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
4
	"bytes"
5
	"fmt"
6
	"math/rand"
7
	"sort"
8
	"sync"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9
	"testing"
10
	"time"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11

12 13
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"

14 15 16
	ds "github.com/ipfs/go-datastore"
	dssync "github.com/ipfs/go-datastore/sync"
	u "github.com/ipfs/go-ipfs-util"
George Antoniadis's avatar
George Antoniadis committed
17
	key "github.com/ipfs/go-key"
18 19 20
	peer "github.com/ipfs/go-libp2p-peer"
	pstore "github.com/ipfs/go-libp2p-peerstore"
	ma "github.com/jbenet/go-multiaddr"
George Antoniadis's avatar
George Antoniadis committed
21 22 23 24 25
	record "github.com/libp2p/go-libp2p-record"
	routing "github.com/libp2p/go-libp2p-routing"
	netutil "github.com/libp2p/go-libp2p/p2p/test/util"
	ci "github.com/libp2p/go-testutil/ci"
	travisci "github.com/libp2p/go-testutil/ci/travis"
26
	context "golang.org/x/net/context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27 28
)

29
var testCaseValues = map[key.Key][]byte{}
30 31 32 33 34 35

func init() {
	testCaseValues["hello"] = []byte("world")
	for i := 0; i < 100; i++ {
		k := fmt.Sprintf("%d -- key", i)
		v := fmt.Sprintf("%d -- value", i)
36
		testCaseValues[key.Key(k)] = []byte(v)
37 38 39
	}
}

40
func setupDHT(ctx context.Context, t *testing.T, client bool) *IpfsDHT {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
	h := netutil.GenHostSwarm(t, ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42

43
	dss := dssync.MutexWrap(ds.NewMapDatastore())
44 45 46 47 48 49
	var d *IpfsDHT
	if client {
		d = NewDHTClient(ctx, h, dss)
	} else {
		d = NewDHT(ctx, h, dss)
	}
50

51
	d.Validator["v"] = &record.ValidChecker{
52
		Func: func(key.Key, []byte) error {
53 54 55
			return nil
		},
		Sign: false,
Jeromy's avatar
Jeromy committed
56
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57 58 59
	return d
}

60 61
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
62
	dhts := make([]*IpfsDHT, n)
63 64
	peers := make([]peer.ID, n)

65 66 67
	sanityAddrsMap := make(map[string]struct{})
	sanityPeersMap := make(map[string]struct{})

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68
	for i := 0; i < n; i++ {
69
		dhts[i] = setupDHT(ctx, t, false)
70
		peers[i] = dhts[i].self
71
		addrs[i] = dhts[i].peerstore.Addrs(dhts[i].self)[0]
72 73

		if _, lol := sanityAddrsMap[addrs[i].String()]; lol {
Jakub Sztandera's avatar
Jakub Sztandera committed
74
			t.Fatal("While setting up DHTs address got duplicated.")
75 76 77 78
		} else {
			sanityAddrsMap[addrs[i].String()] = struct{}{}
		}
		if _, lol := sanityPeersMap[peers[i].String()]; lol {
Jakub Sztandera's avatar
Jakub Sztandera committed
79
			t.Fatal("While setting up DHTs peerid got duplicated.")
80 81 82
		} else {
			sanityPeersMap[peers[i].String()] = struct{}{}
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83 84 85 86 87
	}

	return addrs, peers, dhts
}

88
func connectNoSync(t *testing.T, ctx context.Context, a, b *IpfsDHT) {
89
	idB := b.self
90
	addrB := b.peerstore.Addrs(idB)
91 92
	if len(addrB) == 0 {
		t.Fatal("peers setup incorrectly: no local address")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93
	}
94

Jeromy's avatar
Jeromy committed
95 96
	a.peerstore.AddAddrs(idB, addrB, pstore.TempAddrTTL)
	pi := pstore.PeerInfo{ID: idB}
Jeromy's avatar
Jeromy committed
97
	if err := a.host.Connect(ctx, pi); err != nil {
98
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
99
	}
100 101 102 103
}

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

105 106
	// loop until connection notification has been received.
	// under high load, this may not happen as immediately as we would like.
107 108 109 110 111 112 113
	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
114 115
}

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

118
	ctx, cancel := context.WithCancel(ctx)
Richard Littauer's avatar
Richard Littauer committed
119
	log.Debugf("Bootstrapping DHTs...")
120 121 122 123 124 125

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

126 127 128 129
	var cfg BootstrapConfig
	cfg = DefaultBootstrapConfig
	cfg.Queries = 3

130 131 132
	start := rand.Intn(len(dhts)) // randomize to decrease bias.
	for i := range dhts {
		dht := dhts[(start+i)%len(dhts)]
133
		dht.runBootstrap(ctx, cfg)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134
	}
135
	cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136 137
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138
func TestValueGetSet(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139 140
	// t.Skip("skipping test to debug another")

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141
	ctx := context.Background()
142

143 144
	dhtA := setupDHT(ctx, t, false)
	dhtB := setupDHT(ctx, t, false)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145

146 147
	defer dhtA.Close()
	defer dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
148 149
	defer dhtA.host.Close()
	defer dhtB.host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
150

151
	vf := &record.ValidChecker{
152
		Func: func(key.Key, []byte) error {
153 154 155
			return nil
		},
		Sign: false,
Jeromy's avatar
Jeromy committed
156
	}
157 158 159 160
	nulsel := func(_ key.Key, bs [][]byte) (int, error) {
		return 0, nil
	}

161 162
	dhtA.Validator["v"] = vf
	dhtB.Validator["v"] = vf
163 164
	dhtA.Selector["v"] = nulsel
	dhtB.Selector["v"] = nulsel
Jeromy's avatar
Jeromy committed
165

166
	connect(t, ctx, dhtA, dhtB)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
167

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
168
	ctxT, _ := context.WithTimeout(ctx, time.Second)
169
	dhtA.PutValue(ctxT, "/v/hello", []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
171
	ctxT, _ = context.WithTimeout(ctx, time.Second*2)
Jeromy's avatar
Jeromy committed
172
	val, err := dhtA.GetValue(ctxT, "/v/hello")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
173 174 175 176 177 178 179 180
	if err != nil {
		t.Fatal(err)
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
181
	ctxT, _ = context.WithTimeout(ctx, time.Second*2)
Jeromy's avatar
Jeromy committed
182
	val, err = dhtB.GetValue(ctxT, "/v/hello")
183 184 185 186 187 188 189
	if err != nil {
		t.Fatal(err)
	}

	if string(val) != "world" {
		t.Fatalf("Expected 'world' got '%s'", string(val))
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190 191
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192 193
func TestProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
194
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
195

196
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
197 198
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
199
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
200
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201 202 203
		}
	}()

204 205 206
	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
207

208
	for k, v := range testCaseValues {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
209
		log.Debugf("adding local values for %s = %s", k, v)
Jeromy's avatar
Jeromy committed
210 211 212 213 214 215 216
		sk := dhts[3].peerstore.PrivKey(dhts[3].self)
		rec, err := record.MakePutRecord(sk, k, v, false)
		if err != nil {
			t.Fatal(err)
		}

		err = dhts[3].putLocal(k, rec)
217 218 219 220 221 222 223 224
		if err != nil {
			t.Fatal(err)
		}

		bits, err := dhts[3].getLocal(k)
		if err != nil {
			t.Fatal(err)
		}
225
		if !bytes.Equal(bits.GetValue(), v) {
226
			t.Fatalf("didn't store the right bits (%s, %s)", k, v)
227
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
228 229
	}

rht's avatar
rht committed
230
	for k := range testCaseValues {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
231
		log.Debugf("announcing provider for %s", k)
232 233 234
		if err := dhts[3].Provide(ctx, k); err != nil {
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235 236
	}

237 238 239 240
	// what is this timeout for? was 60ms before.
	time.Sleep(time.Millisecond * 6)

	n := 0
rht's avatar
rht committed
241
	for k := range testCaseValues {
242 243
		n = (n + 1) % 3

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
244
		log.Debugf("getting providers for %s from %d", k, n)
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
		ctxT, _ := context.WithTimeout(ctx, time.Second)
		provchan := dhts[n].FindProvidersAsync(ctxT, k, 1)

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

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
// 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:
289
			log.Debugf("did not reach well-formed routing tables by %s", timeout)
290 291 292 293 294 295 296 297 298 299 300
			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.
301
	fmt.Printf("checking routing table of %d\n", len(dhts))
302 303 304 305 306 307 308
	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
309
func TestBootstrap(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
310
	// t.Skip("skipping test to debug another")
311 312 313 314
	if testing.Short() {
		t.SkipNow()
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
315 316
	ctx := context.Background()

317
	nDHTs := 30
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
318 319 320 321
	_, _, 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
322
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
323 324 325 326 327 328 329 330
		}
	}()

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

331
	<-time.After(100 * time.Millisecond)
332 333 334 335
	// bootstrap a few times until we get good tables.
	stop := make(chan struct{})
	go func() {
		for {
336
			t.Logf("bootstrapping them so they find each other %d", nDHTs)
337 338 339 340 341 342 343 344 345 346 347 348
			ctxT, _ := context.WithTimeout(ctx, 5*time.Second)
			bootstrap(t, ctxT, dhts)

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

349
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
350
	close(stop)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
351

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
352 353
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
354 355 356 357 358 359
		printRoutingTables(dhts)
	}
}

func TestPeriodicBootstrap(t *testing.T) {
	// t.Skip("skipping test to debug another")
360 361 362
	if ci.IsRunning() {
		t.Skip("skipping on CI. highly timing dependent")
	}
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
	if testing.Short() {
		t.SkipNow()
	}

	ctx := context.Background()

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

	// signal amplifier
	amplify := func(signal chan time.Time, other []chan time.Time) {
		for t := range signal {
			for _, s := range other {
				s <- t
			}
		}
		for _, s := range other {
			close(s)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
387 388 389
		}
	}

390 391 392
	signal := make(chan time.Time)
	allSignals := []chan time.Time{}

393 394 395 396
	var cfg BootstrapConfig
	cfg = DefaultBootstrapConfig
	cfg.Queries = 5

397 398 399 400
	// kick off periodic bootstrappers with instrumented signals.
	for _, dht := range dhts {
		s := make(chan time.Time)
		allSignals = append(allSignals, s)
401
		dht.BootstrapOnSignal(cfg, s)
402 403 404
	}
	go amplify(signal, allSignals)

405
	t.Logf("dhts are not connected. %d", nDHTs)
406 407 408 409 410 411 412 413 414 415 416
	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)])
	}

417
	t.Logf("DHTs are now connected to 1-2 others. %d", nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
418
	for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
419
		rtlen := dht.routingTable.Size()
420 421
		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
422
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
423
	}
424

425 426 427 428
	if u.Debug {
		printRoutingTables(dhts)
	}

429
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
430 431 432 433
	signal <- time.Now()

	// 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.
434
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
435 436 437

	if u.Debug {
		printRoutingTables(dhts)
438
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
439 440
}

441 442
func TestProvidesMany(t *testing.T) {
	t.Skip("this test doesn't work")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
443
	// t.Skip("skipping test to debug another")
444 445 446 447 448 449 450
	ctx := context.Background()

	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
451
			defer dhts[i].host.Close()
452 453 454 455 456 457 458 459
		}
	}()

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

460
	<-time.After(100 * time.Millisecond)
461
	t.Logf("bootstrapping them so they find each other. %d", nDHTs)
462
	ctxT, _ := context.WithTimeout(ctx, 20*time.Second)
463 464
	bootstrap(t, ctxT, dhts)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
465 466 467 468 469 470 471 472
	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("")
		}
473
	}
474

475
	var providers = map[key.Key]peer.ID{}
476

477 478 479 480
	d := 0
	for k, v := range testCaseValues {
		d = (d + 1) % len(dhts)
		dht := dhts[d]
481
		providers[k] = dht.self
482 483

		t.Logf("adding local values for %s = %s (on %s)", k, v, dht.self)
Jeromy's avatar
Jeromy committed
484 485 486 487 488 489
		rec, err := record.MakePutRecord(nil, k, v, false)
		if err != nil {
			t.Fatal(err)
		}

		err = dht.putLocal(k, rec)
490 491 492 493 494 495 496 497
		if err != nil {
			t.Fatal(err)
		}

		bits, err := dht.getLocal(k)
		if err != nil {
			t.Fatal(err)
		}
498
		if !bytes.Equal(bits.GetValue(), v) {
499
			t.Fatalf("didn't store the right bits (%s, %s)", k, v)
500 501 502 503 504 505
		}

		t.Logf("announcing provider for %s", k)
		if err := dht.Provide(ctx, k); err != nil {
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
506 507
	}

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

511 512
	errchan := make(chan error)

513
	ctxT, _ = context.WithTimeout(ctx, 5*time.Second)
514 515

	var wg sync.WaitGroup
516
	getProvider := func(dht *IpfsDHT, k key.Key) {
517
		defer wg.Done()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
518

519 520
		expected := providers[k]

521 522 523
		provchan := dht.FindProvidersAsync(ctxT, k, 1)
		select {
		case prov := <-provchan:
524 525
			actual := prov.ID
			if actual == "" {
526
				errchan <- fmt.Errorf("Got back nil provider (%s at %s)", k, dht.self)
527 528 529
			} else if actual != expected {
				errchan <- fmt.Errorf("Got back wrong provider (%s != %s) (%s at %s)",
					expected, actual, k, dht.self)
530 531 532
			}
		case <-ctxT.Done():
			errchan <- fmt.Errorf("Did not get a provider back (%s at %s)", k, dht.self)
Jeromy's avatar
Jeromy committed
533
		}
534 535
	}

rht's avatar
rht committed
536
	for k := range testCaseValues {
537 538
		// everyone should be able to find it...
		for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
539
			log.Debugf("getting providers for %s at %s", k, dht.self)
540 541
			wg.Add(1)
			go getProvider(dht, k)
542
		}
543 544 545 546 547 548 549 550 551 552
	}

	// 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
553 554 555
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
556
func TestProvidesAsync(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
557
	// t.Skip("skipping test to debug another")
558 559 560
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
561

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
562
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
563

564
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
565 566
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
567
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
568
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
569 570 571
		}
	}()

572 573 574
	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
575

576
	k := key.Key("hello")
Jeromy's avatar
Jeromy committed
577 578 579 580 581 582 583 584
	val := []byte("world")
	sk := dhts[3].peerstore.PrivKey(dhts[3].self)
	rec, err := record.MakePutRecord(sk, k, val, false)
	if err != nil {
		t.Fatal(err)
	}

	err = dhts[3].putLocal(k, rec)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
585 586 587 588
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
589
	bits, err := dhts[3].getLocal(k)
590
	if err != nil && bytes.Equal(bits.GetValue(), val) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
591 592 593
		t.Fatal(err)
	}

594
	err = dhts[3].Provide(ctx, key.Key("hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
595 596 597 598 599 600
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 60)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
601
	ctxT, _ := context.WithTimeout(ctx, time.Millisecond*300)
602
	provs := dhts[0].FindProvidersAsync(ctxT, key.Key("hello"), 5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
603
	select {
Jeromy's avatar
Jeromy committed
604 605 606 607
	case p, ok := <-provs:
		if !ok {
			t.Fatal("Provider channel was closed...")
		}
608
		if p.ID == "" {
Jeromy's avatar
Jeromy committed
609 610
			t.Fatal("Got back nil provider!")
		}
611
		if p.ID != dhts[3].self {
612
			t.Fatalf("got a provider, but not the right one. %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
613
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
614
	case <-ctxT.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
615 616 617 618
		t.Fatal("Didnt get back providers")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
619
func TestLayeredGet(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
620
	// t.Skip("skipping test to debug another")
621 622 623
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
624

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
625
	ctx := context.Background()
626

627
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
628 629
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
630
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
631
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
632 633 634
		}
	}()

635 636 637
	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
638

639
	err := dhts[3].Provide(ctx, key.Key("/v/hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
640 641 642 643
	if err != nil {
		t.Fatal(err)
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
646
	t.Log("interface was changed. GetValue should not use providers.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
647
	ctxT, _ := context.WithTimeout(ctx, time.Second)
648
	val, err := dhts[0].GetValue(ctxT, key.Key("/v/hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
649 650
	if err != routing.ErrNotFound {
		t.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
651
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
652 653 654 655 656
	if string(val) == "world" {
		t.Error("should not get value.")
	}
	if len(val) > 0 && string(val) != "world" {
		t.Error("worse, there's a value and its not even the right one.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
657 658 659 660
	}
}

func TestFindPeer(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
661
	// t.Skip("skipping test to debug another")
662 663 664
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
665

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
666
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
667

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
668
	_, peers, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
669 670
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
671
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
672
			dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
673 674 675
		}
	}()

676 677 678
	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
679

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
680
	ctxT, _ := context.WithTimeout(ctx, time.Second)
681
	p, err := dhts[0].FindPeer(ctxT, peers[2])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
682 683 684 685
	if err != nil {
		t.Fatal(err)
	}

686
	if p.ID == "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
687 688 689
		t.Fatal("Failed to find peer.")
	}

690
	if p.ID != peers[2] {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
691 692 693
		t.Fatal("Didnt find expected peer.")
	}
}
694

695
func TestFindPeersConnectedToPeer(t *testing.T) {
696 697
	t.Skip("not quite correct (see note)")

698 699 700 701 702 703 704 705 706 707
	if testing.Short() {
		t.SkipNow()
	}

	ctx := context.Background()

	_, 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
708
			dhts[i].host.Close()
709 710 711 712 713
		}
	}()

	// topology:
	// 0-1, 1-2, 1-3, 2-3
714 715 716 717
	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])
718 719 720 721 722 723 724

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

	ctxT, _ := context.WithTimeout(ctx, time.Second)
725
	pchan, err := dhts[0].FindPeersConnectedToPeer(ctxT, peers[2])
726 727 728 729
	if err != nil {
		t.Fatal(err)
	}

730
	// shouldFind := []peer.ID{peers[1], peers[3]}
Jeromy's avatar
Jeromy committed
731
	var found []pstore.PeerInfo
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
	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.")
	}
}

748
func testPeerListsMatch(t *testing.T, p1, p2 []peer.ID) {
749 750 751 752 753 754 755 756 757

	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 {
758
		ids1[i] = string(p)
759 760 761
	}

	for i, p := range p2 {
762
		ids2[i] = string(p)
763 764 765 766 767 768 769 770 771 772 773 774
	}

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

775
func TestConnectCollision(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
776
	// t.Skip("skipping test to debug another")
777 778 779
	if testing.Short() {
		t.SkipNow()
	}
780 781 782
	if travisci.IsRunning() {
		t.Skip("Skipping on Travis-CI.")
	}
783

784
	runTimes := 10
785

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
789
		ctx := context.Background()
790

791 792
		dhtA := setupDHT(ctx, t, false)
		dhtB := setupDHT(ctx, t, false)
793

794 795
		addrA := dhtA.peerstore.Addrs(dhtA.self)[0]
		addrB := dhtB.peerstore.Addrs(dhtB.self)[0]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
796

797 798
		peerA := dhtA.self
		peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
799

800
		errs := make(chan error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
801
		go func() {
Jeromy's avatar
Jeromy committed
802 803
			dhtA.peerstore.AddAddr(peerB, addrB, pstore.TempAddrTTL)
			pi := pstore.PeerInfo{ID: peerB}
Jeromy's avatar
Jeromy committed
804
			err := dhtA.host.Connect(ctx, pi)
805
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
806 807
		}()
		go func() {
Jeromy's avatar
Jeromy committed
808 809
			dhtB.peerstore.AddAddr(peerA, addrA, pstore.TempAddrTTL)
			pi := pstore.PeerInfo{ID: peerA}
Jeromy's avatar
Jeromy committed
810
			err := dhtB.host.Connect(ctx, pi)
811
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
812 813
		}()

814
		timeout := time.After(5 * time.Second)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
815
		select {
816 817 818 819
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
820 821 822 823
		case <-timeout:
			t.Fatal("Timeout received!")
		}
		select {
824 825 826 827
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
828 829 830 831
		case <-timeout:
			t.Fatal("Timeout received!")
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
832 833
		dhtA.Close()
		dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
834 835
		dhtA.host.Close()
		dhtB.host.Close()
Jeromy's avatar
Jeromy committed
836
	}
837
}
838 839 840 841 842

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

843
	d := setupDHT(ctx, t, false)
844 845 846 847 848 849

	nilrec := new(pb.Message)
	if _, err := d.handlePutValue(ctx, "testpeer", nilrec); err == nil {
		t.Fatal("should have errored on nil record")
	}
}
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876

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)

	k := key.Key("TestHash")
	p := peer.ID("TestPeer")
	a.providers.AddProvider(ctx, k, p)

	provs, err := b.FindProviders(ctx, k)
	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")
	}
}