ext_test.go 9.64 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"
12
	"github.com/libp2p/go-libp2p-core/routing"
13
	opts "github.com/libp2p/go-libp2p-kad-dht/opts"
14 15
	swarmt "github.com/libp2p/go-libp2p-swarm/testing"
	bhost "github.com/libp2p/go-libp2p/p2p/host/basic"
16

George Antoniadis's avatar
George Antoniadis committed
17
	ggio "github.com/gogo/protobuf/io"
18
	u "github.com/ipfs/go-ipfs-util"
19
	pb "github.com/libp2p/go-libp2p-kad-dht/pb"
20 21
	record "github.com/libp2p/go-libp2p-record"
	mocknet "github.com/libp2p/go-libp2p/p2p/net/mock"
Jeromy's avatar
Jeromy committed
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 64 65 66
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:
	}

}

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

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

74 75 76 77
	host1 := bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport))
	host2 := bhost.New(swarmt.GenSwarm(t, ctx, swarmt.OptDisableReuseport))

	d, err := New(ctx, host1, opts.DisableAutoRefresh())
78 79 80
	if err != nil {
		t.Fatal(err)
	}
81

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

88 89 90 91 92 93 94
	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)

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

Łukasz Magiera's avatar
Łukasz Magiera committed
103
		if err != context.DeadlineExceeded {
104
			t.Fatal("Got different error than we expected", err)
105 106 107
		}
	} else {
		t.Fatal("Did not get expected error!")
Jeromy's avatar
Jeromy committed
108 109
	}

110
	t.Log("Timeout test passed.")
111

112
	// Reply with failures to every message
113
	host2.SetStreamHandler(d.protocols[0], func(s network.Stream) {
114 115
		defer s.Close()

116
		pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
117 118
		pbw := ggio.NewDelimitedWriter(s)

119
		pmes := new(pb.Message)
120 121
		if err := pbr.ReadMsg(pmes); err != nil {
			panic(err)
122 123
		}

124
		resp := &pb.Message{
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
125
			Type: pmes.Type,
126
		}
127 128 129
		if err := pbw.WriteMsg(resp); err != nil {
			panic(err)
		}
130 131
	})

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

151 152
	t.Log("ErrNotFound check passed!")

153
	// Now we test this DHT's handleGetValue failure
154 155 156
	{
		typ := pb.Message_GET_VALUE
		str := "hello"
Jeromy's avatar
Jeromy committed
157

158
		rec := record.MakePutRecord(str, []byte("blah"))
159
		req := pb.Message{
160 161
			Type:   typ,
			Key:    []byte(str),
162 163
			Record: rec,
		}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
164

165
		s, err := host2.NewStream(context.Background(), host1.ID(), d.protocols[0])
166 167 168 169
		if err != nil {
			t.Fatal(err)
		}
		defer s.Close()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
170

171
		pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
172
		pbw := ggio.NewDelimitedWriter(s)
173

174 175 176
		if err := pbw.WriteMsg(&req); err != nil {
			t.Fatal(err)
		}
177

178 179 180 181 182 183 184 185 186 187 188
		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
189
}
Jeromy's avatar
Jeromy committed
190 191

func TestNotFound(t *testing.T) {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
192
	// t.Skip("skipping test to debug another")
193 194 195
	if testing.Short() {
		t.SkipNow()
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
196

197
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
198
	mn, err := mocknet.FullMeshConnected(ctx, 16)
199 200 201
	if err != nil {
		t.Fatal(err)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
202
	hosts := mn.Hosts()
203

204
	os := []opts.Option{opts.DisableAutoRefresh()}
205
	d, err := New(ctx, hosts[0], os...)
206 207 208
	if err != nil {
		t.Fatal(err)
	}
Jeromy's avatar
Jeromy committed
209

210 211
	for _, p := range hosts {
		d.Update(ctx, p.ID())
Jeromy's avatar
Jeromy committed
212 213 214
	}

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

220
			pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
221
			pbw := ggio.NewDelimitedWriter(s)
Jeromy's avatar
Jeromy committed
222

223 224 225
			pmes := new(pb.Message)
			if err := pbr.ReadMsg(pmes); err != nil {
				panic(err)
Jeromy's avatar
Jeromy committed
226 227
			}

228 229 230 231
			switch pmes.GetType() {
			case pb.Message_GET_VALUE:
				resp := &pb.Message{Type: pmes.Type}

232
				ps := []peer.AddrInfo{}
233
				for i := 0; i < 7; i++ {
234
					p := hosts[rand.Intn(len(hosts))].ID()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
235
					pi := host.Peerstore().PeerInfo(p)
236
					ps = append(ps, pi)
237 238
				}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
239
				resp.CloserPeers = pb.PeerInfosToPBPeers(d.host.Network(), ps)
240 241 242 243 244 245 246 247
				if err := pbw.WriteMsg(resp); err != nil {
					panic(err)
				}
			default:
				panic("Shouldnt recieve this.")
			}
		})
	}
Jeromy's avatar
Jeromy committed
248

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

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

277
	ctx := context.Background()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
278
	mn, err := mocknet.FullMeshConnected(ctx, 6)
279 280 281
	if err != nil {
		t.Fatal(err)
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
282
	hosts := mn.Hosts()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
283

284
	os := []opts.Option{opts.DisableAutoRefresh()}
285
	d, err := New(ctx, hosts[0], os...)
286 287 288
	if err != nil {
		t.Fatal(err)
	}
289

290
	for i := 1; i < 5; i++ {
291
		d.Update(ctx, hosts[i].ID())
292 293 294
	}

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

300
			pbr := ggio.NewDelimitedReader(s, network.MessageSizeMax)
301
			pbw := ggio.NewDelimitedWriter(s)
302

303 304 305
			pmes := new(pb.Message)
			if err := pbr.ReadMsg(pmes); err != nil {
				panic(err)
306 307
			}

308 309
			switch pmes.GetType() {
			case pb.Message_GET_VALUE:
310
				pi := host.Peerstore().PeerInfo(hosts[1].ID())
311 312
				resp := &pb.Message{
					Type:        pmes.Type,
313
					CloserPeers: pb.PeerInfosToPBPeers(d.host.Network(), []peer.AddrInfo{pi}),
314 315 316 317 318 319 320
				}

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

323 324
		})
	}
325

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

// 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()
354
	os := []opts.Option{opts.DisableAutoRefresh()}
355
	d, err := New(ctx, hosts[0], os...)
356 357 358
	if err != nil {
		t.Fatal(err)
	}
359 360 361 362 363

	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...
364
	hosts[1].SetStreamHandler(d.protocols[0], func(s network.Stream) {
365 366
		defer s.Close()

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

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