basic_host_test.go 8.65 KB
Newer Older
Jeromy's avatar
Jeromy committed
1
package basichost
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
2
3
4

import (
	"bytes"
5
	"context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	"io"
7
	"sort"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8
	"testing"
9
	"time"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
10

Steven Allen's avatar
Steven Allen committed
11
12
	testutil "github.com/libp2p/go-testutil"

Jeromy's avatar
Jeromy committed
13
	host "github.com/libp2p/go-libp2p-host"
Jeromy's avatar
Jeromy committed
14
	inet "github.com/libp2p/go-libp2p-net"
15
	pstore "github.com/libp2p/go-libp2p-peerstore"
Jeromy's avatar
Jeromy committed
16
	protocol "github.com/libp2p/go-libp2p-protocol"
Steven Allen's avatar
Steven Allen committed
17
	swarmt "github.com/libp2p/go-libp2p-swarm/testing"
18
	ma "github.com/multiformats/go-multiaddr"
19
	madns "github.com/multiformats/go-multiaddr-dns"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
20
21
22
23
24
)

func TestHostSimple(t *testing.T) {

	ctx := context.Background()
Steven Allen's avatar
Steven Allen committed
25
26
	h1 := New(swarmt.GenSwarm(t, ctx))
	h2 := New(swarmt.GenSwarm(t, ctx))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
	defer h1.Close()
	defer h2.Close()

	h2pi := h2.Peerstore().PeerInfo(h2.ID())
	if err := h1.Connect(ctx, h2pi); err != nil {
		t.Fatal(err)
	}

	piper, pipew := io.Pipe()
	h2.SetStreamHandler(protocol.TestingID, func(s inet.Stream) {
		defer s.Close()
		w := io.MultiWriter(s, pipew)
		io.Copy(w, s) // mirror everything
	})

42
	s, err := h1.NewStream(ctx, h2pi.ID, protocol.TestingID)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
	if err != nil {
		t.Fatal(err)
	}

	// write to the stream
	buf1 := []byte("abcdefghijkl")
	if _, err := s.Write(buf1); err != nil {
		t.Fatal(err)
	}

	// get it from the stream (echoed)
	buf2 := make([]byte, len(buf1))
	if _, err := io.ReadFull(s, buf2); err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(buf1, buf2) {
Kevin Atkinson's avatar
Kevin Atkinson committed
59
		t.Fatalf("buf1 != buf2 -- %x != %x", buf1, buf2)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
60
61
62
63
64
65
66
67
	}

	// get it from the pipe (tee)
	buf3 := make([]byte, len(buf1))
	if _, err := io.ReadFull(piper, buf3); err != nil {
		t.Fatal(err)
	}
	if !bytes.Equal(buf1, buf3) {
Kevin Atkinson's avatar
Kevin Atkinson committed
68
		t.Fatalf("buf1 != buf3 -- %x != %x", buf1, buf3)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
69
70
	}
}
71

72
73
74
75
76
77
78
func TestHostAddrsFactory(t *testing.T) {
	maddr := ma.StringCast("/ip4/1.2.3.4/tcp/1234")
	addrsFactory := func(addrs []ma.Multiaddr) []ma.Multiaddr {
		return []ma.Multiaddr{maddr}
	}

	ctx := context.Background()
Steven Allen's avatar
Steven Allen committed
79
	h := New(swarmt.GenSwarm(t, ctx), AddrsFactory(addrsFactory))
80
81
82
83
84
85
	defer h.Close()

	addrs := h.Addrs()
	if len(addrs) != 1 {
		t.Fatalf("expected 1 addr, got %d", len(addrs))
	}
Steven Allen's avatar
Steven Allen committed
86
	if !addrs[0].Equal(maddr) {
87
88
89
90
		t.Fatalf("expected %s, got %s", maddr.String(), addrs[0].String())
	}
}

91
func getHostPair(ctx context.Context, t *testing.T) (host.Host, host.Host) {
Steven Allen's avatar
Steven Allen committed
92
93
	h1 := New(swarmt.GenSwarm(t, ctx))
	h2 := New(swarmt.GenSwarm(t, ctx))
94
95
96
97
98
99
100
101
102

	h2pi := h2.Peerstore().PeerInfo(h2.ID())
	if err := h1.Connect(ctx, h2pi); err != nil {
		t.Fatal(err)
	}

	return h1, h2
}

103
func assertWait(t *testing.T, c chan protocol.ID, exp protocol.ID) {
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
	select {
	case proto := <-c:
		if proto != exp {
			t.Fatal("should have connected on ", exp)
		}
	case <-time.After(time.Second * 5):
		t.Fatal("timeout waiting for stream")
	}
}

func TestHostProtoPreference(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	h1, h2 := getHostPair(ctx, t)
	defer h1.Close()
	defer h2.Close()

	protoOld := protocol.ID("/testing")
	protoNew := protocol.ID("/testing/1.1.0")
	protoMinor := protocol.ID("/testing/1.2.0")

126
	connectedOn := make(chan protocol.ID)
127
128
129
130
131
132
133
134
135
136
137
138
139

	handler := func(s inet.Stream) {
		connectedOn <- s.Protocol()
		s.Close()
	}

	h1.SetStreamHandler(protoOld, handler)

	s, err := h2.NewStream(ctx, h1.ID(), protoMinor, protoNew, protoOld)
	if err != nil {
		t.Fatal(err)
	}

140
	assertWait(t, connectedOn, protoOld)
141
142
	s.Close()

143
	mfunc, err := host.MultistreamSemverMatcher(protoMinor)
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
	if err != nil {
		t.Fatal(err)
	}

	h1.SetStreamHandlerMatch(protoMinor, mfunc, handler)

	// remembered preference will be chosen first, even when the other side newly supports it
	s2, err := h2.NewStream(ctx, h1.ID(), protoMinor, protoNew, protoOld)
	if err != nil {
		t.Fatal(err)
	}

	// required to force 'lazy' handshake
	_, err = s2.Write([]byte("hello"))
	if err != nil {
		t.Fatal(err)
	}

162
	assertWait(t, connectedOn, protoOld)
163
164
165
166
167
168
169
170

	s2.Close()

	s3, err := h2.NewStream(ctx, h1.ID(), protoMinor)
	if err != nil {
		t.Fatal(err)
	}

171
	assertWait(t, connectedOn, protoMinor)
172
173
174
175
176
177
178
179
180
181
182
183
184
	s3.Close()
}

func TestHostProtoMismatch(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	h1, h2 := getHostPair(ctx, t)
	defer h1.Close()
	defer h2.Close()

	h1.SetStreamHandler("/super", func(s inet.Stream) {
		t.Error("shouldnt get here")
Steven Allen's avatar
Steven Allen committed
185
		s.Reset()
186
187
188
189
190
191
192
193
194
195
196
197
	})

	_, err := h2.NewStream(ctx, h1.ID(), "/foo", "/bar", "/baz/1.0.0")
	if err == nil {
		t.Fatal("expected new stream to fail")
	}
}

func TestHostProtoPreknowledge(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

Steven Allen's avatar
Steven Allen committed
198
199
	h1 := New(swarmt.GenSwarm(t, ctx))
	h2 := New(swarmt.GenSwarm(t, ctx))
200

201
	conn := make(chan protocol.ID)
202
203
204
205
206
207
208
209
210
211
212
213
214
215
	handler := func(s inet.Stream) {
		conn <- s.Protocol()
		s.Close()
	}

	h1.SetStreamHandler("/super", handler)

	h2pi := h2.Peerstore().PeerInfo(h2.ID())
	if err := h1.Connect(ctx, h2pi); err != nil {
		t.Fatal(err)
	}
	defer h1.Close()
	defer h2.Close()

216
	// wait for identify handshake to finish completely
217
	select {
218
	case <-h1.Ids.IdentifyWait(h1.Network().ConnsToPeer(h2.ID())[0]):
219
220
221
222
223
	case <-time.After(time.Second * 5):
		t.Fatal("timed out waiting for identify")
	}

	select {
224
	case <-h2.Ids.IdentifyWait(h2.Network().ConnsToPeer(h1.ID())[0]):
225
226
227
	case <-time.After(time.Second * 5):
		t.Fatal("timed out waiting for identify")
	}
228

229
230
231
232
233
234
235
236
	h1.SetStreamHandler("/foo", handler)

	s, err := h2.NewStream(ctx, h1.ID(), "/foo", "/bar", "/super")
	if err != nil {
		t.Fatal(err)
	}

	select {
237
238
	case p := <-conn:
		t.Fatal("shouldnt have gotten connection yet, we should have a lazy stream: ", p)
239
240
241
242
243
244
245
246
247
248
249
250
	case <-time.After(time.Millisecond * 50):
	}

	_, err = s.Read(nil)
	if err != nil {
		t.Fatal(err)
	}

	assertWait(t, conn, "/super")

	s.Close()
}
251
252
253
254
255
256
257
258
259

func TestNewDialOld(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	h1, h2 := getHostPair(ctx, t)
	defer h1.Close()
	defer h2.Close()

260
	connectedOn := make(chan protocol.ID)
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
	h1.SetStreamHandler("/testing", func(s inet.Stream) {
		connectedOn <- s.Protocol()
		s.Close()
	})

	s, err := h2.NewStream(ctx, h1.ID(), "/testing/1.0.0", "/testing")
	if err != nil {
		t.Fatal(err)
	}

	assertWait(t, connectedOn, "/testing")

	if s.Protocol() != "/testing" {
		t.Fatal("shoould have gotten /testing")
	}

	s.Close()
}
279
280
281
282
283
284
285
286
287

func TestProtoDowngrade(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	h1, h2 := getHostPair(ctx, t)
	defer h1.Close()
	defer h2.Close()

288
	connectedOn := make(chan protocol.ID)
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
	h1.SetStreamHandler("/testing/1.0.0", func(s inet.Stream) {
		connectedOn <- s.Protocol()
		s.Close()
	})

	s, err := h2.NewStream(ctx, h1.ID(), "/testing/1.0.0", "/testing")
	if err != nil {
		t.Fatal(err)
	}

	assertWait(t, connectedOn, "/testing/1.0.0")

	if s.Protocol() != "/testing/1.0.0" {
		t.Fatal("shoould have gotten /testing")
	}
	s.Close()

	h1.Network().ConnsToPeer(h2.ID())[0].Close()

	time.Sleep(time.Millisecond * 50) // allow notifications to propogate
	h1.RemoveStreamHandler("/testing/1.0.0")
	h1.SetStreamHandler("/testing", func(s inet.Stream) {
		connectedOn <- s.Protocol()
		s.Close()
	})

	h2pi := h2.Peerstore().PeerInfo(h2.ID())
	if err := h1.Connect(ctx, h2pi); err != nil {
		t.Fatal(err)
	}

	s2, err := h2.NewStream(ctx, h1.ID(), "/testing/1.0.0", "/testing")
	if err != nil {
		t.Fatal(err)
	}

	_, err = s2.Write(nil)
	if err != nil {
		t.Fatal(err)
	}

	assertWait(t, connectedOn, "/testing")

	if s2.Protocol() != "/testing" {
		t.Fatal("shoould have gotten /testing")
	}
	s2.Close()

}
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362

func TestAddrResolution(t *testing.T) {
	ctx := context.Background()

	p1, err := testutil.RandPeerID()
	if err != nil {
		t.Error(err)
	}
	p2, err := testutil.RandPeerID()
	if err != nil {
		t.Error(err)
	}
	addr1 := ma.StringCast("/dnsaddr/example.com")
	addr2 := ma.StringCast("/ip4/192.0.2.1/tcp/123")
	p2paddr1 := ma.StringCast("/dnsaddr/example.com/ipfs/" + p1.Pretty())
	p2paddr2 := ma.StringCast("/ip4/192.0.2.1/tcp/123/ipfs/" + p1.Pretty())
	p2paddr3 := ma.StringCast("/ip4/192.0.2.1/tcp/123/ipfs/" + p2.Pretty())

	backend := &madns.MockBackend{
		TXT: map[string][]string{"_dnsaddr.example.com": []string{
			"dnsaddr=" + p2paddr2.String(), "dnsaddr=" + p2paddr3.String(),
		}},
	}
	resolver := &madns.Resolver{Backend: backend}

Steven Allen's avatar
Steven Allen committed
363
	h := New(swarmt.GenSwarm(t, ctx), resolver)
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
	defer h.Close()

	pi, err := pstore.InfoFromP2pAddr(p2paddr1)
	if err != nil {
		t.Error(err)
	}

	tctx, cancel := context.WithTimeout(ctx, time.Millisecond*100)
	defer cancel()
	_ = h.Connect(tctx, *pi)

	addrs := h.Peerstore().Addrs(pi.ID)
	sort.Sort(sortedMultiaddrs(addrs))

	if len(addrs) != 2 || !addrs[0].Equal(addr1) || !addrs[1].Equal(addr2) {
		t.Fatalf("expected [%s %s], got %+v", addr1, addr2, addrs)
	}
}

type sortedMultiaddrs []ma.Multiaddr

func (sma sortedMultiaddrs) Len() int      { return len(sma) }
func (sma sortedMultiaddrs) Swap(i, j int) { sma[i], sma[j] = sma[j], sma[i] }
func (sma sortedMultiaddrs) Less(i, j int) bool {
	return bytes.Compare(sma[i].Bytes(), sma[j].Bytes()) == 1
}