aboutsummaryrefslogtreecommitdiffstats
path: root/p2p/server_test.go
blob: 5ee9c5cebb9ab1150fc28ff791bb1de90b94b38e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
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
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package p2p

import (
    "bytes"
    "crypto/ecdsa"
    "io"
    "math/rand"
    "net"
    "sync"
    "testing"
    "time"

    "github.com/ethereum/go-ethereum/crypto"
    "github.com/ethereum/go-ethereum/crypto/sha3"
    "github.com/ethereum/go-ethereum/p2p/discover"
)

func startTestServer(t *testing.T, pf newPeerHook) *Server {
    server := &Server{
        Name:        "test",
        MaxPeers:    10,
        ListenAddr:  "127.0.0.1:0",
        PrivateKey:  newkey(),
        newPeerHook: pf,
        setupFunc: func(fd net.Conn, prv *ecdsa.PrivateKey, our *protoHandshake, dial *discover.Node, atcap bool, trusted map[discover.NodeID]bool) (*conn, error) {
            id := randomID()
            rw := newRlpxFrameRW(fd, secrets{
                MAC:        zero16,
                AES:        zero16,
                IngressMAC: sha3.NewKeccak256(),
                EgressMAC:  sha3.NewKeccak256(),
            })
            return &conn{
                MsgReadWriter:  rw,
                protoHandshake: &protoHandshake{ID: id, Version: baseProtocolVersion},
            }, nil
        },
    }
    if err := server.Start(); err != nil {
        t.Fatalf("Could not start server: %v", err)
    }
    return server
}

func TestServerListen(t *testing.T) {
    defer testlog(t).detach()

    // start the test server
    connected := make(chan *Peer)
    srv := startTestServer(t, func(p *Peer) {
        if p == nil {
            t.Error("peer func called with nil conn")
        }
        connected <- p
    })
    defer close(connected)
    defer srv.Stop()

    // dial the test server
    conn, err := net.DialTimeout("tcp", srv.ListenAddr, 5*time.Second)
    if err != nil {
        t.Fatalf("could not dial: %v", err)
    }
    defer conn.Close()

    select {
    case peer := <-connected:
        if peer.LocalAddr().String() != conn.RemoteAddr().String() {
            t.Errorf("peer started with wrong conn: got %v, want %v",
                peer.LocalAddr(), conn.RemoteAddr())
        }
    case <-time.After(1 * time.Second):
        t.Error("server did not accept within one second")
    }
}

func TestServerDial(t *testing.T) {
    defer testlog(t).detach()

    // run a one-shot TCP server to handle the connection.
    listener, err := net.Listen("tcp", "127.0.0.1:0")
    if err != nil {
        t.Fatalf("could not setup listener: %v")
    }
    defer listener.Close()
    accepted := make(chan net.Conn)
    go func() {
        conn, err := listener.Accept()
        if err != nil {
            t.Error("accept error:", err)
            return
        }
        conn.Close()
        accepted <- conn
    }()

    // start the server
    connected := make(chan *Peer)
    srv := startTestServer(t, func(p *Peer) { connected <- p })
    defer close(connected)
    defer srv.Stop()

    // tell the server to connect
    tcpAddr := listener.Addr().(*net.TCPAddr)
    srv.staticDial <- &discover.Node{IP: tcpAddr.IP, TCPPort: tcpAddr.Port}

    select {
    case conn := <-accepted:
        select {
        case peer := <-connected:
            if peer.RemoteAddr().String() != conn.LocalAddr().String() {
                t.Errorf("peer started with wrong conn: got %v, want %v",
                    peer.RemoteAddr(), conn.LocalAddr())
            }
            // TODO: validate more fields
        case <-time.After(1 * time.Second):
            t.Error("server did not launch peer within one second")
        }

    case <-time.After(1 * time.Second):
        t.Error("server did not connect within one second")
    }
}

func TestServerBroadcast(t *testing.T) {
    defer testlog(t).detach()

    var connected sync.WaitGroup
    srv := startTestServer(t, func(p *Peer) {
        p.running = matchProtocols([]Protocol{discard}, []Cap{discard.cap()}, p.rw)
        connected.Done()
    })
    defer srv.Stop()

    // create a few peers
    var conns = make([]net.Conn, 8)
    connected.Add(len(conns))
    deadline := time.Now().Add(3 * time.Second)
    dialer := &net.Dialer{Deadline: deadline}
    for i := range conns {
        conn, err := dialer.Dial("tcp", srv.ListenAddr)
        if err != nil {
            t.Fatalf("conn %d: dial error: %v", i, err)
        }
        defer conn.Close()
        conn.SetDeadline(deadline)
        conns[i] = conn
    }
    connected.Wait()

    // broadcast one message
    srv.Broadcast("discard", 0, []string{"foo"})
    golden := unhex("66e94d166f0a2c3b884cfa59ca34")

    // check that the message has been written everywhere
    for i, conn := range conns {
        buf := make([]byte, len(golden))
        if _, err := io.ReadFull(conn, buf); err != nil {
            t.Errorf("conn %d: read error: %v", i, err)
        } else if !bytes.Equal(buf, golden) {
            t.Errorf("conn %d: msg mismatch\ngot:  %x\nwant: %x", i, buf, golden)
        }
    }
}

// This test checks that connections are disconnected
// just after the encryption handshake when the server is
// at capacity.
//
// It also serves as a light-weight integration test.
func TestServerDisconnectAtCap(t *testing.T) {
    defer testlog(t).detach()

    started := make(chan *Peer)
    srv := &Server{
        ListenAddr: "127.0.0.1:0",
        PrivateKey: newkey(),
        MaxPeers:   10,
        NoDial:     true,
        // This hook signals that the peer was actually started. We
        // need to wait for the peer to be started before dialing the
        // next connection to get a deterministic peer count.
        newPeerHook: func(p *Peer) { started <- p },
    }
    if err := srv.Start(); err != nil {
        t.Fatal(err)
    }
    defer srv.Stop()

    nconns := srv.MaxPeers + 1
    dialer := &net.Dialer{Deadline: time.Now().Add(3 * time.Second)}
    for i := 0; i < nconns; i++ {
        conn, err := dialer.Dial("tcp", srv.ListenAddr)
        if err != nil {
            t.Fatalf("conn %d: dial error: %v", i, err)
        }
        // Close the connection when the test ends, before
        // shutting down the server.
        defer conn.Close()
        // Run the handshakes just like a real peer would.
        key := newkey()
        hs := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)}
        _, err = setupConn(conn, key, hs, srv.Self(), false, srv.trustedNodes)
        if i == nconns-1 {
            // When handling the last connection, the server should
            // disconnect immediately instead of running the protocol
            // handshake.
            if err != DiscTooManyPeers {
                t.Errorf("conn %d: got error %q, expected %q", i, err, DiscTooManyPeers)
            }
        } else {
            // For all earlier connections, the handshake should go through.
            if err != nil {
                t.Fatalf("conn %d: unexpected error: %v", i, err)
            }
            // Wait for runPeer to be started.
            <-started
        }
    }
}

// Tests that static peers are (re)connected, and done so even above max peers.
func TestServerStaticPeers(t *testing.T) {
    defer testlog(t).detach()

    // Create a test server with limited connection slots
    started := make(chan *Peer)
    server := &Server{
        ListenAddr:  "127.0.0.1:0",
        PrivateKey:  newkey(),
        MaxPeers:    3,
        newPeerHook: func(p *Peer) { started <- p },
        staticCycle: time.Second,
    }
    if err := server.Start(); err != nil {
        t.Fatal(err)
    }
    defer server.Stop()

    // Fill up all the slots on the server
    dialer := &net.Dialer{Deadline: time.Now().Add(3 * time.Second)}
    for i := 0; i < server.MaxPeers; i++ {
        // Establish a new connection
        conn, err := dialer.Dial("tcp", server.ListenAddr)
        if err != nil {
            t.Fatalf("conn %d: dial error: %v", i, err)
        }
        defer conn.Close()

        // Run the handshakes just like a real peer would, and wait for completion
        key := newkey()
        shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)}
        if _, err = setupConn(conn, key, shake, server.Self(), false, server.trustedNodes); err != nil {
            t.Fatalf("conn %d: unexpected error: %v", i, err)
        }
        <-started
    }
    // Open a TCP listener to accept static connections
    listener, err := net.Listen("tcp", "127.0.0.1:0")
    if err != nil {
        t.Fatalf("failed to setup listener: %v", err)
    }
    defer listener.Close()

    connected := make(chan net.Conn)
    go func() {
        for i := 0; i < 3; i++ {
            conn, err := listener.Accept()
            if err == nil {
                connected <- conn
            }
        }
    }()
    // Inject a static node and wait for a remote dial, then redial, then nothing
    addr := listener.Addr().(*net.TCPAddr)
    static := &discover.Node{
        ID:      discover.PubkeyID(&newkey().PublicKey),
        IP:      addr.IP,
        TCPPort: addr.Port,
    }
    server.AddPeer(static)

    select {
    case conn := <-connected:
        // Close the first connection, expect redial
        conn.Close()

    case <-time.After(2 * server.staticCycle):
        t.Fatalf("remote dial timeout")
    }

    select {
    case conn := <-connected:
        // Keep the second connection, don't expect redial
        defer conn.Close()

    case <-time.After(2 * server.staticCycle):
        t.Fatalf("remote re-dial timeout")
    }

    select {
    case <-time.After(2 * server.staticCycle):
        // Timeout as no dial occurred

    case <-connected:
        t.Fatalf("connected node dialed")
    }
}

// Tests that trusted peers and can connect above max peer caps.
func TestServerTrustedPeers(t *testing.T) {
    defer testlog(t).detach()

    // Create a trusted peer to accept connections from
    key := newkey()
    trusted := &discover.Node{
        ID: discover.PubkeyID(&key.PublicKey),
    }
    // Create a test server with limited connection slots
    started := make(chan *Peer)
    server := &Server{
        ListenAddr:   "127.0.0.1:0",
        PrivateKey:   newkey(),
        MaxPeers:     3,
        NoDial:       true,
        TrustedNodes: []*discover.Node{trusted},
        newPeerHook:  func(p *Peer) { started <- p },
    }
    if err := server.Start(); err != nil {
        t.Fatal(err)
    }
    defer server.Stop()

    // Fill up all the slots on the server
    dialer := &net.Dialer{Deadline: time.Now().Add(3 * time.Second)}
    for i := 0; i < server.MaxPeers; i++ {
        // Establish a new connection
        conn, err := dialer.Dial("tcp", server.ListenAddr)
        if err != nil {
            t.Fatalf("conn %d: dial error: %v", i, err)
        }
        defer conn.Close()

        // Run the handshakes just like a real peer would, and wait for completion
        key := newkey()
        shake := &protoHandshake{Version: baseProtocolVersion, ID: discover.PubkeyID(&key.PublicKey)}
        if _, err = setupConn(conn, key, shake, server.Self(), false, server.trustedNodes); err != nil {
            t.Fatalf("conn %d: unexpected error: %v", i, err)
        }
        <-started
    }
    // Dial from the trusted peer, ensure connection is accepted
    conn, err := dialer.Dial("tcp", server.ListenAddr)
    if err != nil {
        t.Fatalf("trusted node: dial error: %v", err)
    }
    defer conn.Close()

    shake := &protoHandshake{Version: baseProtocolVersion, ID: trusted.ID}
    if _, err = setupConn(conn, key, shake, server.Self(), false, server.trustedNodes); err != nil {
        t.Fatalf("trusted node: unexpected error: %v", err)
    }
    select {
    case <-started:
        // Ok, trusted peer accepted

    case <-time.After(100 * time.Millisecond):
        t.Fatalf("trusted node timeout")
    }
}

func newkey() *ecdsa.PrivateKey {
    key, err := crypto.GenerateKey()
    if err != nil {
        panic("couldn't generate key: " + err.Error())
    }
    return key
}

func randomID() (id discover.NodeID) {
    for i := range id {
        id[i] = byte(rand.Intn(255))
    }
    return id
}