github.com/benorgera/go-ethereum@v1.10.18-0.20220401011646-b3f57b1a73ba/p2p/server_test.go (about) 1 // Copyright 2014 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package p2p 18 19 import ( 20 "crypto/ecdsa" 21 "crypto/sha256" 22 "errors" 23 "io" 24 "math/rand" 25 "net" 26 "reflect" 27 "testing" 28 "time" 29 30 "github.com/ethereum/go-ethereum/crypto" 31 "github.com/ethereum/go-ethereum/internal/testlog" 32 "github.com/ethereum/go-ethereum/log" 33 "github.com/ethereum/go-ethereum/p2p/enode" 34 "github.com/ethereum/go-ethereum/p2p/enr" 35 "github.com/ethereum/go-ethereum/p2p/rlpx" 36 ) 37 38 type testTransport struct { 39 *rlpxTransport 40 rpub *ecdsa.PublicKey 41 closeErr error 42 } 43 44 func newTestTransport(rpub *ecdsa.PublicKey, fd net.Conn, dialDest *ecdsa.PublicKey) transport { 45 wrapped := newRLPX(fd, dialDest).(*rlpxTransport) 46 wrapped.conn.InitWithSecrets(rlpx.Secrets{ 47 AES: make([]byte, 16), 48 MAC: make([]byte, 16), 49 EgressMAC: sha256.New(), 50 IngressMAC: sha256.New(), 51 }) 52 return &testTransport{rpub: rpub, rlpxTransport: wrapped} 53 } 54 55 func (c *testTransport) doEncHandshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) { 56 return c.rpub, nil 57 } 58 59 func (c *testTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) { 60 pubkey := crypto.FromECDSAPub(c.rpub)[1:] 61 return &protoHandshake{ID: pubkey, Name: "test"}, nil 62 } 63 64 func (c *testTransport) close(err error) { 65 c.conn.Close() 66 c.closeErr = err 67 } 68 69 func startTestServer(t *testing.T, remoteKey *ecdsa.PublicKey, pf func(*Peer)) *Server { 70 config := Config{ 71 Name: "test", 72 MaxPeers: 10, 73 ListenAddr: "127.0.0.1:0", 74 NoDiscovery: true, 75 PrivateKey: newkey(), 76 Logger: testlog.Logger(t, log.LvlTrace), 77 } 78 server := &Server{ 79 Config: config, 80 newPeerHook: pf, 81 newTransport: func(fd net.Conn, dialDest *ecdsa.PublicKey) transport { 82 return newTestTransport(remoteKey, fd, dialDest) 83 }, 84 } 85 if err := server.Start(); err != nil { 86 t.Fatalf("Could not start server: %v", err) 87 } 88 return server 89 } 90 91 func TestServerListen(t *testing.T) { 92 // start the test server 93 connected := make(chan *Peer) 94 remid := &newkey().PublicKey 95 srv := startTestServer(t, remid, func(p *Peer) { 96 if p.ID() != enode.PubkeyToIDV4(remid) { 97 t.Error("peer func called with wrong node id") 98 } 99 connected <- p 100 }) 101 defer close(connected) 102 defer srv.Stop() 103 104 // dial the test server 105 conn, err := net.DialTimeout("tcp", srv.ListenAddr, 5*time.Second) 106 if err != nil { 107 t.Fatalf("could not dial: %v", err) 108 } 109 defer conn.Close() 110 111 select { 112 case peer := <-connected: 113 if peer.LocalAddr().String() != conn.RemoteAddr().String() { 114 t.Errorf("peer started with wrong conn: got %v, want %v", 115 peer.LocalAddr(), conn.RemoteAddr()) 116 } 117 peers := srv.Peers() 118 if !reflect.DeepEqual(peers, []*Peer{peer}) { 119 t.Errorf("Peers mismatch: got %v, want %v", peers, []*Peer{peer}) 120 } 121 case <-time.After(1 * time.Second): 122 t.Error("server did not accept within one second") 123 } 124 } 125 126 func TestServerDial(t *testing.T) { 127 // run a one-shot TCP server to handle the connection. 128 listener, err := net.Listen("tcp", "127.0.0.1:0") 129 if err != nil { 130 t.Fatalf("could not setup listener: %v", err) 131 } 132 defer listener.Close() 133 accepted := make(chan net.Conn, 1) 134 go func() { 135 conn, err := listener.Accept() 136 if err != nil { 137 return 138 } 139 accepted <- conn 140 }() 141 142 // start the server 143 connected := make(chan *Peer) 144 remid := &newkey().PublicKey 145 srv := startTestServer(t, remid, func(p *Peer) { connected <- p }) 146 defer close(connected) 147 defer srv.Stop() 148 149 // tell the server to connect 150 tcpAddr := listener.Addr().(*net.TCPAddr) 151 node := enode.NewV4(remid, tcpAddr.IP, tcpAddr.Port, 0) 152 srv.AddPeer(node) 153 154 select { 155 case conn := <-accepted: 156 defer conn.Close() 157 158 select { 159 case peer := <-connected: 160 if peer.ID() != enode.PubkeyToIDV4(remid) { 161 t.Errorf("peer has wrong id") 162 } 163 if peer.Name() != "test" { 164 t.Errorf("peer has wrong name") 165 } 166 if peer.RemoteAddr().String() != conn.LocalAddr().String() { 167 t.Errorf("peer started with wrong conn: got %v, want %v", 168 peer.RemoteAddr(), conn.LocalAddr()) 169 } 170 peers := srv.Peers() 171 if !reflect.DeepEqual(peers, []*Peer{peer}) { 172 t.Errorf("Peers mismatch: got %v, want %v", peers, []*Peer{peer}) 173 } 174 175 // Test AddTrustedPeer/RemoveTrustedPeer and changing Trusted flags 176 // Particularly for race conditions on changing the flag state. 177 if peer := srv.Peers()[0]; peer.Info().Network.Trusted { 178 t.Errorf("peer is trusted prematurely: %v", peer) 179 } 180 done := make(chan bool) 181 go func() { 182 srv.AddTrustedPeer(node) 183 if peer := srv.Peers()[0]; !peer.Info().Network.Trusted { 184 t.Errorf("peer is not trusted after AddTrustedPeer: %v", peer) 185 } 186 srv.RemoveTrustedPeer(node) 187 if peer := srv.Peers()[0]; peer.Info().Network.Trusted { 188 t.Errorf("peer is trusted after RemoveTrustedPeer: %v", peer) 189 } 190 done <- true 191 }() 192 // Trigger potential race conditions 193 peer = srv.Peers()[0] 194 _ = peer.Inbound() 195 _ = peer.Info() 196 <-done 197 case <-time.After(1 * time.Second): 198 t.Error("server did not launch peer within one second") 199 } 200 201 case <-time.After(1 * time.Second): 202 t.Error("server did not connect within one second") 203 } 204 } 205 206 // This test checks that RemovePeer disconnects the peer if it is connected. 207 func TestServerRemovePeerDisconnect(t *testing.T) { 208 srv1 := &Server{Config: Config{ 209 PrivateKey: newkey(), 210 MaxPeers: 1, 211 NoDiscovery: true, 212 Logger: testlog.Logger(t, log.LvlTrace).New("server", "1"), 213 }} 214 srv2 := &Server{Config: Config{ 215 PrivateKey: newkey(), 216 MaxPeers: 1, 217 NoDiscovery: true, 218 NoDial: true, 219 ListenAddr: "127.0.0.1:0", 220 Logger: testlog.Logger(t, log.LvlTrace).New("server", "2"), 221 }} 222 srv1.Start() 223 defer srv1.Stop() 224 srv2.Start() 225 defer srv2.Stop() 226 227 if !syncAddPeer(srv1, srv2.Self()) { 228 t.Fatal("peer not connected") 229 } 230 srv1.RemovePeer(srv2.Self()) 231 if srv1.PeerCount() > 0 { 232 t.Fatal("removed peer still connected") 233 } 234 } 235 236 // This test checks that connections are disconnected just after the encryption handshake 237 // when the server is at capacity. Trusted connections should still be accepted. 238 func TestServerAtCap(t *testing.T) { 239 trustedNode := newkey() 240 trustedID := enode.PubkeyToIDV4(&trustedNode.PublicKey) 241 srv := &Server{ 242 Config: Config{ 243 PrivateKey: newkey(), 244 MaxPeers: 10, 245 NoDial: true, 246 NoDiscovery: true, 247 TrustedNodes: []*enode.Node{newNode(trustedID, "")}, 248 Logger: testlog.Logger(t, log.LvlTrace), 249 }, 250 } 251 if err := srv.Start(); err != nil { 252 t.Fatalf("could not start: %v", err) 253 } 254 defer srv.Stop() 255 256 newconn := func(id enode.ID) *conn { 257 fd, _ := net.Pipe() 258 tx := newTestTransport(&trustedNode.PublicKey, fd, nil) 259 node := enode.SignNull(new(enr.Record), id) 260 return &conn{fd: fd, transport: tx, flags: inboundConn, node: node, cont: make(chan error)} 261 } 262 263 // Inject a few connections to fill up the peer set. 264 for i := 0; i < 10; i++ { 265 c := newconn(randomID()) 266 if err := srv.checkpoint(c, srv.checkpointAddPeer); err != nil { 267 t.Fatalf("could not add conn %d: %v", i, err) 268 } 269 } 270 // Try inserting a non-trusted connection. 271 anotherID := randomID() 272 c := newconn(anotherID) 273 if err := srv.checkpoint(c, srv.checkpointPostHandshake); err != DiscTooManyPeers { 274 t.Error("wrong error for insert:", err) 275 } 276 // Try inserting a trusted connection. 277 c = newconn(trustedID) 278 if err := srv.checkpoint(c, srv.checkpointPostHandshake); err != nil { 279 t.Error("unexpected error for trusted conn @posthandshake:", err) 280 } 281 if !c.is(trustedConn) { 282 t.Error("Server did not set trusted flag") 283 } 284 285 // Remove from trusted set and try again 286 srv.RemoveTrustedPeer(newNode(trustedID, "")) 287 c = newconn(trustedID) 288 if err := srv.checkpoint(c, srv.checkpointPostHandshake); err != DiscTooManyPeers { 289 t.Error("wrong error for insert:", err) 290 } 291 292 // Add anotherID to trusted set and try again 293 srv.AddTrustedPeer(newNode(anotherID, "")) 294 c = newconn(anotherID) 295 if err := srv.checkpoint(c, srv.checkpointPostHandshake); err != nil { 296 t.Error("unexpected error for trusted conn @posthandshake:", err) 297 } 298 if !c.is(trustedConn) { 299 t.Error("Server did not set trusted flag") 300 } 301 } 302 303 func TestServerPeerLimits(t *testing.T) { 304 srvkey := newkey() 305 clientkey := newkey() 306 clientnode := enode.NewV4(&clientkey.PublicKey, nil, 0, 0) 307 308 var tp = &setupTransport{ 309 pubkey: &clientkey.PublicKey, 310 phs: protoHandshake{ 311 ID: crypto.FromECDSAPub(&clientkey.PublicKey)[1:], 312 // Force "DiscUselessPeer" due to unmatching caps 313 // Caps: []Cap{discard.cap()}, 314 }, 315 } 316 317 srv := &Server{ 318 Config: Config{ 319 PrivateKey: srvkey, 320 MaxPeers: 0, 321 NoDial: true, 322 NoDiscovery: true, 323 Protocols: []Protocol{discard}, 324 Logger: testlog.Logger(t, log.LvlTrace), 325 }, 326 newTransport: func(fd net.Conn, dialDest *ecdsa.PublicKey) transport { return tp }, 327 } 328 if err := srv.Start(); err != nil { 329 t.Fatalf("couldn't start server: %v", err) 330 } 331 defer srv.Stop() 332 333 // Check that server is full (MaxPeers=0) 334 flags := dynDialedConn 335 dialDest := clientnode 336 conn, _ := net.Pipe() 337 srv.SetupConn(conn, flags, dialDest) 338 if tp.closeErr != DiscTooManyPeers { 339 t.Errorf("unexpected close error: %q", tp.closeErr) 340 } 341 conn.Close() 342 343 srv.AddTrustedPeer(clientnode) 344 345 // Check that server allows a trusted peer despite being full. 346 conn, _ = net.Pipe() 347 srv.SetupConn(conn, flags, dialDest) 348 if tp.closeErr == DiscTooManyPeers { 349 t.Errorf("failed to bypass MaxPeers with trusted node: %q", tp.closeErr) 350 } 351 352 if tp.closeErr != DiscUselessPeer { 353 t.Errorf("unexpected close error: %q", tp.closeErr) 354 } 355 conn.Close() 356 357 srv.RemoveTrustedPeer(clientnode) 358 359 // Check that server is full again. 360 conn, _ = net.Pipe() 361 srv.SetupConn(conn, flags, dialDest) 362 if tp.closeErr != DiscTooManyPeers { 363 t.Errorf("unexpected close error: %q", tp.closeErr) 364 } 365 conn.Close() 366 } 367 368 func TestServerSetupConn(t *testing.T) { 369 var ( 370 clientkey, srvkey = newkey(), newkey() 371 clientpub = &clientkey.PublicKey 372 srvpub = &srvkey.PublicKey 373 fooErr = errors.New("foo") 374 readErr = errors.New("read error") 375 ) 376 tests := []struct { 377 dontstart bool 378 tt *setupTransport 379 flags connFlag 380 dialDest *enode.Node 381 382 wantCloseErr error 383 wantCalls string 384 }{ 385 { 386 dontstart: true, 387 tt: &setupTransport{pubkey: clientpub}, 388 wantCalls: "close,", 389 wantCloseErr: errServerStopped, 390 }, 391 { 392 tt: &setupTransport{pubkey: clientpub, encHandshakeErr: readErr}, 393 flags: inboundConn, 394 wantCalls: "doEncHandshake,close,", 395 wantCloseErr: readErr, 396 }, 397 { 398 tt: &setupTransport{pubkey: clientpub, phs: protoHandshake{ID: randomID().Bytes()}}, 399 dialDest: enode.NewV4(clientpub, nil, 0, 0), 400 flags: dynDialedConn, 401 wantCalls: "doEncHandshake,doProtoHandshake,close,", 402 wantCloseErr: DiscUnexpectedIdentity, 403 }, 404 { 405 tt: &setupTransport{pubkey: clientpub, protoHandshakeErr: fooErr}, 406 dialDest: enode.NewV4(clientpub, nil, 0, 0), 407 flags: dynDialedConn, 408 wantCalls: "doEncHandshake,doProtoHandshake,close,", 409 wantCloseErr: fooErr, 410 }, 411 { 412 tt: &setupTransport{pubkey: srvpub, phs: protoHandshake{ID: crypto.FromECDSAPub(srvpub)[1:]}}, 413 flags: inboundConn, 414 wantCalls: "doEncHandshake,close,", 415 wantCloseErr: DiscSelf, 416 }, 417 { 418 tt: &setupTransport{pubkey: clientpub, phs: protoHandshake{ID: crypto.FromECDSAPub(clientpub)[1:]}}, 419 flags: inboundConn, 420 wantCalls: "doEncHandshake,doProtoHandshake,close,", 421 wantCloseErr: DiscUselessPeer, 422 }, 423 } 424 425 for i, test := range tests { 426 t.Run(test.wantCalls, func(t *testing.T) { 427 cfg := Config{ 428 PrivateKey: srvkey, 429 MaxPeers: 10, 430 NoDial: true, 431 NoDiscovery: true, 432 Protocols: []Protocol{discard}, 433 Logger: testlog.Logger(t, log.LvlTrace), 434 } 435 srv := &Server{ 436 Config: cfg, 437 newTransport: func(fd net.Conn, dialDest *ecdsa.PublicKey) transport { return test.tt }, 438 log: cfg.Logger, 439 } 440 if !test.dontstart { 441 if err := srv.Start(); err != nil { 442 t.Fatalf("couldn't start server: %v", err) 443 } 444 defer srv.Stop() 445 } 446 p1, _ := net.Pipe() 447 srv.SetupConn(p1, test.flags, test.dialDest) 448 if !errors.Is(test.tt.closeErr, test.wantCloseErr) { 449 t.Errorf("test %d: close error mismatch: got %q, want %q", i, test.tt.closeErr, test.wantCloseErr) 450 } 451 if test.tt.calls != test.wantCalls { 452 t.Errorf("test %d: calls mismatch: got %q, want %q", i, test.tt.calls, test.wantCalls) 453 } 454 }) 455 } 456 } 457 458 type setupTransport struct { 459 pubkey *ecdsa.PublicKey 460 encHandshakeErr error 461 phs protoHandshake 462 protoHandshakeErr error 463 464 calls string 465 closeErr error 466 } 467 468 func (c *setupTransport) doEncHandshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) { 469 c.calls += "doEncHandshake," 470 return c.pubkey, c.encHandshakeErr 471 } 472 473 func (c *setupTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) { 474 c.calls += "doProtoHandshake," 475 if c.protoHandshakeErr != nil { 476 return nil, c.protoHandshakeErr 477 } 478 return &c.phs, nil 479 } 480 func (c *setupTransport) close(err error) { 481 c.calls += "close," 482 c.closeErr = err 483 } 484 485 // setupConn shouldn't write to/read from the connection. 486 func (c *setupTransport) WriteMsg(Msg) error { 487 panic("WriteMsg called on setupTransport") 488 } 489 func (c *setupTransport) ReadMsg() (Msg, error) { 490 panic("ReadMsg called on setupTransport") 491 } 492 493 func newkey() *ecdsa.PrivateKey { 494 key, err := crypto.GenerateKey() 495 if err != nil { 496 panic("couldn't generate key: " + err.Error()) 497 } 498 return key 499 } 500 501 func randomID() (id enode.ID) { 502 for i := range id { 503 id[i] = byte(rand.Intn(255)) 504 } 505 return id 506 } 507 508 // This test checks that inbound connections are throttled by IP. 509 func TestServerInboundThrottle(t *testing.T) { 510 const timeout = 5 * time.Second 511 newTransportCalled := make(chan struct{}) 512 srv := &Server{ 513 Config: Config{ 514 PrivateKey: newkey(), 515 ListenAddr: "127.0.0.1:0", 516 MaxPeers: 10, 517 NoDial: true, 518 NoDiscovery: true, 519 Protocols: []Protocol{discard}, 520 Logger: testlog.Logger(t, log.LvlTrace), 521 }, 522 newTransport: func(fd net.Conn, dialDest *ecdsa.PublicKey) transport { 523 newTransportCalled <- struct{}{} 524 return newRLPX(fd, dialDest) 525 }, 526 listenFunc: func(network, laddr string) (net.Listener, error) { 527 fakeAddr := &net.TCPAddr{IP: net.IP{95, 33, 21, 2}, Port: 4444} 528 return listenFakeAddr(network, laddr, fakeAddr) 529 }, 530 } 531 if err := srv.Start(); err != nil { 532 t.Fatal("can't start: ", err) 533 } 534 defer srv.Stop() 535 536 // Dial the test server. 537 conn, err := net.DialTimeout("tcp", srv.ListenAddr, timeout) 538 if err != nil { 539 t.Fatalf("could not dial: %v", err) 540 } 541 select { 542 case <-newTransportCalled: 543 // OK 544 case <-time.After(timeout): 545 t.Error("newTransport not called") 546 } 547 conn.Close() 548 549 // Dial again. This time the server should close the connection immediately. 550 connClosed := make(chan struct{}, 1) 551 conn, err = net.DialTimeout("tcp", srv.ListenAddr, timeout) 552 if err != nil { 553 t.Fatalf("could not dial: %v", err) 554 } 555 defer conn.Close() 556 go func() { 557 conn.SetDeadline(time.Now().Add(timeout)) 558 buf := make([]byte, 10) 559 if n, err := conn.Read(buf); err != io.EOF || n != 0 { 560 t.Errorf("expected io.EOF and n == 0, got error %q and n == %d", err, n) 561 } 562 connClosed <- struct{}{} 563 }() 564 select { 565 case <-connClosed: 566 // OK 567 case <-newTransportCalled: 568 t.Error("newTransport called for second attempt") 569 case <-time.After(timeout): 570 t.Error("connection not closed within timeout") 571 } 572 } 573 574 func listenFakeAddr(network, laddr string, remoteAddr net.Addr) (net.Listener, error) { 575 l, err := net.Listen(network, laddr) 576 if err == nil { 577 l = &fakeAddrListener{l, remoteAddr} 578 } 579 return l, err 580 } 581 582 // fakeAddrListener is a listener that creates connections with a mocked remote address. 583 type fakeAddrListener struct { 584 net.Listener 585 remoteAddr net.Addr 586 } 587 588 type fakeAddrConn struct { 589 net.Conn 590 remoteAddr net.Addr 591 } 592 593 func (l *fakeAddrListener) Accept() (net.Conn, error) { 594 c, err := l.Listener.Accept() 595 if err != nil { 596 return nil, err 597 } 598 return &fakeAddrConn{c, l.remoteAddr}, nil 599 } 600 601 func (c *fakeAddrConn) RemoteAddr() net.Addr { 602 return c.remoteAddr 603 } 604 605 func syncAddPeer(srv *Server, node *enode.Node) bool { 606 var ( 607 ch = make(chan *PeerEvent) 608 sub = srv.SubscribeEvents(ch) 609 timeout = time.After(2 * time.Second) 610 ) 611 defer sub.Unsubscribe() 612 srv.AddPeer(node) 613 for { 614 select { 615 case ev := <-ch: 616 if ev.Type == PeerEventTypeAdd && ev.Peer == node.ID() { 617 return true 618 } 619 case <-timeout: 620 return false 621 } 622 } 623 }