gitee.com/liu-zhao234568/cntest@v1.0.0/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 "gitee.com/liu-zhao234568/cntest/crypto" 31 "gitee.com/liu-zhao234568/cntest/internal/testlog" 32 "gitee.com/liu-zhao234568/cntest/log" 33 "gitee.com/liu-zhao234568/cntest/p2p/enode" 34 "gitee.com/liu-zhao234568/cntest/p2p/enr" 35 "gitee.com/liu-zhao234568/cntest/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 ) 374 tests := []struct { 375 dontstart bool 376 tt *setupTransport 377 flags connFlag 378 dialDest *enode.Node 379 380 wantCloseErr error 381 wantCalls string 382 }{ 383 { 384 dontstart: true, 385 tt: &setupTransport{pubkey: clientpub}, 386 wantCalls: "close,", 387 wantCloseErr: errServerStopped, 388 }, 389 { 390 tt: &setupTransport{pubkey: clientpub, encHandshakeErr: errors.New("read error")}, 391 flags: inboundConn, 392 wantCalls: "doEncHandshake,close,", 393 wantCloseErr: errors.New("read error"), 394 }, 395 { 396 tt: &setupTransport{pubkey: clientpub, phs: protoHandshake{ID: randomID().Bytes()}}, 397 dialDest: enode.NewV4(clientpub, nil, 0, 0), 398 flags: dynDialedConn, 399 wantCalls: "doEncHandshake,doProtoHandshake,close,", 400 wantCloseErr: DiscUnexpectedIdentity, 401 }, 402 { 403 tt: &setupTransport{pubkey: clientpub, protoHandshakeErr: errors.New("foo")}, 404 dialDest: enode.NewV4(clientpub, nil, 0, 0), 405 flags: dynDialedConn, 406 wantCalls: "doEncHandshake,doProtoHandshake,close,", 407 wantCloseErr: errors.New("foo"), 408 }, 409 { 410 tt: &setupTransport{pubkey: srvpub, phs: protoHandshake{ID: crypto.FromECDSAPub(srvpub)[1:]}}, 411 flags: inboundConn, 412 wantCalls: "doEncHandshake,close,", 413 wantCloseErr: DiscSelf, 414 }, 415 { 416 tt: &setupTransport{pubkey: clientpub, phs: protoHandshake{ID: crypto.FromECDSAPub(clientpub)[1:]}}, 417 flags: inboundConn, 418 wantCalls: "doEncHandshake,doProtoHandshake,close,", 419 wantCloseErr: DiscUselessPeer, 420 }, 421 } 422 423 for i, test := range tests { 424 t.Run(test.wantCalls, func(t *testing.T) { 425 cfg := Config{ 426 PrivateKey: srvkey, 427 MaxPeers: 10, 428 NoDial: true, 429 NoDiscovery: true, 430 Protocols: []Protocol{discard}, 431 Logger: testlog.Logger(t, log.LvlTrace), 432 } 433 srv := &Server{ 434 Config: cfg, 435 newTransport: func(fd net.Conn, dialDest *ecdsa.PublicKey) transport { return test.tt }, 436 log: cfg.Logger, 437 } 438 if !test.dontstart { 439 if err := srv.Start(); err != nil { 440 t.Fatalf("couldn't start server: %v", err) 441 } 442 defer srv.Stop() 443 } 444 p1, _ := net.Pipe() 445 srv.SetupConn(p1, test.flags, test.dialDest) 446 if !reflect.DeepEqual(test.tt.closeErr, test.wantCloseErr) { 447 t.Errorf("test %d: close error mismatch: got %q, want %q", i, test.tt.closeErr, test.wantCloseErr) 448 } 449 if test.tt.calls != test.wantCalls { 450 t.Errorf("test %d: calls mismatch: got %q, want %q", i, test.tt.calls, test.wantCalls) 451 } 452 }) 453 } 454 } 455 456 type setupTransport struct { 457 pubkey *ecdsa.PublicKey 458 encHandshakeErr error 459 phs protoHandshake 460 protoHandshakeErr error 461 462 calls string 463 closeErr error 464 } 465 466 func (c *setupTransport) doEncHandshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) { 467 c.calls += "doEncHandshake," 468 return c.pubkey, c.encHandshakeErr 469 } 470 471 func (c *setupTransport) doProtoHandshake(our *protoHandshake) (*protoHandshake, error) { 472 c.calls += "doProtoHandshake," 473 if c.protoHandshakeErr != nil { 474 return nil, c.protoHandshakeErr 475 } 476 return &c.phs, nil 477 } 478 func (c *setupTransport) close(err error) { 479 c.calls += "close," 480 c.closeErr = err 481 } 482 483 // setupConn shouldn't write to/read from the connection. 484 func (c *setupTransport) WriteMsg(Msg) error { 485 panic("WriteMsg called on setupTransport") 486 } 487 func (c *setupTransport) ReadMsg() (Msg, error) { 488 panic("ReadMsg called on setupTransport") 489 } 490 491 func newkey() *ecdsa.PrivateKey { 492 key, err := crypto.GenerateKey() 493 if err != nil { 494 panic("couldn't generate key: " + err.Error()) 495 } 496 return key 497 } 498 499 func randomID() (id enode.ID) { 500 for i := range id { 501 id[i] = byte(rand.Intn(255)) 502 } 503 return id 504 } 505 506 // This test checks that inbound connections are throttled by IP. 507 func TestServerInboundThrottle(t *testing.T) { 508 const timeout = 5 * time.Second 509 newTransportCalled := make(chan struct{}) 510 srv := &Server{ 511 Config: Config{ 512 PrivateKey: newkey(), 513 ListenAddr: "127.0.0.1:0", 514 MaxPeers: 10, 515 NoDial: true, 516 NoDiscovery: true, 517 Protocols: []Protocol{discard}, 518 Logger: testlog.Logger(t, log.LvlTrace), 519 }, 520 newTransport: func(fd net.Conn, dialDest *ecdsa.PublicKey) transport { 521 newTransportCalled <- struct{}{} 522 return newRLPX(fd, dialDest) 523 }, 524 listenFunc: func(network, laddr string) (net.Listener, error) { 525 fakeAddr := &net.TCPAddr{IP: net.IP{95, 33, 21, 2}, Port: 4444} 526 return listenFakeAddr(network, laddr, fakeAddr) 527 }, 528 } 529 if err := srv.Start(); err != nil { 530 t.Fatal("can't start: ", err) 531 } 532 defer srv.Stop() 533 534 // Dial the test server. 535 conn, err := net.DialTimeout("tcp", srv.ListenAddr, timeout) 536 if err != nil { 537 t.Fatalf("could not dial: %v", err) 538 } 539 select { 540 case <-newTransportCalled: 541 // OK 542 case <-time.After(timeout): 543 t.Error("newTransport not called") 544 } 545 conn.Close() 546 547 // Dial again. This time the server should close the connection immediately. 548 connClosed := make(chan struct{}, 1) 549 conn, err = net.DialTimeout("tcp", srv.ListenAddr, timeout) 550 if err != nil { 551 t.Fatalf("could not dial: %v", err) 552 } 553 defer conn.Close() 554 go func() { 555 conn.SetDeadline(time.Now().Add(timeout)) 556 buf := make([]byte, 10) 557 if n, err := conn.Read(buf); err != io.EOF || n != 0 { 558 t.Errorf("expected io.EOF and n == 0, got error %q and n == %d", err, n) 559 } 560 connClosed <- struct{}{} 561 }() 562 select { 563 case <-connClosed: 564 // OK 565 case <-newTransportCalled: 566 t.Error("newTransport called for second attempt") 567 case <-time.After(timeout): 568 t.Error("connection not closed within timeout") 569 } 570 } 571 572 func listenFakeAddr(network, laddr string, remoteAddr net.Addr) (net.Listener, error) { 573 l, err := net.Listen(network, laddr) 574 if err == nil { 575 l = &fakeAddrListener{l, remoteAddr} 576 } 577 return l, err 578 } 579 580 // fakeAddrListener is a listener that creates connections with a mocked remote address. 581 type fakeAddrListener struct { 582 net.Listener 583 remoteAddr net.Addr 584 } 585 586 type fakeAddrConn struct { 587 net.Conn 588 remoteAddr net.Addr 589 } 590 591 func (l *fakeAddrListener) Accept() (net.Conn, error) { 592 c, err := l.Listener.Accept() 593 if err != nil { 594 return nil, err 595 } 596 return &fakeAddrConn{c, l.remoteAddr}, nil 597 } 598 599 func (c *fakeAddrConn) RemoteAddr() net.Addr { 600 return c.remoteAddr 601 } 602 603 func syncAddPeer(srv *Server, node *enode.Node) bool { 604 var ( 605 ch = make(chan *PeerEvent) 606 sub = srv.SubscribeEvents(ch) 607 timeout = time.After(2 * time.Second) 608 ) 609 defer sub.Unsubscribe() 610 srv.AddPeer(node) 611 for { 612 select { 613 case ev := <-ch: 614 if ev.Type == PeerEventTypeAdd && ev.Peer == node.ID() { 615 return true 616 } 617 case <-timeout: 618 return false 619 } 620 } 621 }