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
	"sort"
7
	"sync"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	"testing"
9
	"time"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10 11 12

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

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

17
	// ci "github.com/jbenet/go-ipfs/crypto"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19
	inet "github.com/jbenet/go-ipfs/net"
	peer "github.com/jbenet/go-ipfs/peer"
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
	testutil "github.com/jbenet/go-ipfs/util/testutil"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
23 24
)

25 26 27 28 29 30 31 32 33 34 35
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)
	}
}

36
func setupDHT(ctx context.Context, t *testing.T, addr ma.Multiaddr) *IpfsDHT {
37

38 39 40 41 42 43
	sk, pk, err := testutil.RandKeyPair(512)
	if err != nil {
		t.Fatal(err)
	}

	p, err := peer.IDFromPublicKey(pk)
44 45 46 47
	if err != nil {
		t.Fatal(err)
	}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48
	peerstore := peer.NewPeerstore()
49 50 51
	peerstore.AddPrivKey(p, sk)
	peerstore.AddPubKey(p, pk)
	peerstore.AddAddress(p, addr)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
52

53
	n, err := inet.NewNetwork(ctx, []ma.Multiaddr{addr}, p, peerstore)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54 55 56 57
	if err != nil {
		t.Fatal(err)
	}

58 59
	dss := dssync.MutexWrap(ds.NewMapDatastore())
	d := NewDHT(ctx, p, n, dss)
60

Jeromy's avatar
Jeromy committed
61 62 63
	d.Validators["v"] = func(u.Key, []byte) error {
		return nil
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64 65 66
	return d
}

67 68
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
69
	dhts := make([]*IpfsDHT, n)
70 71
	peers := make([]peer.ID, n)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
72
	for i := 0; i < n; i++ {
73 74 75
		addrs[i] = testutil.RandLocalTCPAddress()
		dhts[i] = setupDHT(ctx, t, addrs[i])
		peers[i] = dhts[i].self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
76 77 78 79 80
	}

	return addrs, peers, dhts
}

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

83 84 85 86
	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
87
	}
88 89 90 91

	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
92 93 94
	}
}

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

97 98
	ctx, cancel := context.WithCancel(ctx)

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

103 104 105 106
		// 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
107
		for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
108
			log.Debugf("bootstrapping round %d/%d -- %s\n", i, rounds, dht.self)
109
			dht.Bootstrap(ctx, 3)
110
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
111
	}
112 113

	cancel()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
114 115
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
116
func TestPing(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
117
	// t.Skip("skipping test to debug another")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
118
	ctx := context.Background()
119

120 121
	addrA := testutil.RandLocalTCPAddress()
	addrB := testutil.RandLocalTCPAddress()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
122

123 124
	dhtA := setupDHT(ctx, t, addrA)
	dhtB := setupDHT(ctx, t, addrB)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125

126 127
	peerA := dhtA.self
	peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
128

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
129 130
	defer dhtA.Close()
	defer dhtB.Close()
131 132
	defer dhtA.network.Close()
	defer dhtB.network.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
133

134
	connect(t, ctx, dhtA, dhtB)
135

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
136
	//Test that we can ping the node
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137
	ctxT, _ := context.WithTimeout(ctx, 100*time.Millisecond)
138
	if err := dhtA.Ping(ctxT, peerB); err != nil {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
139 140
		t.Fatal(err)
	}
141

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
142
	ctxT, _ = context.WithTimeout(ctx, 100*time.Millisecond)
143
	if err := dhtB.Ping(ctxT, peerA); err != nil {
144 145
		t.Fatal(err)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
146 147 148
}

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

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

153 154
	addrA := testutil.RandLocalTCPAddress()
	addrB := testutil.RandLocalTCPAddress()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
155

156 157
	dhtA := setupDHT(ctx, t, addrA)
	dhtB := setupDHT(ctx, t, addrB)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158

159 160 161 162
	defer dhtA.Close()
	defer dhtB.Close()
	defer dhtA.network.Close()
	defer dhtB.network.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
163

Jeromy's avatar
Jeromy committed
164 165 166 167 168 169
	vf := func(u.Key, []byte) error {
		return nil
	}
	dhtA.Validators["v"] = vf
	dhtB.Validators["v"] = vf

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

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
175
	ctxT, _ = context.WithTimeout(ctx, time.Second*2)
Jeromy's avatar
Jeromy committed
176
	val, err := dhtA.GetValue(ctxT, "/v/hello")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
177 178 179 180 181 182 183 184
	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
185
	ctxT, _ = context.WithTimeout(ctx, time.Second*2)
Jeromy's avatar
Jeromy committed
186
	val, err = dhtB.GetValue(ctxT, "/v/hello")
187 188 189 190 191 192 193
	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
194 195
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
196 197
func TestProvides(t *testing.T) {
	// t.Skip("skipping test to debug another")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
198
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
199

200
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
201 202
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
203
			dhts[i].Close()
204
			defer dhts[i].network.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
205 206 207
		}
	}()

208 209 210
	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
211

212
	for k, v := range testCaseValues {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
213
		log.Debugf("adding local values for %s = %s", k, v)
214 215 216 217 218 219 220 221 222 223 224 225
		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
226 227
	}

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

235 236 237 238 239 240 241
	// 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
242
		log.Debugf("getting providers for %s from %d", k, n)
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
		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
260
func TestBootstrap(t *testing.T) {
261 262 263 264
	if testing.Short() {
		t.SkipNow()
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
267
	nDHTs := 15
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
268 269 270 271 272 273 274 275 276 277 278 279 280
	_, _, dhts := setupDHTS(ctx, nDHTs, t)
	defer func() {
		for i := 0; i < nDHTs; i++ {
			dhts[i].Close()
			defer dhts[i].network.Close()
		}
	}()

	t.Logf("connecting %d dhts in a ring", nDHTs)
	for i := 0; i < nDHTs; i++ {
		connect(t, ctx, dhts[i], dhts[(i+1)%len(dhts)])
	}

281
	<-time.After(100 * time.Millisecond)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
282
	t.Logf("bootstrapping them so they find each other", nDHTs)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283 284
	ctxT, _ := context.WithTimeout(ctx, 5*time.Second)
	bootstrap(t, ctxT, dhts)
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 294 295 296 297
	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)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
298
	for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
299 300 301 302
		rtlen := dht.routingTable.Size()
		if rtlen < 4 {
			t.Errorf("routing table for %s only has %d peers", dht.self, rtlen)
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
303 304 305
	}
}

306 307
func TestProvidesMany(t *testing.T) {
	t.Skip("this test doesn't work")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
308
	// t.Skip("skipping test to debug another")
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
	ctx := context.Background()

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

	t.Logf("connecting %d dhts in a ring", nDHTs)
	for i := 0; i < nDHTs; i++ {
		connect(t, ctx, dhts[i], dhts[(i+1)%len(dhts)])
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
330 331 332 333 334 335 336 337 338
	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("")
		}
339
	}
340

341 342
	var providers = map[u.Key]peer.ID{}

343 344 345 346
	d := 0
	for k, v := range testCaseValues {
		d = (d + 1) % len(dhts)
		dht := dhts[d]
347
		providers[k] = dht.self
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

		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
367 368
	}

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

372 373
	errchan := make(chan error)

374
	ctxT, _ = context.WithTimeout(ctx, 5*time.Second)
375 376 377 378

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

380 381
		expected := providers[k]

382 383 384
		provchan := dht.FindProvidersAsync(ctxT, k, 1)
		select {
		case prov := <-provchan:
385 386
			actual := prov.ID
			if actual == "" {
387
				errchan <- fmt.Errorf("Got back nil provider (%s at %s)", k, dht.self)
388 389 390
			} else if actual != expected {
				errchan <- fmt.Errorf("Got back wrong provider (%s != %s) (%s at %s)",
					expected, actual, k, dht.self)
391 392 393
			}
		case <-ctxT.Done():
			errchan <- fmt.Errorf("Did not get a provider back (%s at %s)", k, dht.self)
Jeromy's avatar
Jeromy committed
394
		}
395 396 397 398 399
	}

	for k, _ := range testCaseValues {
		// everyone should be able to find it...
		for _, dht := range dhts {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
400
			log.Debugf("getting providers for %s at %s", k, dht.self)
401 402
			wg.Add(1)
			go getProvider(dht, k)
403
		}
404 405 406 407 408 409 410 411 412 413
	}

	// 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
414 415 416
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
417
func TestProvidesAsync(t *testing.T) {
418 419 420
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
421

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

424
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
425 426
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
427
			dhts[i].Close()
428
			defer dhts[i].network.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
429 430 431
		}
	}()

432 433 434
	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
435

436
	err := dhts[3].putLocal(u.Key("hello"), []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
437 438 439 440 441 442 443 444 445
	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
446
	err = dhts[3].Provide(ctx, u.Key("hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
447 448 449 450 451 452
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 60)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
453 454
	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
455
	select {
Jeromy's avatar
Jeromy committed
456 457 458 459
	case p, ok := <-provs:
		if !ok {
			t.Fatal("Provider channel was closed...")
		}
460
		if p.ID == "" {
Jeromy's avatar
Jeromy committed
461 462
			t.Fatal("Got back nil provider!")
		}
463
		if p.ID != dhts[3].self {
464
			t.Fatalf("got a provider, but not the right one. %s", p)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
465
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
466
	case <-ctxT.Done():
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
467 468 469 470
		t.Fatal("Didnt get back providers")
	}
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
471
func TestLayeredGet(t *testing.T) {
472 473 474
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
475

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

478
	_, _, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
479 480
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
481
			dhts[i].Close()
482
			defer dhts[i].network.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
483 484 485
		}
	}()

486 487 488
	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
489

490
	err := dhts[3].putLocal(u.Key("/v/hello"), []byte("world"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
491 492 493 494
	if err != nil {
		t.Fatal(err)
	}

Jeromy's avatar
Jeromy committed
495
	err = dhts[3].Provide(ctx, u.Key("/v/hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
496 497 498 499
	if err != nil {
		t.Fatal(err)
	}

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
502
	t.Log("interface was changed. GetValue should not use providers.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
503
	ctxT, _ := context.WithTimeout(ctx, time.Second)
Jeromy's avatar
Jeromy committed
504
	val, err := dhts[0].GetValue(ctxT, u.Key("/v/hello"))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
505 506
	if err != routing.ErrNotFound {
		t.Error(err)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
507
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
508 509 510 511 512
	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
513 514 515 516
	}
}

func TestFindPeer(t *testing.T) {
517 518 519
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
520

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

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
523
	_, peers, dhts := setupDHTS(ctx, 4, t)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
524 525
	defer func() {
		for i := 0; i < 4; i++ {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
526
			dhts[i].Close()
527
			dhts[i].network.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
528 529 530
		}
	}()

531 532 533
	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
534

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
535
	ctxT, _ := context.WithTimeout(ctx, time.Second)
536
	p, err := dhts[0].FindPeer(ctxT, peers[2])
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
537 538 539 540
	if err != nil {
		t.Fatal(err)
	}

541
	if p.ID == "" {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
542 543 544
		t.Fatal("Failed to find peer.")
	}

545
	if p.ID != peers[2] {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
546 547 548
		t.Fatal("Didnt find expected peer.")
	}
}
549

550
func TestFindPeersConnectedToPeer(t *testing.T) {
551 552
	t.Skip("not quite correct (see note)")

553 554 555 556 557 558 559 560 561 562
	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()
563
			dhts[i].network.Close()
564 565 566 567 568
		}
	}()

	// topology:
	// 0-1, 1-2, 1-3, 2-3
569 570 571 572
	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])
573 574 575 576 577 578 579

	// 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)
580
	pchan, err := dhts[0].FindPeersConnectedToPeer(ctxT, peers[2])
581 582 583 584
	if err != nil {
		t.Fatal(err)
	}

585 586
	// shouldFind := []peer.ID{peers[1], peers[3]}
	found := []peer.PeerInfo{}
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
	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.")
	}
}

603
func testPeerListsMatch(t *testing.T, p1, p2 []peer.ID) {
604 605 606 607 608 609 610 611 612

	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 {
613
		ids1[i] = string(p)
614 615 616
	}

	for i, p := range p2 {
617
		ids2[i] = string(p)
618 619 620 621 622 623 624 625 626 627 628 629
	}

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

630
func TestConnectCollision(t *testing.T) {
631 632 633
	if testing.Short() {
		t.SkipNow()
	}
634

635
	runTimes := 10
636

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

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

642 643
		addrA := testutil.RandLocalTCPAddress()
		addrB := testutil.RandLocalTCPAddress()
644

645 646
		dhtA := setupDHT(ctx, t, addrA)
		dhtB := setupDHT(ctx, t, addrB)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
647

648 649
		peerA := dhtA.self
		peerB := dhtB.self
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
650

651
		errs := make(chan error)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
652
		go func() {
653
			dhtA.peerstore.AddAddress(peerB, addrB)
654
			err := dhtA.Connect(ctx, peerB)
655
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
656 657
		}()
		go func() {
658
			dhtB.peerstore.AddAddress(peerA, addrA)
659
			err := dhtB.Connect(ctx, peerA)
660
			errs <- err
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
661 662 663 664
		}()

		timeout := time.After(time.Second)
		select {
665 666 667 668
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
669 670 671 672
		case <-timeout:
			t.Fatal("Timeout received!")
		}
		select {
673 674 675 676
		case e := <-errs:
			if e != nil {
				t.Fatal(e)
			}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
677 678 679 680
		case <-timeout:
			t.Fatal("Timeout received!")
		}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
681 682
		dhtA.Close()
		dhtB.Close()
683 684
		dhtA.network.Close()
		dhtB.network.Close()
Jeromy's avatar
Jeromy committed
685
	}
686
}