ext_test.go 9.32 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 11
	"github.com/libp2p/go-libp2p-core/network"
	"github.com/libp2p/go-libp2p-core/peer"
	"github.com/libp2p/go-libp2p-core/routing"
12
	opts "github.com/libp2p/go-libp2p-kad-dht/opts"
13

George Antoniadis's avatar
George Antoniadis committed
14
	ggio "github.com/gogo/protobuf/io"
15
	u "github.com/ipfs/go-ipfs-util"
16
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
17 18
	record "github.com/libp2p/go-libp2p-record"
	mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
Jeromy's avatar
Jeromy committed
19 20
)

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
func TestHang(t *testing.T) {
	ctx := context.Background()
	mn, err := mocknet.FullMeshConnected(ctx, 2)
	if err != nil {
		t.Fatal(err)
	}
	hosts := mn.Hosts()

	os := []opts.Option{opts.DisableAutoRefresh()}
	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) {
		defer s.Reset()
		<-ctx.Done()
	})
	d.Update(ctx, hosts[1].ID())

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

	peers, err := d.GetClosestPeers(ctx1, testCaseCids[0].KeyString())
	if err != nil {
		t.Fatal(err)
	}

	time.Sleep(100 * time.Millisecond)
	ctx2, cancel2 := context.WithTimeout(ctx, 100*time.Millisecond)
	defer cancel2()
	_ = d.Provide(ctx2, testCaseCids[0], true)
	if ctx2.Err() != context.DeadlineExceeded {
		t.Errorf("expected to fail with deadline exceeded, got: %s", ctx2.Err())
	}
	select {
	case <-peers:
		t.Error("GetClosestPeers should not have returned yet")
	default:
	}

}

64
func TestGetFailures(t *testing.T) {
65 66 67
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
68

69
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
70
	mn, err := mocknet.FullMeshConnected(ctx, 2)
71 72 73
	if err != nil {
		t.Fatal(err)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
74
	hosts := mn.Hosts()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
75

76
	os := []opts.Option{opts.DisableAutoRefresh()}
77
	d, err := New(ctx, hosts[0], os...)
78 79 80
	if err != nil {
		t.Fatal(err)
	}
81
	d.Update(ctx, hosts[1].ID())
82

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
83
	// Reply with failures to every message
84
	hosts[1].SetStreamHandler(d.protocols[0], func(s network.Stream) {
Łukasz Magiera's avatar
Łukasz Magiera committed
85
		time.Sleep(400 * time.Millisecond)
86
		s.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
87 88
	})

89
	// This one should time out
Jeromy's avatar
Jeromy committed
90 91
	ctx1, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
	defer cancel()
92
	if _, err := d.GetValue(ctx1, "test"); err != nil {
93 94 95 96
		if merr, ok := err.(u.MultiErr); ok && len(merr) > 0 {
			err = merr[0]
		}

Łukasz Magiera's avatar
Łukasz Magiera committed
97
		if err != context.DeadlineExceeded {
98
			t.Fatal("Got different error than we expected", err)
99 100 101
		}
	} else {
		t.Fatal("Did not get expected error!")
Jeromy's avatar
Jeromy committed
102 103
	}

104
	t.Log("Timeout test passed.")
105

106
	// Reply with failures to every message
107
	hosts[1].SetStreamHandler(d.protocols[0], func(s network.Stream) {
108 109
		defer s.Close()

110
		pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
111 112
		pbw := ggio.NewDelimitedWriter(s)

113
		pmes := new(pb.Message)
114 115
		if err := pbr.ReadMsg(pmes); err != nil {
			panic(err)
116 117
		}

118
		resp := &pb.Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
119
			Type: pmes.Type,
120
		}
121 122 123
		if err := pbw.WriteMsg(resp); err != nil {
			panic(err)
		}
124 125
	})

126 127 128 129 130
	// 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
131 132
	ctx2, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
133
	_, err = d.GetValue(ctx2, "test")
134
	if err != nil {
135 136 137
		if merr, ok := err.(u.MultiErr); ok && len(merr) > 0 {
			err = merr[0]
		}
138
		if err != routing.ErrNotFound {
139
			t.Fatalf("Expected ErrNotFound, got: %s", err)
140 141 142 143
		}
	} else {
		t.Fatal("expected error, got none.")
	}
144

145 146
	t.Log("ErrNotFound check passed!")

147
	// Now we test this DHT's handleGetValue failure
148 149 150
	{
		typ := pb.Message_GET_VALUE
		str := "hello"
Jeromy's avatar
Jeromy committed
151

152
		rec := record.MakePutRecord(str, []byte("blah"))
153
		req := pb.Message{
154 155
			Type:   typ,
			Key:    []byte(str),
156 157
			Record: rec,
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
158

159
		s, err := hosts[1].NewStream(context.Background(), hosts[0].ID(), d.protocols[0])
160 161 162 163
		if err != nil {
			t.Fatal(err)
		}
		defer s.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164

165
		pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
166
		pbw := ggio.NewDelimitedWriter(s)
167

168 169 170
		if err := pbw.WriteMsg(&req); err != nil {
			t.Fatal(err)
		}
171

172 173 174 175 176 177 178 179 180 181 182
		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
183
}
Jeromy's avatar
Jeromy committed
184 185

func TestNotFound(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
186
	// t.Skip("skipping test to debug another")
187 188 189
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
190

191
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192
	mn, err := mocknet.FullMeshConnected(ctx, 16)
193 194 195
	if err != nil {
		t.Fatal(err)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
196
	hosts := mn.Hosts()
197

198
	os := []opts.Option{opts.DisableAutoRefresh()}
199
	d, err := New(ctx, hosts[0], os...)
200 201 202
	if err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
203

204 205
	for _, p := range hosts {
		d.Update(ctx, p.ID())
Jeromy's avatar
Jeromy committed
206 207 208
	}

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

214
			pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
215
			pbw := ggio.NewDelimitedWriter(s)
Jeromy's avatar
Jeromy committed
216

217 218 219
			pmes := new(pb.Message)
			if err := pbr.ReadMsg(pmes); err != nil {
				panic(err)
Jeromy's avatar
Jeromy committed
220 221
			}

222 223 224 225
			switch pmes.GetType() {
			case pb.Message_GET_VALUE:
				resp := &pb.Message{Type: pmes.Type}

226
				ps := []peer.AddrInfo{}
227
				for i := 0; i < 7; i++ {
228
					p := hosts[rand.Intn(len(hosts))].ID()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
229
					pi := host.Peerstore().PeerInfo(p)
230
					ps = append(ps, pi)
231 232
				}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
233
				resp.CloserPeers = pb.PeerInfosToPBPeers(d.host.Network(), ps)
234 235 236 237 238 239 240 241
				if err := pbw.WriteMsg(resp); err != nil {
					panic(err)
				}
			default:
				panic("Shouldnt recieve this.")
			}
		})
	}
Jeromy's avatar
Jeromy committed
242

243
	// long timeout to ensure timing is not at play.
rht's avatar
rht committed
244 245
	ctx, cancel := context.WithTimeout(ctx, time.Second*20)
	defer cancel()
246
	v, err := d.GetValue(ctx, "hello")
Matt Joiner's avatar
Matt Joiner committed
247
	logger.Debugf("get value got %v", v)
Jeromy's avatar
Jeromy committed
248
	if err != nil {
249 250 251
		if merr, ok := err.(u.MultiErr); ok && len(merr) > 0 {
			err = merr[0]
		}
Jeromy's avatar
Jeromy committed
252
		switch err {
253
		case routing.ErrNotFound:
Jeromy's avatar
Jeromy committed
254 255 256 257 258 259 260 261 262 263
			//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.")
}
264 265 266 267

// 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
268
	// t.Skip("skipping test to debug another")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
269 270
	// t.Skip("skipping test because it makes a lot of output")

271
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
272
	mn, err := mocknet.FullMeshConnected(ctx, 6)
273 274 275
	if err != nil {
		t.Fatal(err)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
276
	hosts := mn.Hosts()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
277

278
	os := []opts.Option{opts.DisableAutoRefresh()}
279
	d, err := New(ctx, hosts[0], os...)
280 281 282
	if err != nil {
		t.Fatal(err)
	}
283

284
	for i := 1; i < 5; i++ {
285
		d.Update(ctx, hosts[i].ID())
286 287 288
	}

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

294
			pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
295
			pbw := ggio.NewDelimitedWriter(s)
296

297 298 299
			pmes := new(pb.Message)
			if err := pbr.ReadMsg(pmes); err != nil {
				panic(err)
300 301
			}

302 303
			switch pmes.GetType() {
			case pb.Message_GET_VALUE:
304
				pi := host.Peerstore().PeerInfo(hosts[1].ID())
305 306
				resp := &pb.Message{
					Type:        pmes.Type,
307
					CloserPeers: pb.PeerInfosToPBPeers(d.host.Network(), []peer.AddrInfo{pi}),
308 309 310 311 312 313 314
				}

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

317 318
		})
	}
319

rht's avatar
rht committed
320 321
	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()
322
	if _, err := d.GetValue(ctx, "hello"); err != nil {
323
		switch err {
324
		case routing.ErrNotFound:
325 326 327 328 329 330 331 332 333 334
			//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.")
}
335 336 337 338 339 340 341 342 343 344 345 346 347

// 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()
348
	os := []opts.Option{opts.DisableAutoRefresh()}
349
	d, err := New(ctx, hosts[0], os...)
350 351 352
	if err != nil {
		t.Fatal(err)
	}
353 354 355 356 357

	d.Update(ctx, hosts[1].ID())

	// 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...
358
	hosts[1].SetStreamHandler(d.protocols[0], func(s network.Stream) {
359 360
		defer s.Close()

361
		pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
362 363 364 365 366 367 368 369 370 371 372 373
		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,
374
				CloserPeers: pb.PeerInfosToPBPeers(d.host.Network(), []peer.AddrInfo{pi}),
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
			}

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