ext_test.go 10.1 KB
Newer Older
Jeromy's avatar
Jeromy committed
1 2 3
package dht

import (
Jeromy's avatar
Jeromy committed
4
	"context"
5
	"math/rand"
Jeromy's avatar
Jeromy committed
6
	"testing"
7
	"time"
Jeromy's avatar
Jeromy committed
8

9 10
	"github.com/libp2p/go-libp2p-core/network"
	"github.com/libp2p/go-libp2p-core/peer"
11
	"github.com/libp2p/go-libp2p-core/peerstore"
Aarsh Shah's avatar
Aarsh Shah committed
12
	"github.com/libp2p/go-libp2p-core/protocol"
13
	"github.com/libp2p/go-libp2p-core/routing"
Aarsh Shah's avatar
Aarsh Shah committed
14 15 16

	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
	record "github.com/libp2p/go-libp2p-record"
17 18
	swarmt "github.com/libp2p/go-libp2p-swarm/testing"
	bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
Aarsh Shah's avatar
Aarsh Shah committed
19
	mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
20

George Antoniadis's avatar
George Antoniadis committed
21
	ggio "github.com/gogo/protobuf/io"
22
	u "github.com/ipfs/go-ipfs-util"
Aarsh Shah's avatar
Aarsh Shah committed
23
	"github.com/stretchr/testify/require"
Jeromy's avatar
Jeromy committed
24 25
)

26 27 28
// Test that one hung request to a peer doesn't prevent another request
// using that same peer from obeying its context.
func TestHungRequest(t *testing.T) {
29 30 31 32 33 34 35
	ctx := context.Background()
	mn, err := mocknet.FullMeshConnected(ctx, 2)
	if err != nil {
		t.Fatal(err)
	}
	hosts := mn.Hosts()

Adin Schmahmann's avatar
Adin Schmahmann committed
36
	os := []Option{testPrefix, DisableAutoRefresh()}
37 38 39 40 41 42
	d, err := New(ctx, hosts[0], os...)
	if err != nil {
		t.Fatal(err)
	}
	// Hang on every request.
	hosts[1].SetStreamHandler(d.protocols[0], func(s network.Stream) {
Steven Allen's avatar
Steven Allen committed
43
		defer s.Reset() //nolint
44 45
		<-ctx.Done()
	})
Aarsh Shah's avatar
Aarsh Shah committed
46 47 48

	require.NoError(t, hosts[0].Peerstore().AddProtocols(hosts[1].ID(), protocol.ConvertToStrings(d.protocols)...))
	d.peerFound(ctx, hosts[1].ID(), true)
49 50 51 52

	ctx1, cancel1 := context.WithTimeout(ctx, 1*time.Second)
	defer cancel1()

53 54 55 56 57
	done := make(chan error, 1)
	go func() {
		_, err := d.GetClosestPeers(ctx1, testCaseCids[0].KeyString())
		done <- err
	}()
58 59 60 61

	time.Sleep(100 * time.Millisecond)
	ctx2, cancel2 := context.WithTimeout(ctx, 100*time.Millisecond)
	defer cancel2()
62 63
	err = d.Provide(ctx2, testCaseCids[0], true)
	if err != context.DeadlineExceeded {
64 65 66
		t.Errorf("expected to fail with deadline exceeded, got: %s", ctx2.Err())
	}
	select {
67 68
	case <-done:
		t.Errorf("GetClosestPeers should not have returned yet")
69
	default:
70 71 72 73
		err = <-done
		if err != context.DeadlineExceeded {
			t.Errorf("expected the deadline to be exceeded, got %s", err)
		}
74 75 76 77
	}

}

78
func TestGetFailures(t *testing.T) {
79 80 81
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
82

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

85 86 87
	host1 := bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport))
	host2 := bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport))

Adin Schmahmann's avatar
Adin Schmahmann committed
88
	d, err := New(ctx, host1, testPrefix, DisableAutoRefresh(), Mode(ModeServer))
89 90 91
	if err != nil {
		t.Fatal(err)
	}
92

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
93
	// Reply with failures to every message
94
	host2.SetStreamHandler(d.protocols[0], func(s network.Stream) {
Łukasz Magiera's avatar
Łukasz Magiera committed
95
		time.Sleep(400 * time.Millisecond)
96
		s.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
97 98
	})

99 100 101 102 103 104 105
	host1.Peerstore().AddAddrs(host2.ID(), host2.Addrs(), peerstore.ConnectedAddrTTL)
	_, err = host1.Network().DialPeer(ctx, host2.ID())
	if err != nil {
		t.Fatal(err)
	}
	time.Sleep(1 * time.Second)

106
	// This one should time out
Jeromy's avatar
Jeromy committed
107 108
	ctx1, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
	defer cancel()
109
	if _, err := d.GetValue(ctx1, "test"); err != nil {
110 111 112 113
		if merr, ok := err.(u.MultiErr); ok && len(merr) > 0 {
			err = merr[0]
		}

Łukasz Magiera's avatar
Łukasz Magiera committed
114
		if err != context.DeadlineExceeded {
115
			t.Fatal("Got different error than we expected", err)
116 117 118
		}
	} else {
		t.Fatal("Did not get expected error!")
Jeromy's avatar
Jeromy committed
119 120
	}

121
	t.Log("Timeout test passed.")
122

123
	// Reply with failures to every message
124
	host2.SetStreamHandler(d.protocols[0], func(s network.Stream) {
125 126
		defer s.Close()

127
		pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
128 129
		pbw := ggio.NewDelimitedWriter(s)

130
		pmes := new(pb.Message)
131
		if err := pbr.ReadMsg(pmes); err != nil {
132 133
			// user gave up
			return
134 135
		}

136
		resp := &pb.Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
137
			Type: pmes.Type,
138
		}
139
		_ = pbw.WriteMsg(resp)
140 141
	})

142 143 144 145 146
	// This one should fail with NotFound.
	// long context timeout to ensure we dont end too early.
	// the dht should be exhausting its query and returning not found.
	// (was 3 seconds before which should be _plenty_ of time, but maybe
	// travis machines really have a hard time...)
Jeromy's avatar
Jeromy committed
147 148
	ctx2, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
149
	_, err = d.GetValue(ctx2, "test")
150
	if err != nil {
151 152 153
		if merr, ok := err.(u.MultiErr); ok && len(merr) > 0 {
			err = merr[0]
		}
154
		if err != routing.ErrNotFound {
155
			t.Fatalf("Expected ErrNotFound, got: %s", err)
156 157 158 159
		}
	} else {
		t.Fatal("expected error, got none.")
	}
160

161 162
	t.Log("ErrNotFound check passed!")

163
	// Now we test this DHT's handleGetValue failure
164 165 166
	{
		typ := pb.Message_GET_VALUE
		str := "hello"
Jeromy's avatar
Jeromy committed
167

168
		rec := record.MakePutRecord(str, []byte("blah"))
169
		req := pb.Message{
170 171
			Type:   typ,
			Key:    []byte(str),
172 173
			Record: rec,
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
174

175
		s, err := host2.NewStream(context.Background(), host1.ID(), d.protocols[0])
176 177 178 179
		if err != nil {
			t.Fatal(err)
		}
		defer s.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
180

181
		pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
182
		pbw := ggio.NewDelimitedWriter(s)
183

184 185 186
		if err := pbw.WriteMsg(&req); err != nil {
			t.Fatal(err)
		}
187

188 189 190 191 192 193 194 195 196 197 198
		pmes := new(pb.Message)
		if err := pbr.ReadMsg(pmes); err != nil {
			t.Fatal(err)
		}
		if pmes.GetRecord() != nil {
			t.Fatal("shouldnt have value")
		}
		if pmes.GetProviderPeers() != nil {
			t.Fatal("shouldnt have provider peers")
		}
	}
Jeromy's avatar
Jeromy committed
199
}
Jeromy's avatar
Jeromy committed
200 201

func TestNotFound(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202
	// t.Skip("skipping test to debug another")
203 204 205
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
206

207
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
208
	mn, err := mocknet.FullMeshConnected(ctx, 16)
209 210 211
	if err != nil {
		t.Fatal(err)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
212
	hosts := mn.Hosts()
213

Adin Schmahmann's avatar
Adin Schmahmann committed
214
	os := []Option{testPrefix, DisableAutoRefresh()}
215
	d, err := New(ctx, hosts[0], os...)
216 217 218
	if err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
219

220
	for _, p := range hosts {
Aarsh Shah's avatar
Aarsh Shah committed
221
		d.peerFound(ctx, p.ID(), true)
Jeromy's avatar
Jeromy committed
222 223 224
	}

	// Reply with random peers to every message
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
225 226
	for _, host := range hosts {
		host := host // shadow loop var
227
		host.SetStreamHandler(d.protocols[0], func(s network.Stream) {
228
			defer s.Close()
Jeromy's avatar
Jeromy committed
229

230
			pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
231
			pbw := ggio.NewDelimitedWriter(s)
Jeromy's avatar
Jeromy committed
232

233 234 235
			pmes := new(pb.Message)
			if err := pbr.ReadMsg(pmes); err != nil {
				panic(err)
Jeromy's avatar
Jeromy committed
236 237
			}

238 239 240 241
			switch pmes.GetType() {
			case pb.Message_GET_VALUE:
				resp := &pb.Message{Type: pmes.Type}

242
				ps := []peer.AddrInfo{}
243
				for i := 0; i < 7; i++ {
244
					p := hosts[rand.Intn(len(hosts))].ID()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
245
					pi := host.Peerstore().PeerInfo(p)
246
					ps = append(ps, pi)
247 248
				}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
249
				resp.CloserPeers = pb.PeerInfosToPBPeers(d.host.Network(), ps)
250 251 252 253 254 255 256 257
				if err := pbw.WriteMsg(resp); err != nil {
					panic(err)
				}
			default:
				panic("Shouldnt recieve this.")
			}
		})
	}
Jeromy's avatar
Jeromy committed
258

259
	// long timeout to ensure timing is not at play.
rht's avatar
rht committed
260 261
	ctx, cancel := context.WithTimeout(ctx, time.Second*20)
	defer cancel()
262
	v, err := d.GetValue(ctx, "hello")
Matt Joiner's avatar
Matt Joiner committed
263
	logger.Debugf("get value got %v", v)
Jeromy's avatar
Jeromy committed
264
	if err != nil {
265 266 267
		if merr, ok := err.(u.MultiErr); ok && len(merr) > 0 {
			err = merr[0]
		}
Jeromy's avatar
Jeromy committed
268
		switch err {
269
		case routing.ErrNotFound:
Jeromy's avatar
Jeromy committed
270 271 272 273 274 275 276 277 278 279
			//Success!
			return
		case u.ErrTimeout:
			t.Fatal("Should not have gotten timeout!")
		default:
			t.Fatalf("Got unexpected error: %s", err)
		}
	}
	t.Fatal("Expected to recieve an error.")
}
280 281 282 283

// If less than K nodes are in the entire network, it should fail when we make
// a GET rpc and nobody has the value
func TestLessThanKResponses(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
284
	// t.Skip("skipping test to debug another")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
285 286
	// t.Skip("skipping test because it makes a lot of output")

287
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
288
	mn, err := mocknet.FullMeshConnected(ctx, 6)
289 290 291
	if err != nil {
		t.Fatal(err)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
292
	hosts := mn.Hosts()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
293

Adin Schmahmann's avatar
Adin Schmahmann committed
294
	os := []Option{testPrefix, DisableAutoRefresh()}
295
	d, err := New(ctx, hosts[0], os...)
296 297 298
	if err != nil {
		t.Fatal(err)
	}
299

300
	for i := 1; i < 5; i++ {
Aarsh Shah's avatar
Aarsh Shah committed
301
		d.peerFound(ctx, hosts[i].ID(), true)
302 303 304
	}

	// Reply with random peers to every message
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
305 306
	for _, host := range hosts {
		host := host // shadow loop var
307
		host.SetStreamHandler(d.protocols[0], func(s network.Stream) {
308 309
			defer s.Close()

310
			pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
311
			pbw := ggio.NewDelimitedWriter(s)
312

313 314 315
			pmes := new(pb.Message)
			if err := pbr.ReadMsg(pmes); err != nil {
				panic(err)
316 317
			}

318 319
			switch pmes.GetType() {
			case pb.Message_GET_VALUE:
320
				pi := host.Peerstore().PeerInfo(hosts[1].ID())
321 322
				resp := &pb.Message{
					Type:        pmes.Type,
323
					CloserPeers: pb.PeerInfosToPBPeers(d.host.Network(), []peer.AddrInfo{pi}),
324 325 326 327 328 329 330
				}

				if err := pbw.WriteMsg(resp); err != nil {
					panic(err)
				}
			default:
				panic("Shouldnt recieve this.")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
331
			}
332

333 334
		})
	}
335

rht's avatar
rht committed
336 337
	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()
338
	if _, err := d.GetValue(ctx, "hello"); err != nil {
339
		switch err {
340
		case routing.ErrNotFound:
341 342 343 344 345 346 347 348 349 350
			//Success!
			return
		case u.ErrTimeout:
			t.Fatal("Should not have gotten timeout!")
		default:
			t.Fatalf("Got unexpected error: %s", err)
		}
	}
	t.Fatal("Expected to recieve an error.")
}
351 352 353 354 355 356 357 358 359 360 361 362 363

// Test multiple queries against a node that closes its stream after every query.
func TestMultipleQueries(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}

	ctx := context.Background()
	mn, err := mocknet.FullMeshConnected(ctx, 2)
	if err != nil {
		t.Fatal(err)
	}
	hosts := mn.Hosts()
Adin Schmahmann's avatar
Adin Schmahmann committed
364
	os := []Option{testPrefix, DisableAutoRefresh()}
365
	d, err := New(ctx, hosts[0], os...)
366 367 368
	if err != nil {
		t.Fatal(err)
	}
369

Aarsh Shah's avatar
Aarsh Shah committed
370
	d.peerFound(ctx, hosts[1].ID(), true)
371 372 373

	// It would be nice to be able to just get a value and succeed but then
	// we'd need to deal with selectors and validators...
374
	hosts[1].SetStreamHandler(d.protocols[0], func(s network.Stream) {
375 376
		defer s.Close()

377
		pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
378 379 380 381 382 383 384 385 386 387 388 389
		pbw := ggio.NewDelimitedWriter(s)

		pmes := new(pb.Message)
		if err := pbr.ReadMsg(pmes); err != nil {
			panic(err)
		}

		switch pmes.GetType() {
		case pb.Message_GET_VALUE:
			pi := hosts[1].Peerstore().PeerInfo(hosts[0].ID())
			resp := &pb.Message{
				Type:        pmes.Type,
390
				CloserPeers: pb.PeerInfosToPBPeers(d.host.Network(), []peer.AddrInfo{pi}),
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
			}

			if err := pbw.WriteMsg(resp); err != nil {
				panic(err)
			}
		default:
			panic("Shouldnt recieve this.")
		}
	})

	// long timeout to ensure timing is not at play.
	ctx, cancel := context.WithTimeout(ctx, time.Second*20)
	defer cancel()
	for i := 0; i < 10; i++ {
		if _, err := d.GetValue(ctx, "hello"); err != nil {
			switch err {
			case routing.ErrNotFound:
				//Success!
				continue
			case u.ErrTimeout:
				t.Fatal("Should not have gotten timeout!")
			default:
				t.Fatalf("Got unexpected error: %s", err)
			}
		}
		t.Fatal("Expected to recieve an error.")
	}
}