dht_test.go 14.7 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 22 23
	u "github.com/jbenet/go-ipfs/util"
)

24 25 26 27 28 29 30 31 32 33 34
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
35 36
func setupDHT(ctx context.Context, t *testing.T) *IpfsDHT {
	h := netutil.GenHostSwarm(t, ctx)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37

38
	dss := dssync.MutexWrap(ds.NewMapDatastore())
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39
	d := NewDHT(ctx, h, dss)
40

Jeromy's avatar
Jeromy committed
41 42 43
	d.Validators["v"] = func(u.Key, []byte) error {
		return nil
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44 45 46
	return d
}

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

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

	return addrs, peers, dhts
}

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

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

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

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

77 78
	ctx, cancel := context.WithCancel(ctx)

79
	rounds := 1
80

81
	for i := 0; i < rounds; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82
		log.Debugf("bootstrapping round %d/%d\n", i, rounds)
83

84 85 86 87
		// 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

		start := rand.Intn(len(dhts)) // randomize to decrease bias.
		for i := range dhts {
			dht := dhts[(start+i)%len(dhts)]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
92
			log.Debugf("bootstrapping round %d/%d -- %s\n", i, rounds, dht.self)
93
			dht.Bootstrap(ctx, 3)
94
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
95
	}
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)
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)
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 145 146 147
	vf := func(u.Key, []byte) error {
		return nil
	}
	dhtA.Validators["v"] = vf
	dhtB.Validators["v"] = vf

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
238
func TestBootstrap(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239
	// t.Skip("skipping test to debug another")
240 241 242 243
	if testing.Short() {
		t.SkipNow()
	}

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

246
	nDHTs := 30
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
247 248 249 250
	_, _, 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
251
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
252 253 254 255 256 257 258 259
		}
	}()

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

260
	<-time.After(100 * time.Millisecond)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
261
	t.Logf("bootstrapping them so they find each other", nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
262 263
	ctxT, _ := context.WithTimeout(ctx, 5*time.Second)
	bootstrap(t, ctxT, dhts)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
264

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
265 266 267 268 269 270 271 272 273 274 275 276
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
		<-time.After(5 * time.Second)
		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("")
		}
	}

	// test "well-formed-ness" (>= 3 peers in every routing table)
277
	avgsize := 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
278
	for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
279
		rtlen := dht.routingTable.Size()
280 281
		avgsize += rtlen
		t.Logf("routing table for %s has %d peers", dht.self, rtlen)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
282
		if rtlen < 4 {
283 284
			// currently, we dont have good bootstrapping guarantees.
			// t.Errorf("routing table for %s only has %d peers", dht.self, rtlen)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
285
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
286
	}
287 288 289 290 291 292 293
	avgsize = avgsize / len(dhts)
	avgsizeExpected := 6

	t.Logf("avg rt size: %d", avgsize)
	if avgsize < avgsizeExpected {
		t.Errorf("avg rt size: %d < %d", avgsize, avgsizeExpected)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
294 295
}

296 297
func TestProvidesMany(t *testing.T) {
	t.Skip("this test doesn't work")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
298
	// t.Skip("skipping test to debug another")
299 300 301 302 303 304 305
	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
306
			defer dhts[i].host.Close()
307 308 309 310 311 312 313 314
		}
	}()

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
320 321 322 323 324 325 326 327 328
	if u.Debug {
		// the routing tables should be full now. let's inspect them.
		<-time.After(5 * time.Second)
		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("")
		}
329
	}
330

331 332
	var providers = map[u.Key]peer.ID{}

333 334 335 336
	d := 0
	for k, v := range testCaseValues {
		d = (d + 1) % len(dhts)
		dht := dhts[d]
337
		providers[k] = dht.self
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356

		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
357 358
	}

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

362 363
	errchan := make(chan error)

364
	ctxT, _ = context.WithTimeout(ctx, 5*time.Second)
365 366 367 368

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

370 371
		expected := providers[k]

372 373 374
		provchan := dht.FindProvidersAsync(ctxT, k, 1)
		select {
		case prov := <-provchan:
375 376
			actual := prov.ID
			if actual == "" {
377
				errchan <- fmt.Errorf("Got back nil provider (%s at %s)", k, dht.self)
378 379 380
			} else if actual != expected {
				errchan <- fmt.Errorf("Got back wrong provider (%s != %s) (%s at %s)",
					expected, actual, k, dht.self)
381 382 383
			}
		case <-ctxT.Done():
			errchan <- fmt.Errorf("Did not get a provider back (%s at %s)", k, dht.self)
Jeromy's avatar
Jeromy committed
384
		}
385 386 387 388 389
	}

	for k, _ := range testCaseValues {
		// everyone should be able to find it...
		for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
390
			log.Debugf("getting providers for %s at %s", k, dht.self)
391 392
			wg.Add(1)
			go getProvider(dht, k)
393
		}
394 395 396 397 398 399 400 401 402 403
	}

	// 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
404 405 406
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
407
func TestProvidesAsync(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
408
	// t.Skip("skipping test to debug another")
409 410 411
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
412

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

415
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
416 417
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
418
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
419
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
420 421 422
		}
	}()

423 424 425
	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
426

427
	err := dhts[3].putLocal(u.Key("hello"), []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
428 429 430 431 432 433 434 435 436
	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
437
	err = dhts[3].Provide(ctx, u.Key("hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
438 439 440 441 442 443
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 60)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
444 445
	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
446
	select {
Jeromy's avatar
Jeromy committed
447 448 449 450
	case p, ok := <-provs:
		if !ok {
			t.Fatal("Provider channel was closed...")
		}
451
		if p.ID == "" {
Jeromy's avatar
Jeromy committed
452 453
			t.Fatal("Got back nil provider!")
		}
454
		if p.ID != dhts[3].self {
455
			t.Fatalf("got a provider, but not the right one. %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
456
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
457
	case <-ctxT.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
458 459 460 461
		t.Fatal("Didnt get back providers")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
462
func TestLayeredGet(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
463
	// t.Skip("skipping test to debug another")
464 465 466
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
467

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

470
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
471 472
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
473
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
474
			defer dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
475 476 477
		}
	}()

478 479 480
	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
481

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
482
	err := dhts[3].Provide(ctx, u.Key("/v/hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
483 484 485 486
	if err != nil {
		t.Fatal(err)
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
489
	t.Log("interface was changed. GetValue should not use providers.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
490
	ctxT, _ := context.WithTimeout(ctx, time.Second)
Jeromy's avatar
Jeromy committed
491
	val, err := dhts[0].GetValue(ctxT, u.Key("/v/hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
492 493
	if err != routing.ErrNotFound {
		t.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
494
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
495 496 497 498 499
	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
500 501 502 503
	}
}

func TestFindPeer(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
504
	// t.Skip("skipping test to debug another")
505 506 507
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
508

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
511
	_, peers, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
512 513
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
514
			dhts[i].Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
515
			dhts[i].host.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
516 517 518
		}
	}()

519 520 521
	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
522

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
523
	ctxT, _ := context.WithTimeout(ctx, time.Second)
524
	p, err := dhts[0].FindPeer(ctxT, peers[2])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
525 526 527 528
	if err != nil {
		t.Fatal(err)
	}

529
	if p.ID == "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
530 531 532
		t.Fatal("Failed to find peer.")
	}

533
	if p.ID != peers[2] {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
534 535 536
		t.Fatal("Didnt find expected peer.")
	}
}
537

538
func TestFindPeersConnectedToPeer(t *testing.T) {
539 540
	t.Skip("not quite correct (see note)")

541 542 543 544 545 546 547 548 549 550
	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
551
			dhts[i].host.Close()
552 553 554 555 556
		}
	}()

	// topology:
	// 0-1, 1-2, 1-3, 2-3
557 558 559 560
	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])
561 562 563 564 565 566 567

	// 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)
568
	pchan, err := dhts[0].FindPeersConnectedToPeer(ctxT, peers[2])
569 570 571 572
	if err != nil {
		t.Fatal(err)
	}

573 574
	// shouldFind := []peer.ID{peers[1], peers[3]}
	found := []peer.PeerInfo{}
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
	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.")
	}
}

591
func testPeerListsMatch(t *testing.T, p1, p2 []peer.ID) {
592 593 594 595 596 597 598 599 600

	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 {
601
		ids1[i] = string(p)
602 603 604
	}

	for i, p := range p2 {
605
		ids2[i] = string(p)
606 607 608 609 610 611 612 613 614 615 616 617
	}

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

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

624
	runTimes := 10
625

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
631 632
		dhtA := setupDHT(ctx, t)
		dhtB := setupDHT(ctx, t)
633

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
634 635
		addrA := dhtA.peerstore.Addresses(dhtA.self)[0]
		addrB := dhtB.peerstore.Addresses(dhtB.self)[0]
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
636

637 638
		peerA := dhtA.self
		peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
639

640
		errs := make(chan error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
641
		go func() {
642
			dhtA.peerstore.AddAddress(peerB, addrB)
643
			err := dhtA.Connect(ctx, peerB)
644
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
645 646
		}()
		go func() {
647
			dhtB.peerstore.AddAddress(peerA, addrA)
648
			err := dhtB.Connect(ctx, peerA)
649
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
650 651 652 653
		}()

		timeout := time.After(time.Second)
		select {
654 655 656 657
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
658 659 660 661
		case <-timeout:
			t.Fatal("Timeout received!")
		}
		select {
662 663 664 665
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
666 667 668 669
		case <-timeout:
			t.Fatal("Timeout received!")
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
670 671
		dhtA.Close()
		dhtB.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
672 673
		dhtA.host.Close()
		dhtB.host.Close()
Jeromy's avatar
Jeromy committed
674
	}
675
}