dht_test.go 18 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 14 15
	ds "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore"
	dssync "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-datastore/sync"
	ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
16

17
	key "github.com/ipfs/go-ipfs/blocks/key"
18 19 20 21 22
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	netutil "github.com/ipfs/go-ipfs/p2p/test/util"
	routing "github.com/ipfs/go-ipfs/routing"
	record "github.com/ipfs/go-ipfs/routing/record"
	u "github.com/ipfs/go-ipfs/util"
23

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

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

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

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

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

45
	d.Validator["v"] = &record.ValidChecker{
46
		Func: func(key.Key, []byte) error {
47 48 49
			return nil
		},
		Sign: false,
Jeromy's avatar
Jeromy committed
50
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
51 52 53
	return d
}

54 55
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
56
	dhts := make([]*IpfsDHT, n)
57 58
	peers := make([]peer.ID, n)

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

	return addrs, peers, dhts
}

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

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

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

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

84
	ctx, cancel := context.WithCancel(ctx)
85 86 87 88 89 90 91
	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

92 93 94 95
	var cfg BootstrapConfig
	cfg = DefaultBootstrapConfig
	cfg.Queries = 3

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
104
func TestPing(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
105
	// t.Skip("skipping test to debug another")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
106
	ctx := context.Background()
107

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108 109
	dhtA := setupDHT(ctx, t)
	dhtB := setupDHT(ctx, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
110

111 112
	peerA := dhtA.self
	peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
113

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114 115
	defer dhtA.Close()
	defer dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116 117
	defer dhtA.host.Close()
	defer dhtB.host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118

119
	connect(t, ctx, dhtA, dhtB)
120

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

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

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
138 139
	dhtA := setupDHT(ctx, t)
	dhtB := setupDHT(ctx, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
140

141 142
	defer dhtA.Close()
	defer dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
143 144
	defer dhtA.host.Close()
	defer dhtB.host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
145

146
	vf := &record.ValidChecker{
147
		Func: func(key.Key, []byte) error {
148 149 150
			return nil
		},
		Sign: false,
Jeromy's avatar
Jeromy committed
151
	}
152 153
	dhtA.Validator["v"] = vf
	dhtB.Validator["v"] = vf
Jeromy's avatar
Jeromy committed
154

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
160
	ctxT, _ = context.WithTimeout(ctx, time.Second*2)
Jeromy's avatar
Jeromy committed
161
	val, err := dhtA.GetValue(ctxT, "/v/hello")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
162 163 164 165 166 167 168 169
	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
170
	ctxT, _ = context.WithTimeout(ctx, time.Second*2)
Jeromy's avatar
Jeromy committed
171
	val, err = dhtB.GetValue(ctxT, "/v/hello")
172 173 174 175 176 177 178
	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
179 180
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
181 182
func TestProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
183
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
184

185
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
186 187
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
188
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
189
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190 191 192
		}
	}()

193 194 195
	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
196

197
	for k, v := range testCaseValues {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
198
		log.Debugf("adding local values for %s = %s", k, v)
Jeromy's avatar
Jeromy committed
199 200 201 202 203 204 205
		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)
206 207 208 209 210 211 212 213 214 215 216
		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
217 218
	}

rht's avatar
rht committed
219
	for k := range testCaseValues {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
220
		log.Debugf("announcing provider for %s", k)
221 222 223
		if err := dhts[3].Provide(ctx, k); err != nil {
			t.Fatal(err)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
224 225
	}

226 227 228 229
	// what is this timeout for? was 60ms before.
	time.Sleep(time.Millisecond * 6)

	n := 0
rht's avatar
rht committed
230
	for k := range testCaseValues {
231 232
		n = (n + 1) % 3

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
233
		log.Debugf("getting providers for %s from %d", k, n)
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
		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.")
		}
	}
}

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 277
// 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:
278
			log.Debugf("did not reach well-formed routing tables by %s", timeout)
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
			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
298
func TestBootstrap(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
299
	// t.Skip("skipping test to debug another")
300 301 302 303
	if testing.Short() {
		t.SkipNow()
	}

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

306
	nDHTs := 30
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
307 308 309 310
	_, _, 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
311
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
312 313 314 315 316 317 318 319
		}
	}()

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

320
	<-time.After(100 * time.Millisecond)
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
	// 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
			}
		}
	}()

338
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
339
	close(stop)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
340

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
341 342
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
343 344 345 346 347 348
		printRoutingTables(dhts)
	}
}

func TestPeriodicBootstrap(t *testing.T) {
	// t.Skip("skipping test to debug another")
349 350 351
	if ci.IsRunning() {
		t.Skip("skipping on CI. highly timing dependent")
	}
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
	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
376 377 378
		}
	}

379 380 381
	signal := make(chan time.Time)
	allSignals := []chan time.Time{}

382 383 384 385
	var cfg BootstrapConfig
	cfg = DefaultBootstrapConfig
	cfg.Queries = 5

386 387 388 389
	// kick off periodic bootstrappers with instrumented signals.
	for _, dht := range dhts {
		s := make(chan time.Time)
		allSignals = append(allSignals, s)
390
		dht.BootstrapOnSignal(cfg, s)
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
	}
	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
407
	for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
408
		rtlen := dht.routingTable.Size()
409 410
		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
411
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
412
	}
413

414 415 416 417 418 419 420 421 422
	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.
423
	waitForWellFormedTables(t, dhts, 7, 10, 20*time.Second)
424 425 426

	if u.Debug {
		printRoutingTables(dhts)
427
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
428 429
}

430 431
func TestProvidesMany(t *testing.T) {
	t.Skip("this test doesn't work")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
432
	// t.Skip("skipping test to debug another")
433 434 435 436 437 438 439
	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
440
			defer dhts[i].host.Close()
441 442 443 444 445 446 447 448
		}
	}()

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
454 455 456 457 458 459 460 461
	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("")
		}
462
	}
463

464
	var providers = map[key.Key]peer.ID{}
465

466 467 468 469
	d := 0
	for k, v := range testCaseValues {
		d = (d + 1) % len(dhts)
		dht := dhts[d]
470
		providers[k] = dht.self
471 472

		t.Logf("adding local values for %s = %s (on %s)", k, v, dht.self)
Jeromy's avatar
Jeromy committed
473 474 475 476 477 478
		rec, err := record.MakePutRecord(nil, k, v, false)
		if err != nil {
			t.Fatal(err)
		}

		err = dht.putLocal(k, rec)
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
		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
495 496
	}

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

500 501
	errchan := make(chan error)

502
	ctxT, _ = context.WithTimeout(ctx, 5*time.Second)
503 504

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

508 509
		expected := providers[k]

510 511 512
		provchan := dht.FindProvidersAsync(ctxT, k, 1)
		select {
		case prov := <-provchan:
513 514
			actual := prov.ID
			if actual == "" {
515
				errchan <- fmt.Errorf("Got back nil provider (%s at %s)", k, dht.self)
516 517 518
			} else if actual != expected {
				errchan <- fmt.Errorf("Got back wrong provider (%s != %s) (%s at %s)",
					expected, actual, k, dht.self)
519 520 521
			}
		case <-ctxT.Done():
			errchan <- fmt.Errorf("Did not get a provider back (%s at %s)", k, dht.self)
Jeromy's avatar
Jeromy committed
522
		}
523 524
	}

rht's avatar
rht committed
525
	for k := range testCaseValues {
526 527
		// everyone should be able to find it...
		for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
528
			log.Debugf("getting providers for %s at %s", k, dht.self)
529 530
			wg.Add(1)
			go getProvider(dht, k)
531
		}
532 533 534 535 536 537 538 539 540 541
	}

	// 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
542 543 544
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
545
func TestProvidesAsync(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
546
	// t.Skip("skipping test to debug another")
547 548 549
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
550

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

553
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
554 555
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
556
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
557
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
558 559 560
		}
	}()

561 562 563
	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
564

565
	k := key.Key("hello")
Jeromy's avatar
Jeromy committed
566 567 568 569 570 571 572 573
	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
574 575 576 577
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
578 579
	bits, err := dhts[3].getLocal(k)
	if err != nil && bytes.Equal(bits, val) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
580 581 582
		t.Fatal(err)
	}

583
	err = dhts[3].Provide(ctx, key.Key("hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
584 585 586 587 588 589
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 60)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
590
	ctxT, _ := context.WithTimeout(ctx, time.Millisecond*300)
591
	provs := dhts[0].FindProvidersAsync(ctxT, key.Key("hello"), 5)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
592
	select {
Jeromy's avatar
Jeromy committed
593 594 595 596
	case p, ok := <-provs:
		if !ok {
			t.Fatal("Provider channel was closed...")
		}
597
		if p.ID == "" {
Jeromy's avatar
Jeromy committed
598 599
			t.Fatal("Got back nil provider!")
		}
600
		if p.ID != dhts[3].self {
601
			t.Fatalf("got a provider, but not the right one. %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
602
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
603
	case <-ctxT.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
604 605 606 607
		t.Fatal("Didnt get back providers")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
608
func TestLayeredGet(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
609
	// t.Skip("skipping test to debug another")
610 611 612
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
613

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

616
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
617 618
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
619
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
620
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
621 622 623
		}
	}()

624 625 626
	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
627

628
	err := dhts[3].Provide(ctx, key.Key("/v/hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
629 630 631 632
	if err != nil {
		t.Fatal(err)
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
635
	t.Log("interface was changed. GetValue should not use providers.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
636
	ctxT, _ := context.WithTimeout(ctx, time.Second)
637
	val, err := dhts[0].GetValue(ctxT, key.Key("/v/hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
638 639
	if err != routing.ErrNotFound {
		t.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
640
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
641 642 643 644 645
	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
646 647 648 649
	}
}

func TestFindPeer(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
650
	// t.Skip("skipping test to debug another")
651 652 653
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
654

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
657
	_, peers, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
658 659
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
660
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
661
			dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
662 663 664
		}
	}()

665 666 667
	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
668

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
669
	ctxT, _ := context.WithTimeout(ctx, time.Second)
670
	p, err := dhts[0].FindPeer(ctxT, peers[2])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
671 672 673 674
	if err != nil {
		t.Fatal(err)
	}

675
	if p.ID == "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
676 677 678
		t.Fatal("Failed to find peer.")
	}

679
	if p.ID != peers[2] {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
680 681 682
		t.Fatal("Didnt find expected peer.")
	}
}
683

684
func TestFindPeersConnectedToPeer(t *testing.T) {
685 686
	t.Skip("not quite correct (see note)")

687 688 689 690 691 692 693 694 695 696
	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
697
			dhts[i].host.Close()
698 699 700 701 702
		}
	}()

	// topology:
	// 0-1, 1-2, 1-3, 2-3
703 704 705 706
	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])
707 708 709 710 711 712 713

	// 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)
714
	pchan, err := dhts[0].FindPeersConnectedToPeer(ctxT, peers[2])
715 716 717 718
	if err != nil {
		t.Fatal(err)
	}

719 720
	// shouldFind := []peer.ID{peers[1], peers[3]}
	found := []peer.PeerInfo{}
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
	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.")
	}
}

737
func testPeerListsMatch(t *testing.T, p1, p2 []peer.ID) {
738 739 740 741 742 743 744 745 746

	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 {
747
		ids1[i] = string(p)
748 749 750
	}

	for i, p := range p2 {
751
		ids2[i] = string(p)
752 753 754 755 756 757 758 759 760 761 762 763
	}

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

764
func TestConnectCollision(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
765
	// t.Skip("skipping test to debug another")
766 767 768
	if testing.Short() {
		t.SkipNow()
	}
769 770 771
	if travisci.IsRunning() {
		t.Skip("Skipping on Travis-CI.")
	}
772

773
	runTimes := 10
774

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
780 781
		dhtA := setupDHT(ctx, t)
		dhtB := setupDHT(ctx, t)
782

783 784
		addrA := dhtA.peerstore.Addrs(dhtA.self)[0]
		addrB := dhtB.peerstore.Addrs(dhtB.self)[0]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
785

786 787
		peerA := dhtA.self
		peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
788

789
		errs := make(chan error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
790
		go func() {
791
			dhtA.peerstore.AddAddr(peerB, addrB, peer.TempAddrTTL)
792
			err := dhtA.Connect(ctx, peerB)
793
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
794 795
		}()
		go func() {
796
			dhtB.peerstore.AddAddr(peerA, addrA, peer.TempAddrTTL)
797
			err := dhtB.Connect(ctx, peerA)
798
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
799 800
		}()

801
		timeout := time.After(5 * time.Second)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
802
		select {
803 804 805 806
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
807 808 809 810
		case <-timeout:
			t.Fatal("Timeout received!")
		}
		select {
811 812 813 814
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
815 816 817 818
		case <-timeout:
			t.Fatal("Timeout received!")
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
819 820
		dhtA.Close()
		dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
821 822
		dhtA.host.Close()
		dhtB.host.Close()
Jeromy's avatar
Jeromy committed
823
	}
824
}