dht_test.go 17.5 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

	context "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/go.net/context"

14
	ds "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
15
	dssync "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/sync"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16 17
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18
	peer "github.com/jbenet/go-ipfs/p2p/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19
	netutil "github.com/jbenet/go-ipfs/p2p/test/util"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
	routing "github.com/jbenet/go-ipfs/routing"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21
	u "github.com/jbenet/go-ipfs/util"
22

23
	ci "github.com/jbenet/go-ipfs/util/testutil/ci"
24
	travisci "github.com/jbenet/go-ipfs/util/testutil/ci/travis"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
25 26
)

27 28 29 30 31 32 33 34 35 36 37
var testCaseValues = map[u.Key][]byte{}

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

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

41
	dss := dssync.MutexWrap(ds.NewMapDatastore())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42
	d := NewDHT(ctx, h, dss)
43

44
	d.Validator["v"] = func(u.Key, []byte) error {
Jeromy's avatar
Jeromy committed
45 46
		return nil
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47 48 49
	return d
}

50 51
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
52
	dhts := make([]*IpfsDHT, n)
53 54
	peers := make([]peer.ID, n)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
55
	for i := 0; i < n; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
56
		dhts[i] = setupDHT(ctx, t)
57
		peers[i] = dhts[i].self
58
		addrs[i] = dhts[i].peerstore.Addrs(dhts[i].self)[0]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
59 60 61 62 63
	}

	return addrs, peers, dhts
}

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

66
	idB := b.self
67
	addrB := b.peerstore.Addrs(idB)
68 69
	if len(addrB) == 0 {
		t.Fatal("peers setup incorrectly: no local address")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70
	}
71

72
	a.peerstore.AddAddrs(idB, addrB, peer.TempAddrTTL)
73 74
	if err := a.Connect(ctx, idB); err != nil {
		t.Fatal(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75 76 77
	}
}

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

80
	ctx, cancel := context.WithCancel(ctx)
81 82 83 84 85 86 87
	log.Debugf("bootstrapping dhts...")

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

88 89 90 91
	var cfg BootstrapConfig
	cfg = DefaultBootstrapConfig
	cfg.Queries = 3

92 93 94
	start := rand.Intn(len(dhts)) // randomize to decrease bias.
	for i := range dhts {
		dht := dhts[(start+i)%len(dhts)]
95
		dht.runBootstrap(ctx, cfg)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
96
	}
97
	cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
98 99
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
100
func TestPing(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
101
	// t.Skip("skipping test to debug another")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
102
	ctx := context.Background()
103

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104 105
	dhtA := setupDHT(ctx, t)
	dhtB := setupDHT(ctx, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106

107 108
	peerA := dhtA.self
	peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
109

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110 111
	defer dhtA.Close()
	defer dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
112 113
	defer dhtA.host.Close()
	defer dhtB.host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114

115
	connect(t, ctx, dhtA, dhtB)
116

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117
	//Test that we can ping the node
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118
	ctxT, _ := context.WithTimeout(ctx, 100*time.Millisecond)
Jeromy's avatar
Jeromy committed
119
	if _, err := dhtA.Ping(ctxT, peerB); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
120 121
		t.Fatal(err)
	}
122

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
123
	ctxT, _ = context.WithTimeout(ctx, 100*time.Millisecond)
Jeromy's avatar
Jeromy committed
124
	if _, err := dhtB.Ping(ctxT, peerA); err != nil {
125 126
		t.Fatal(err)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
127 128 129
}

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
134 135
	dhtA := setupDHT(ctx, t)
	dhtB := setupDHT(ctx, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136

137 138
	defer dhtA.Close()
	defer dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139 140
	defer dhtA.host.Close()
	defer dhtB.host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
141

Jeromy's avatar
Jeromy committed
142 143 144
	vf := func(u.Key, []byte) error {
		return nil
	}
145 146
	dhtA.Validator["v"] = vf
	dhtB.Validator["v"] = vf
Jeromy's avatar
Jeromy committed
147

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
153
	ctxT, _ = context.WithTimeout(ctx, time.Second*2)
Jeromy's avatar
Jeromy committed
154
	val, err := dhtA.GetValue(ctxT, "/v/hello")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155 156 157 158 159 160 161 162
	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
163
	ctxT, _ = context.WithTimeout(ctx, time.Second*2)
Jeromy's avatar
Jeromy committed
164
	val, err = dhtB.GetValue(ctxT, "/v/hello")
165 166 167 168 169 170 171
	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
172 173
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
174 175
func TestProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
176
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177

178
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
179 180
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
181
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
182
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183 184 185
		}
	}()

186 187 188
	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
189

190
	for k, v := range testCaseValues {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
191
		log.Debugf("adding local values for %s = %s", k, v)
192 193 194 195 196 197 198 199 200 201 202 203
		err := dhts[3].putLocal(k, v)
		if err != nil {
			t.Fatal(err)
		}

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

206
	for k, _ := range testCaseValues {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
207
		log.Debugf("announcing provider for %s", k)
208 209 210
		if err := dhts[3].Provide(ctx, k); err != nil {
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
211 212
	}

213 214 215 216 217 218 219
	// what is this timeout for? was 60ms before.
	time.Sleep(time.Millisecond * 6)

	n := 0
	for k, _ := range testCaseValues {
		n = (n + 1) % 3

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220
		log.Debugf("getting providers for %s from %d", k, n)
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
		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.")
		}
	}
}

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
// 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:
265
			log.Debugf("did not reach well-formed routing tables by %s", timeout)
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
			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.
	fmt.Println("checking routing table of %d", len(dhts))
	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
285
func TestBootstrap(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
286
	// t.Skip("skipping test to debug another")
287 288 289 290
	if testing.Short() {
		t.SkipNow()
	}

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

293
	nDHTs := 30
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294 295 296 297
	_, _, 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
298
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
299 300 301 302 303 304 305 306
		}
	}()

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

307
	<-time.After(100 * time.Millisecond)
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
	// bootstrap a few times until we get good tables.
	stop := make(chan struct{})
	go func() {
		for {
			t.Logf("bootstrapping them so they find each other", nDHTs)
			ctxT, _ := context.WithTimeout(ctx, 5*time.Second)
			bootstrap(t, ctxT, dhts)

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

325
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
326
	close(stop)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
327

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
328 329
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
330 331 332 333 334 335
		printRoutingTables(dhts)
	}
}

func TestPeriodicBootstrap(t *testing.T) {
	// t.Skip("skipping test to debug another")
336 337 338
	if ci.IsRunning() {
		t.Skip("skipping on CI. highly timing dependent")
	}
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
	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
363 364 365
		}
	}

366 367 368
	signal := make(chan time.Time)
	allSignals := []chan time.Time{}

369 370 371 372
	var cfg BootstrapConfig
	cfg = DefaultBootstrapConfig
	cfg.Queries = 5

373 374 375 376
	// kick off periodic bootstrappers with instrumented signals.
	for _, dht := range dhts {
		s := make(chan time.Time)
		allSignals = append(allSignals, s)
377
		dht.BootstrapOnSignal(cfg, s)
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
	}
	go amplify(signal, allSignals)

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

	t.Logf("dhts are now connected to 1-2 others.", nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
394
	for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
395
		rtlen := dht.routingTable.Size()
396 397
		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
398
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
399
	}
400

401 402 403 404 405 406 407 408 409
	if u.Debug {
		printRoutingTables(dhts)
	}

	t.Logf("bootstrapping them so they find each other", nDHTs)
	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.
410
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
411 412 413

	if u.Debug {
		printRoutingTables(dhts)
414
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
415 416
}

417 418
func TestProvidesMany(t *testing.T) {
	t.Skip("this test doesn't work")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
419
	// t.Skip("skipping test to debug another")
420 421 422 423 424 425 426
	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
427
			defer dhts[i].host.Close()
428 429 430 431 432 433 434 435
		}
	}()

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

436
	<-time.After(100 * time.Millisecond)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
437
	t.Logf("bootstrapping them so they find each other", nDHTs)
438
	ctxT, _ := context.WithTimeout(ctx, 20*time.Second)
439 440
	bootstrap(t, ctxT, dhts)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
441 442 443 444 445 446 447 448
	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("")
		}
449
	}
450

451 452
	var providers = map[u.Key]peer.ID{}

453 454 455 456
	d := 0
	for k, v := range testCaseValues {
		d = (d + 1) % len(dhts)
		dht := dhts[d]
457
		providers[k] = dht.self
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

		t.Logf("adding local values for %s = %s (on %s)", k, v, dht.self)
		err := dht.putLocal(k, v)
		if err != nil {
			t.Fatal(err)
		}

		bits, err := dht.getLocal(k)
		if err != nil {
			t.Fatal(err)
		}
		if !bytes.Equal(bits, v) {
			t.Fatal("didn't store the right bits (%s, %s)", k, v)
		}

		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
477 478
	}

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

482 483
	errchan := make(chan error)

484
	ctxT, _ = context.WithTimeout(ctx, 5*time.Second)
485 486 487 488

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

490 491
		expected := providers[k]

492 493 494
		provchan := dht.FindProvidersAsync(ctxT, k, 1)
		select {
		case prov := <-provchan:
495 496
			actual := prov.ID
			if actual == "" {
497
				errchan <- fmt.Errorf("Got back nil provider (%s at %s)", k, dht.self)
498 499 500
			} else if actual != expected {
				errchan <- fmt.Errorf("Got back wrong provider (%s != %s) (%s at %s)",
					expected, actual, k, dht.self)
501 502 503
			}
		case <-ctxT.Done():
			errchan <- fmt.Errorf("Did not get a provider back (%s at %s)", k, dht.self)
Jeromy's avatar
Jeromy committed
504
		}
505 506 507 508 509
	}

	for k, _ := range testCaseValues {
		// everyone should be able to find it...
		for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
510
			log.Debugf("getting providers for %s at %s", k, dht.self)
511 512
			wg.Add(1)
			go getProvider(dht, k)
513
		}
514 515 516 517 518 519 520 521 522 523
	}

	// 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
524 525 526
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
527
func TestProvidesAsync(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
528
	// t.Skip("skipping test to debug another")
529 530 531
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
532

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

535
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
536 537
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
538
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
539
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
540 541 542
		}
	}()

543 544 545
	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
546

547
	err := dhts[3].putLocal(u.Key("hello"), []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
548 549 550 551 552 553 554 555 556
	if err != nil {
		t.Fatal(err)
	}

	bits, err := dhts[3].getLocal(u.Key("hello"))
	if err != nil && bytes.Equal(bits, []byte("world")) {
		t.Fatal(err)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
557
	err = dhts[3].Provide(ctx, u.Key("hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
558 559 560 561 562 563
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 60)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
564 565
	ctxT, _ := context.WithTimeout(ctx, time.Millisecond*300)
	provs := dhts[0].FindProvidersAsync(ctxT, u.Key("hello"), 5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
566
	select {
Jeromy's avatar
Jeromy committed
567 568 569 570
	case p, ok := <-provs:
		if !ok {
			t.Fatal("Provider channel was closed...")
		}
571
		if p.ID == "" {
Jeromy's avatar
Jeromy committed
572 573
			t.Fatal("Got back nil provider!")
		}
574
		if p.ID != dhts[3].self {
575
			t.Fatalf("got a provider, but not the right one. %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
576
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
577
	case <-ctxT.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
578 579 580 581
		t.Fatal("Didnt get back providers")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
582
func TestLayeredGet(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
583
	// t.Skip("skipping test to debug another")
584 585 586
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
587

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

590
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
591 592
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
593
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
594
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
595 596 597
		}
	}()

598 599 600
	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
601

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
602
	err := dhts[3].Provide(ctx, u.Key("/v/hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
603 604 605 606
	if err != nil {
		t.Fatal(err)
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
609
	t.Log("interface was changed. GetValue should not use providers.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
610
	ctxT, _ := context.WithTimeout(ctx, time.Second)
Jeromy's avatar
Jeromy committed
611
	val, err := dhts[0].GetValue(ctxT, u.Key("/v/hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
612 613
	if err != routing.ErrNotFound {
		t.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
614
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
615 616 617 618 619
	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
620 621 622 623
	}
}

func TestFindPeer(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
624
	// t.Skip("skipping test to debug another")
625 626 627
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
628

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

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

639 640 641
	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
642

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
643
	ctxT, _ := context.WithTimeout(ctx, time.Second)
644
	p, err := dhts[0].FindPeer(ctxT, peers[2])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
645 646 647 648
	if err != nil {
		t.Fatal(err)
	}

649
	if p.ID == "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
650 651 652
		t.Fatal("Failed to find peer.")
	}

653
	if p.ID != peers[2] {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
654 655 656
		t.Fatal("Didnt find expected peer.")
	}
}
657

658
func TestFindPeersConnectedToPeer(t *testing.T) {
659 660
	t.Skip("not quite correct (see note)")

661 662 663 664 665 666 667 668 669 670
	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
671
			dhts[i].host.Close()
672 673 674 675 676
		}
	}()

	// topology:
	// 0-1, 1-2, 1-3, 2-3
677 678 679 680
	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])
681 682 683 684 685 686 687

	// 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)
688
	pchan, err := dhts[0].FindPeersConnectedToPeer(ctxT, peers[2])
689 690 691 692
	if err != nil {
		t.Fatal(err)
	}

693 694
	// shouldFind := []peer.ID{peers[1], peers[3]}
	found := []peer.PeerInfo{}
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
	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.")
	}
}

711
func testPeerListsMatch(t *testing.T, p1, p2 []peer.ID) {
712 713 714 715 716 717 718 719 720

	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 {
721
		ids1[i] = string(p)
722 723 724
	}

	for i, p := range p2 {
725
		ids2[i] = string(p)
726 727 728 729 730 731 732 733 734 735 736 737
	}

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

738
func TestConnectCollision(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
739
	// t.Skip("skipping test to debug another")
740 741 742
	if testing.Short() {
		t.SkipNow()
	}
743 744 745
	if travisci.IsRunning() {
		t.Skip("Skipping on Travis-CI.")
	}
746

747
	runTimes := 10
748

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
749 750
	for rtime := 0; rtime < runTimes; rtime++ {
		log.Notice("Running Time: ", rtime)
751

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
754 755
		dhtA := setupDHT(ctx, t)
		dhtB := setupDHT(ctx, t)
756

757 758
		addrA := dhtA.peerstore.Addrs(dhtA.self)[0]
		addrB := dhtB.peerstore.Addrs(dhtB.self)[0]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
759

760 761
		peerA := dhtA.self
		peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
762

763
		errs := make(chan error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
764
		go func() {
765
			dhtA.peerstore.AddAddr(peerB, addrB, peer.TempAddrTTL)
766
			err := dhtA.Connect(ctx, peerB)
767
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
768 769
		}()
		go func() {
770
			dhtB.peerstore.AddAddr(peerA, addrA, peer.TempAddrTTL)
771
			err := dhtB.Connect(ctx, peerA)
772
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
773 774
		}()

775
		timeout := time.After(5 * time.Second)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
776
		select {
777 778 779 780
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
781 782 783 784
		case <-timeout:
			t.Fatal("Timeout received!")
		}
		select {
785 786 787 788
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
789 790 791 792
		case <-timeout:
			t.Fatal("Timeout received!")
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
793 794
		dhtA.Close()
		dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
795 796
		dhtA.host.Close()
		dhtB.host.Close()
Jeromy's avatar
Jeromy committed
797
	}
798
}