github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/p2p/server.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 implements the Ethereum p2p network protocols. 18 package p2p 19 20 import ( 21 "bytes" 22 "crypto/ecdsa" 23 "encoding/hex" 24 "errors" 25 "fmt" 26 "net" 27 "slices" 28 "sync" 29 "sync/atomic" 30 "time" 31 32 "github.com/ethereum/go-ethereum/common" 33 "github.com/ethereum/go-ethereum/common/mclock" 34 "github.com/ethereum/go-ethereum/crypto" 35 "github.com/ethereum/go-ethereum/event" 36 "github.com/ethereum/go-ethereum/log" 37 "github.com/ethereum/go-ethereum/p2p/discover" 38 "github.com/ethereum/go-ethereum/p2p/enode" 39 "github.com/ethereum/go-ethereum/p2p/enr" 40 "github.com/ethereum/go-ethereum/p2p/nat" 41 "github.com/ethereum/go-ethereum/p2p/netutil" 42 ) 43 44 const ( 45 defaultDialTimeout = 15 * time.Second 46 47 // This is the fairness knob for the discovery mixer. When looking for peers, we'll 48 // wait this long for a single source of candidates before moving on and trying other 49 // sources. 50 discmixTimeout = 5 * time.Second 51 52 // Connectivity defaults. 53 defaultMaxPendingPeers = 50 54 defaultDialRatio = 3 55 56 // This time limits inbound connection attempts per source IP. 57 inboundThrottleTime = 30 * time.Second 58 59 // Maximum time allowed for reading a complete message. 60 // This is effectively the amount of time a connection can be idle. 61 frameReadTimeout = 30 * time.Second 62 63 // Maximum amount of time allowed for writing a complete message. 64 frameWriteTimeout = 20 * time.Second 65 ) 66 67 var ( 68 errServerStopped = errors.New("server stopped") 69 errEncHandshakeError = errors.New("rlpx enc error") 70 errProtoHandshakeError = errors.New("rlpx proto error") 71 ) 72 73 // Config holds Server options. 74 type Config struct { 75 // This field must be set to a valid secp256k1 private key. 76 PrivateKey *ecdsa.PrivateKey `toml:"-"` 77 78 // MaxPeers is the maximum number of peers that can be 79 // connected. It must be greater than zero. 80 MaxPeers int 81 82 // MaxPendingPeers is the maximum number of peers that can be pending in the 83 // handshake phase, counted separately for inbound and outbound connections. 84 // Zero defaults to preset values. 85 MaxPendingPeers int `toml:",omitempty"` 86 87 // DialRatio controls the ratio of inbound to dialed connections. 88 // Example: a DialRatio of 2 allows 1/2 of connections to be dialed. 89 // Setting DialRatio to zero defaults it to 3. 90 DialRatio int `toml:",omitempty"` 91 92 // NoDiscovery can be used to disable the peer discovery mechanism. 93 // Disabling is useful for protocol debugging (manual topology). 94 NoDiscovery bool 95 96 // DiscoveryV4 specifies whether V4 discovery should be started. 97 DiscoveryV4 bool `toml:",omitempty"` 98 99 // DiscoveryV5 specifies whether the new topic-discovery based V5 discovery 100 // protocol should be started or not. 101 DiscoveryV5 bool `toml:",omitempty"` 102 103 // Name sets the node name of this server. 104 Name string `toml:"-"` 105 106 // BootstrapNodes are used to establish connectivity 107 // with the rest of the network. 108 BootstrapNodes []*enode.Node 109 110 // BootstrapNodesV5 are used to establish connectivity 111 // with the rest of the network using the V5 discovery 112 // protocol. 113 BootstrapNodesV5 []*enode.Node `toml:",omitempty"` 114 115 // Static nodes are used as pre-configured connections which are always 116 // maintained and re-connected on disconnects. 117 StaticNodes []*enode.Node 118 119 // Trusted nodes are used as pre-configured connections which are always 120 // allowed to connect, even above the peer limit. 121 TrustedNodes []*enode.Node 122 123 // Connectivity can be restricted to certain IP networks. 124 // If this option is set to a non-nil value, only hosts which match one of the 125 // IP networks contained in the list are considered. 126 NetRestrict *netutil.Netlist `toml:",omitempty"` 127 128 // NodeDatabase is the path to the database containing the previously seen 129 // live nodes in the network. 130 NodeDatabase string `toml:",omitempty"` 131 132 // Protocols should contain the protocols supported 133 // by the server. Matching protocols are launched for 134 // each peer. 135 Protocols []Protocol `toml:"-" json:"-"` 136 137 // If ListenAddr is set to a non-nil address, the server 138 // will listen for incoming connections. 139 // 140 // If the port is zero, the operating system will pick a port. The 141 // ListenAddr field will be updated with the actual address when 142 // the server is started. 143 ListenAddr string 144 145 // If DiscAddr is set to a non-nil value, the server will use ListenAddr 146 // for TCP and DiscAddr for the UDP discovery protocol. 147 DiscAddr string 148 149 // If set to a non-nil value, the given NAT port mapper 150 // is used to make the listening port available to the 151 // Internet. 152 NAT nat.Interface `toml:",omitempty"` 153 154 // If Dialer is set to a non-nil value, the given Dialer 155 // is used to dial outbound peer connections. 156 Dialer NodeDialer `toml:"-"` 157 158 // If NoDial is true, the server will not dial any peers. 159 NoDial bool `toml:",omitempty"` 160 161 // If EnableMsgEvents is set then the server will emit PeerEvents 162 // whenever a message is sent to or received from a peer 163 EnableMsgEvents bool 164 165 // Logger is a custom logger to use with the p2p.Server. 166 Logger log.Logger `toml:",omitempty"` 167 168 clock mclock.Clock 169 } 170 171 // Server manages all peer connections. 172 type Server struct { 173 // Config fields may not be modified while the server is running. 174 Config 175 176 // Hooks for testing. These are useful because we can inhibit 177 // the whole protocol stack. 178 newTransport func(net.Conn, *ecdsa.PublicKey) transport 179 newPeerHook func(*Peer) 180 listenFunc func(network, addr string) (net.Listener, error) 181 182 lock sync.Mutex // protects running 183 running bool 184 185 listener net.Listener 186 ourHandshake *protoHandshake 187 loopWG sync.WaitGroup // loop, listenLoop 188 peerFeed event.Feed 189 log log.Logger 190 191 nodedb *enode.DB 192 localnode *enode.LocalNode 193 ntab *discover.UDPv4 194 DiscV5 *discover.UDPv5 195 discmix *enode.FairMix 196 dialsched *dialScheduler 197 198 // This is read by the NAT port mapping loop. 199 portMappingRegister chan *portMapping 200 201 // Channels into the run loop. 202 quit chan struct{} 203 addtrusted chan *enode.Node 204 removetrusted chan *enode.Node 205 peerOp chan peerOpFunc 206 peerOpDone chan struct{} 207 delpeer chan peerDrop 208 checkpointPostHandshake chan *conn 209 checkpointAddPeer chan *conn 210 211 // State of run loop and listenLoop. 212 inboundHistory expHeap 213 } 214 215 type peerOpFunc func(map[enode.ID]*Peer) 216 217 type peerDrop struct { 218 *Peer 219 err error 220 requested bool // true if signaled by the peer 221 } 222 223 type connFlag int32 224 225 const ( 226 dynDialedConn connFlag = 1 << iota 227 staticDialedConn 228 inboundConn 229 trustedConn 230 ) 231 232 // conn wraps a network connection with information gathered 233 // during the two handshakes. 234 type conn struct { 235 fd net.Conn 236 transport 237 node *enode.Node 238 flags connFlag 239 cont chan error // The run loop uses cont to signal errors to SetupConn. 240 caps []Cap // valid after the protocol handshake 241 name string // valid after the protocol handshake 242 } 243 244 type transport interface { 245 // The two handshakes. 246 doEncHandshake(prv *ecdsa.PrivateKey) (*ecdsa.PublicKey, error) 247 doProtoHandshake(our *protoHandshake) (*protoHandshake, error) 248 // The MsgReadWriter can only be used after the encryption 249 // handshake has completed. The code uses conn.id to track this 250 // by setting it to a non-nil value after the encryption handshake. 251 MsgReadWriter 252 // transports must provide Close because we use MsgPipe in some of 253 // the tests. Closing the actual network connection doesn't do 254 // anything in those tests because MsgPipe doesn't use it. 255 close(err error) 256 } 257 258 func (c *conn) String() string { 259 s := c.flags.String() 260 if (c.node.ID() != enode.ID{}) { 261 s += " " + c.node.ID().String() 262 } 263 s += " " + c.fd.RemoteAddr().String() 264 return s 265 } 266 267 func (f connFlag) String() string { 268 s := "" 269 if f&trustedConn != 0 { 270 s += "-trusted" 271 } 272 if f&dynDialedConn != 0 { 273 s += "-dyndial" 274 } 275 if f&staticDialedConn != 0 { 276 s += "-staticdial" 277 } 278 if f&inboundConn != 0 { 279 s += "-inbound" 280 } 281 if s != "" { 282 s = s[1:] 283 } 284 return s 285 } 286 287 func (c *conn) is(f connFlag) bool { 288 flags := connFlag(atomic.LoadInt32((*int32)(&c.flags))) 289 return flags&f != 0 290 } 291 292 func (c *conn) set(f connFlag, val bool) { 293 for { 294 oldFlags := connFlag(atomic.LoadInt32((*int32)(&c.flags))) 295 flags := oldFlags 296 if val { 297 flags |= f 298 } else { 299 flags &= ^f 300 } 301 if atomic.CompareAndSwapInt32((*int32)(&c.flags), int32(oldFlags), int32(flags)) { 302 return 303 } 304 } 305 } 306 307 // LocalNode returns the local node record. 308 func (srv *Server) LocalNode() *enode.LocalNode { 309 return srv.localnode 310 } 311 312 // Peers returns all connected peers. 313 func (srv *Server) Peers() []*Peer { 314 var ps []*Peer 315 srv.doPeerOp(func(peers map[enode.ID]*Peer) { 316 for _, p := range peers { 317 ps = append(ps, p) 318 } 319 }) 320 return ps 321 } 322 323 // PeerCount returns the number of connected peers. 324 func (srv *Server) PeerCount() int { 325 var count int 326 srv.doPeerOp(func(ps map[enode.ID]*Peer) { 327 count = len(ps) 328 }) 329 return count 330 } 331 332 // AddPeer adds the given node to the static node set. When there is room in the peer set, 333 // the server will connect to the node. If the connection fails for any reason, the server 334 // will attempt to reconnect the peer. 335 func (srv *Server) AddPeer(node *enode.Node) { 336 srv.dialsched.addStatic(node) 337 } 338 339 // RemovePeer removes a node from the static node set. It also disconnects from the given 340 // node if it is currently connected as a peer. 341 // 342 // This method blocks until all protocols have exited and the peer is removed. Do not use 343 // RemovePeer in protocol implementations, call Disconnect on the Peer instead. 344 func (srv *Server) RemovePeer(node *enode.Node) { 345 var ( 346 ch chan *PeerEvent 347 sub event.Subscription 348 ) 349 // Disconnect the peer on the main loop. 350 srv.doPeerOp(func(peers map[enode.ID]*Peer) { 351 srv.dialsched.removeStatic(node) 352 if peer := peers[node.ID()]; peer != nil { 353 ch = make(chan *PeerEvent, 1) 354 sub = srv.peerFeed.Subscribe(ch) 355 peer.Disconnect(DiscRequested) 356 } 357 }) 358 // Wait for the peer connection to end. 359 if ch != nil { 360 defer sub.Unsubscribe() 361 for ev := range ch { 362 if ev.Peer == node.ID() && ev.Type == PeerEventTypeDrop { 363 return 364 } 365 } 366 } 367 } 368 369 // AddTrustedPeer adds the given node to a reserved trusted list which allows the 370 // node to always connect, even if the slot are full. 371 func (srv *Server) AddTrustedPeer(node *enode.Node) { 372 select { 373 case srv.addtrusted <- node: 374 case <-srv.quit: 375 } 376 } 377 378 // RemoveTrustedPeer removes the given node from the trusted peer set. 379 func (srv *Server) RemoveTrustedPeer(node *enode.Node) { 380 select { 381 case srv.removetrusted <- node: 382 case <-srv.quit: 383 } 384 } 385 386 // SubscribeEvents subscribes the given channel to peer events 387 func (srv *Server) SubscribeEvents(ch chan *PeerEvent) event.Subscription { 388 return srv.peerFeed.Subscribe(ch) 389 } 390 391 // Self returns the local node's endpoint information. 392 func (srv *Server) Self() *enode.Node { 393 srv.lock.Lock() 394 ln := srv.localnode 395 srv.lock.Unlock() 396 397 if ln == nil { 398 return enode.NewV4(&srv.PrivateKey.PublicKey, net.ParseIP("0.0.0.0"), 0, 0) 399 } 400 return ln.Node() 401 } 402 403 // Stop terminates the server and all active peer connections. 404 // It blocks until all active connections have been closed. 405 func (srv *Server) Stop() { 406 srv.lock.Lock() 407 if !srv.running { 408 srv.lock.Unlock() 409 return 410 } 411 srv.running = false 412 if srv.listener != nil { 413 // this unblocks listener Accept 414 srv.listener.Close() 415 } 416 close(srv.quit) 417 srv.lock.Unlock() 418 srv.loopWG.Wait() 419 } 420 421 // sharedUDPConn implements a shared connection. Write sends messages to the underlying connection while read returns 422 // messages that were found unprocessable and sent to the unhandled channel by the primary listener. 423 type sharedUDPConn struct { 424 *net.UDPConn 425 unhandled chan discover.ReadPacket 426 } 427 428 // ReadFromUDP implements discover.UDPConn 429 func (s *sharedUDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) { 430 packet, ok := <-s.unhandled 431 if !ok { 432 return 0, nil, errors.New("connection was closed") 433 } 434 l := len(packet.Data) 435 if l > len(b) { 436 l = len(b) 437 } 438 copy(b[:l], packet.Data[:l]) 439 return l, packet.Addr, nil 440 } 441 442 // Close implements discover.UDPConn 443 func (s *sharedUDPConn) Close() error { 444 return nil 445 } 446 447 // Start starts running the server. 448 // Servers can not be re-used after stopping. 449 func (srv *Server) Start() (err error) { 450 srv.lock.Lock() 451 defer srv.lock.Unlock() 452 if srv.running { 453 return errors.New("server already running") 454 } 455 srv.running = true 456 srv.log = srv.Logger 457 if srv.log == nil { 458 srv.log = log.Root() 459 } 460 if srv.clock == nil { 461 srv.clock = mclock.System{} 462 } 463 if srv.NoDial && srv.ListenAddr == "" { 464 srv.log.Warn("P2P server will be useless, neither dialing nor listening") 465 } 466 467 // static fields 468 if srv.PrivateKey == nil { 469 return errors.New("Server.PrivateKey must be set to a non-nil key") 470 } 471 if srv.newTransport == nil { 472 srv.newTransport = newRLPX 473 } 474 if srv.listenFunc == nil { 475 srv.listenFunc = net.Listen 476 } 477 srv.quit = make(chan struct{}) 478 srv.delpeer = make(chan peerDrop) 479 srv.checkpointPostHandshake = make(chan *conn) 480 srv.checkpointAddPeer = make(chan *conn) 481 srv.addtrusted = make(chan *enode.Node) 482 srv.removetrusted = make(chan *enode.Node) 483 srv.peerOp = make(chan peerOpFunc) 484 srv.peerOpDone = make(chan struct{}) 485 486 if err := srv.setupLocalNode(); err != nil { 487 return err 488 } 489 srv.setupPortMapping() 490 491 if srv.ListenAddr != "" { 492 if err := srv.setupListening(); err != nil { 493 return err 494 } 495 } 496 if err := srv.setupDiscovery(); err != nil { 497 return err 498 } 499 srv.setupDialScheduler() 500 501 srv.loopWG.Add(1) 502 go srv.run() 503 return nil 504 } 505 506 func (srv *Server) setupLocalNode() error { 507 // Create the devp2p handshake. 508 pubkey := crypto.FromECDSAPub(&srv.PrivateKey.PublicKey) 509 srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: pubkey[1:]} 510 for _, p := range srv.Protocols { 511 srv.ourHandshake.Caps = append(srv.ourHandshake.Caps, p.cap()) 512 } 513 slices.SortFunc(srv.ourHandshake.Caps, Cap.Cmp) 514 515 // Create the local node. 516 db, err := enode.OpenDB(srv.NodeDatabase) 517 if err != nil { 518 return err 519 } 520 srv.nodedb = db 521 srv.localnode = enode.NewLocalNode(db, srv.PrivateKey) 522 srv.localnode.SetFallbackIP(net.IP{127, 0, 0, 1}) 523 // TODO: check conflicts 524 for _, p := range srv.Protocols { 525 for _, e := range p.Attributes { 526 srv.localnode.Set(e) 527 } 528 } 529 return nil 530 } 531 532 func (srv *Server) setupDiscovery() error { 533 srv.discmix = enode.NewFairMix(discmixTimeout) 534 535 // Don't listen on UDP endpoint if DHT is disabled. 536 if srv.NoDiscovery { 537 return nil 538 } 539 conn, err := srv.setupUDPListening() 540 if err != nil { 541 return err 542 } 543 544 var ( 545 sconn discover.UDPConn = conn 546 unhandled chan discover.ReadPacket 547 ) 548 // If both versions of discovery are running, setup a shared 549 // connection, so v5 can read unhandled messages from v4. 550 if srv.DiscoveryV4 && srv.DiscoveryV5 { 551 unhandled = make(chan discover.ReadPacket, 100) 552 sconn = &sharedUDPConn{conn, unhandled} 553 } 554 555 // Start discovery services. 556 if srv.DiscoveryV4 { 557 cfg := discover.Config{ 558 PrivateKey: srv.PrivateKey, 559 NetRestrict: srv.NetRestrict, 560 Bootnodes: srv.BootstrapNodes, 561 Unhandled: unhandled, 562 Log: srv.log, 563 } 564 ntab, err := discover.ListenV4(conn, srv.localnode, cfg) 565 if err != nil { 566 return err 567 } 568 srv.ntab = ntab 569 srv.discmix.AddSource(ntab.RandomNodes()) 570 } 571 if srv.DiscoveryV5 { 572 cfg := discover.Config{ 573 PrivateKey: srv.PrivateKey, 574 NetRestrict: srv.NetRestrict, 575 Bootnodes: srv.BootstrapNodesV5, 576 Log: srv.log, 577 } 578 srv.DiscV5, err = discover.ListenV5(sconn, srv.localnode, cfg) 579 if err != nil { 580 return err 581 } 582 } 583 584 // Add protocol-specific discovery sources. 585 added := make(map[string]bool) 586 for _, proto := range srv.Protocols { 587 if proto.DialCandidates != nil && !added[proto.Name] { 588 srv.discmix.AddSource(proto.DialCandidates) 589 added[proto.Name] = true 590 } 591 } 592 return nil 593 } 594 595 func (srv *Server) setupDialScheduler() { 596 config := dialConfig{ 597 self: srv.localnode.ID(), 598 maxDialPeers: srv.maxDialedConns(), 599 maxActiveDials: srv.MaxPendingPeers, 600 log: srv.Logger, 601 netRestrict: srv.NetRestrict, 602 dialer: srv.Dialer, 603 clock: srv.clock, 604 } 605 if srv.ntab != nil { 606 config.resolver = srv.ntab 607 } 608 if config.dialer == nil { 609 config.dialer = tcpDialer{&net.Dialer{Timeout: defaultDialTimeout}} 610 } 611 srv.dialsched = newDialScheduler(config, srv.discmix, srv.SetupConn) 612 for _, n := range srv.StaticNodes { 613 srv.dialsched.addStatic(n) 614 } 615 } 616 617 func (srv *Server) maxInboundConns() int { 618 return srv.MaxPeers - srv.maxDialedConns() 619 } 620 621 func (srv *Server) maxDialedConns() (limit int) { 622 if srv.NoDial || srv.MaxPeers == 0 { 623 return 0 624 } 625 if srv.DialRatio == 0 { 626 limit = srv.MaxPeers / defaultDialRatio 627 } else { 628 limit = srv.MaxPeers / srv.DialRatio 629 } 630 if limit == 0 { 631 limit = 1 632 } 633 return limit 634 } 635 636 func (srv *Server) setupListening() error { 637 // Launch the listener. 638 listener, err := srv.listenFunc("tcp", srv.ListenAddr) 639 if err != nil { 640 return err 641 } 642 srv.listener = listener 643 srv.ListenAddr = listener.Addr().String() 644 645 // Update the local node record and map the TCP listening port if NAT is configured. 646 tcp, isTCP := listener.Addr().(*net.TCPAddr) 647 if isTCP { 648 srv.localnode.Set(enr.TCP(tcp.Port)) 649 if !tcp.IP.IsLoopback() && !tcp.IP.IsPrivate() { 650 srv.portMappingRegister <- &portMapping{ 651 protocol: "TCP", 652 name: "ethereum p2p", 653 port: tcp.Port, 654 } 655 } 656 } 657 658 srv.loopWG.Add(1) 659 go srv.listenLoop() 660 return nil 661 } 662 663 func (srv *Server) setupUDPListening() (*net.UDPConn, error) { 664 listenAddr := srv.ListenAddr 665 666 // Use an alternate listening address for UDP if 667 // a custom discovery address is configured. 668 if srv.DiscAddr != "" { 669 listenAddr = srv.DiscAddr 670 } 671 addr, err := net.ResolveUDPAddr("udp", listenAddr) 672 if err != nil { 673 return nil, err 674 } 675 conn, err := net.ListenUDP("udp", addr) 676 if err != nil { 677 return nil, err 678 } 679 laddr := conn.LocalAddr().(*net.UDPAddr) 680 srv.localnode.SetFallbackUDP(laddr.Port) 681 srv.log.Debug("UDP listener up", "addr", laddr) 682 if !laddr.IP.IsLoopback() && !laddr.IP.IsPrivate() { 683 srv.portMappingRegister <- &portMapping{ 684 protocol: "UDP", 685 name: "ethereum peer discovery", 686 port: laddr.Port, 687 } 688 } 689 690 return conn, nil 691 } 692 693 // doPeerOp runs fn on the main loop. 694 func (srv *Server) doPeerOp(fn peerOpFunc) { 695 select { 696 case srv.peerOp <- fn: 697 <-srv.peerOpDone 698 case <-srv.quit: 699 } 700 } 701 702 // run is the main loop of the server. 703 func (srv *Server) run() { 704 srv.log.Info("Started P2P networking", "self", srv.localnode.Node().URLv4()) 705 defer srv.loopWG.Done() 706 defer srv.nodedb.Close() 707 defer srv.discmix.Close() 708 defer srv.dialsched.stop() 709 710 var ( 711 peers = make(map[enode.ID]*Peer) 712 inboundCount = 0 713 trusted = make(map[enode.ID]bool, len(srv.TrustedNodes)) 714 ) 715 // Put trusted nodes into a map to speed up checks. 716 // Trusted peers are loaded on startup or added via AddTrustedPeer RPC. 717 for _, n := range srv.TrustedNodes { 718 trusted[n.ID()] = true 719 } 720 721 running: 722 for { 723 select { 724 case <-srv.quit: 725 // The server was stopped. Run the cleanup logic. 726 break running 727 728 case n := <-srv.addtrusted: 729 // This channel is used by AddTrustedPeer to add a node 730 // to the trusted node set. 731 srv.log.Trace("Adding trusted node", "node", n) 732 trusted[n.ID()] = true 733 if p, ok := peers[n.ID()]; ok { 734 p.rw.set(trustedConn, true) 735 } 736 737 case n := <-srv.removetrusted: 738 // This channel is used by RemoveTrustedPeer to remove a node 739 // from the trusted node set. 740 srv.log.Trace("Removing trusted node", "node", n) 741 delete(trusted, n.ID()) 742 if p, ok := peers[n.ID()]; ok { 743 p.rw.set(trustedConn, false) 744 } 745 746 case op := <-srv.peerOp: 747 // This channel is used by Peers and PeerCount. 748 op(peers) 749 srv.peerOpDone <- struct{}{} 750 751 case c := <-srv.checkpointPostHandshake: 752 // A connection has passed the encryption handshake so 753 // the remote identity is known (but hasn't been verified yet). 754 if trusted[c.node.ID()] { 755 // Ensure that the trusted flag is set before checking against MaxPeers. 756 c.flags |= trustedConn 757 } 758 // TODO: track in-progress inbound node IDs (pre-Peer) to avoid dialing them. 759 c.cont <- srv.postHandshakeChecks(peers, inboundCount, c) 760 761 case c := <-srv.checkpointAddPeer: 762 // At this point the connection is past the protocol handshake. 763 // Its capabilities are known and the remote identity is verified. 764 err := srv.addPeerChecks(peers, inboundCount, c) 765 if err == nil { 766 // The handshakes are done and it passed all checks. 767 p := srv.launchPeer(c) 768 peers[c.node.ID()] = p 769 srv.log.Debug("Adding p2p peer", "peercount", len(peers), "id", p.ID(), "conn", c.flags, "addr", p.RemoteAddr(), "name", p.Name()) 770 srv.dialsched.peerAdded(c) 771 if p.Inbound() { 772 inboundCount++ 773 serveSuccessMeter.Mark(1) 774 activeInboundPeerGauge.Inc(1) 775 } else { 776 dialSuccessMeter.Mark(1) 777 activeOutboundPeerGauge.Inc(1) 778 } 779 activePeerGauge.Inc(1) 780 } 781 c.cont <- err 782 783 case pd := <-srv.delpeer: 784 // A peer disconnected. 785 d := common.PrettyDuration(mclock.Now() - pd.created) 786 delete(peers, pd.ID()) 787 srv.log.Debug("Removing p2p peer", "peercount", len(peers), "id", pd.ID(), "duration", d, "req", pd.requested, "err", pd.err) 788 srv.dialsched.peerRemoved(pd.rw) 789 if pd.Inbound() { 790 inboundCount-- 791 activeInboundPeerGauge.Dec(1) 792 } else { 793 activeOutboundPeerGauge.Dec(1) 794 } 795 activePeerGauge.Dec(1) 796 } 797 } 798 799 srv.log.Trace("P2P networking is spinning down") 800 801 // Terminate discovery. If there is a running lookup it will terminate soon. 802 if srv.ntab != nil { 803 srv.ntab.Close() 804 } 805 if srv.DiscV5 != nil { 806 srv.DiscV5.Close() 807 } 808 // Disconnect all peers. 809 for _, p := range peers { 810 p.Disconnect(DiscQuitting) 811 } 812 // Wait for peers to shut down. Pending connections and tasks are 813 // not handled here and will terminate soon-ish because srv.quit 814 // is closed. 815 for len(peers) > 0 { 816 p := <-srv.delpeer 817 p.log.Trace("<-delpeer (spindown)") 818 delete(peers, p.ID()) 819 } 820 } 821 822 func (srv *Server) postHandshakeChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error { 823 switch { 824 case !c.is(trustedConn) && len(peers) >= srv.MaxPeers: 825 return DiscTooManyPeers 826 case !c.is(trustedConn) && c.is(inboundConn) && inboundCount >= srv.maxInboundConns(): 827 return DiscTooManyPeers 828 case peers[c.node.ID()] != nil: 829 return DiscAlreadyConnected 830 case c.node.ID() == srv.localnode.ID(): 831 return DiscSelf 832 default: 833 return nil 834 } 835 } 836 837 func (srv *Server) addPeerChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error { 838 // Drop connections with no matching protocols. 839 if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 { 840 return DiscUselessPeer 841 } 842 // Repeat the post-handshake checks because the 843 // peer set might have changed since those checks were performed. 844 return srv.postHandshakeChecks(peers, inboundCount, c) 845 } 846 847 // listenLoop runs in its own goroutine and accepts 848 // inbound connections. 849 func (srv *Server) listenLoop() { 850 srv.log.Debug("TCP listener up", "addr", srv.listener.Addr()) 851 852 // The slots channel limits accepts of new connections. 853 tokens := defaultMaxPendingPeers 854 if srv.MaxPendingPeers > 0 { 855 tokens = srv.MaxPendingPeers 856 } 857 slots := make(chan struct{}, tokens) 858 for i := 0; i < tokens; i++ { 859 slots <- struct{}{} 860 } 861 862 // Wait for slots to be returned on exit. This ensures all connection goroutines 863 // are down before listenLoop returns. 864 defer srv.loopWG.Done() 865 defer func() { 866 for i := 0; i < cap(slots); i++ { 867 <-slots 868 } 869 }() 870 871 for { 872 // Wait for a free slot before accepting. 873 <-slots 874 875 var ( 876 fd net.Conn 877 err error 878 lastLog time.Time 879 ) 880 for { 881 fd, err = srv.listener.Accept() 882 if netutil.IsTemporaryError(err) { 883 if time.Since(lastLog) > 1*time.Second { 884 srv.log.Debug("Temporary read error", "err", err) 885 lastLog = time.Now() 886 } 887 time.Sleep(time.Millisecond * 200) 888 continue 889 } else if err != nil { 890 srv.log.Debug("Read error", "err", err) 891 slots <- struct{}{} 892 return 893 } 894 break 895 } 896 897 remoteIP := netutil.AddrIP(fd.RemoteAddr()) 898 if err := srv.checkInboundConn(remoteIP); err != nil { 899 srv.log.Debug("Rejected inbound connection", "addr", fd.RemoteAddr(), "err", err) 900 fd.Close() 901 slots <- struct{}{} 902 continue 903 } 904 if remoteIP != nil { 905 fd = newMeteredConn(fd) 906 serveMeter.Mark(1) 907 srv.log.Trace("Accepted connection", "addr", fd.RemoteAddr()) 908 } 909 go func() { 910 srv.SetupConn(fd, inboundConn, nil) 911 slots <- struct{}{} 912 }() 913 } 914 } 915 916 func (srv *Server) checkInboundConn(remoteIP net.IP) error { 917 if remoteIP == nil { 918 return nil 919 } 920 // Reject connections that do not match NetRestrict. 921 if srv.NetRestrict != nil && !srv.NetRestrict.Contains(remoteIP) { 922 return errors.New("not in netrestrict list") 923 } 924 // Reject Internet peers that try too often. 925 now := srv.clock.Now() 926 srv.inboundHistory.expire(now, nil) 927 if !netutil.IsLAN(remoteIP) && srv.inboundHistory.contains(remoteIP.String()) { 928 return errors.New("too many attempts") 929 } 930 srv.inboundHistory.add(remoteIP.String(), now.Add(inboundThrottleTime)) 931 return nil 932 } 933 934 // SetupConn runs the handshakes and attempts to add the connection 935 // as a peer. It returns when the connection has been added as a peer 936 // or the handshakes have failed. 937 func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *enode.Node) error { 938 c := &conn{fd: fd, flags: flags, cont: make(chan error)} 939 if dialDest == nil { 940 c.transport = srv.newTransport(fd, nil) 941 } else { 942 c.transport = srv.newTransport(fd, dialDest.Pubkey()) 943 } 944 945 err := srv.setupConn(c, dialDest) 946 if err != nil { 947 if !c.is(inboundConn) { 948 markDialError(err) 949 } 950 c.close(err) 951 } 952 return err 953 } 954 955 func (srv *Server) setupConn(c *conn, dialDest *enode.Node) error { 956 // Prevent leftover pending conns from entering the handshake. 957 srv.lock.Lock() 958 running := srv.running 959 srv.lock.Unlock() 960 if !running { 961 return errServerStopped 962 } 963 964 // If dialing, figure out the remote public key. 965 if dialDest != nil { 966 dialPubkey := new(ecdsa.PublicKey) 967 if err := dialDest.Load((*enode.Secp256k1)(dialPubkey)); err != nil { 968 err = fmt.Errorf("%w: dial destination doesn't have a secp256k1 public key", errEncHandshakeError) 969 srv.log.Trace("Setting up connection failed", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err) 970 return err 971 } 972 } 973 974 // Run the RLPx handshake. 975 remotePubkey, err := c.doEncHandshake(srv.PrivateKey) 976 if err != nil { 977 srv.log.Trace("Failed RLPx handshake", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err) 978 return fmt.Errorf("%w: %v", errEncHandshakeError, err) 979 } 980 if dialDest != nil { 981 c.node = dialDest 982 } else { 983 c.node = nodeFromConn(remotePubkey, c.fd) 984 } 985 clog := srv.log.New("id", c.node.ID(), "addr", c.fd.RemoteAddr(), "conn", c.flags) 986 err = srv.checkpoint(c, srv.checkpointPostHandshake) 987 if err != nil { 988 clog.Trace("Rejected peer", "err", err) 989 return err 990 } 991 992 // Run the capability negotiation handshake. 993 phs, err := c.doProtoHandshake(srv.ourHandshake) 994 if err != nil { 995 clog.Trace("Failed p2p handshake", "err", err) 996 return fmt.Errorf("%w: %v", errProtoHandshakeError, err) 997 } 998 if id := c.node.ID(); !bytes.Equal(crypto.Keccak256(phs.ID), id[:]) { 999 clog.Trace("Wrong devp2p handshake identity", "phsid", hex.EncodeToString(phs.ID)) 1000 return DiscUnexpectedIdentity 1001 } 1002 c.caps, c.name = phs.Caps, phs.Name 1003 err = srv.checkpoint(c, srv.checkpointAddPeer) 1004 if err != nil { 1005 clog.Trace("Rejected peer", "err", err) 1006 return err 1007 } 1008 1009 return nil 1010 } 1011 1012 func nodeFromConn(pubkey *ecdsa.PublicKey, conn net.Conn) *enode.Node { 1013 var ip net.IP 1014 var port int 1015 if tcp, ok := conn.RemoteAddr().(*net.TCPAddr); ok { 1016 ip = tcp.IP 1017 port = tcp.Port 1018 } 1019 return enode.NewV4(pubkey, ip, port, port) 1020 } 1021 1022 // checkpoint sends the conn to run, which performs the 1023 // post-handshake checks for the stage (posthandshake, addpeer). 1024 func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error { 1025 select { 1026 case stage <- c: 1027 case <-srv.quit: 1028 return errServerStopped 1029 } 1030 return <-c.cont 1031 } 1032 1033 func (srv *Server) launchPeer(c *conn) *Peer { 1034 p := newPeer(srv.log, c, srv.Protocols) 1035 if srv.EnableMsgEvents { 1036 // If message events are enabled, pass the peerFeed 1037 // to the peer. 1038 p.events = &srv.peerFeed 1039 } 1040 go srv.runPeer(p) 1041 return p 1042 } 1043 1044 // runPeer runs in its own goroutine for each peer. 1045 func (srv *Server) runPeer(p *Peer) { 1046 if srv.newPeerHook != nil { 1047 srv.newPeerHook(p) 1048 } 1049 srv.peerFeed.Send(&PeerEvent{ 1050 Type: PeerEventTypeAdd, 1051 Peer: p.ID(), 1052 RemoteAddress: p.RemoteAddr().String(), 1053 LocalAddress: p.LocalAddr().String(), 1054 }) 1055 1056 // Run the per-peer main loop. 1057 remoteRequested, err := p.run() 1058 1059 // Announce disconnect on the main loop to update the peer set. 1060 // The main loop waits for existing peers to be sent on srv.delpeer 1061 // before returning, so this send should not select on srv.quit. 1062 srv.delpeer <- peerDrop{p, err, remoteRequested} 1063 1064 // Broadcast peer drop to external subscribers. This needs to be 1065 // after the send to delpeer so subscribers have a consistent view of 1066 // the peer set (i.e. Server.Peers() doesn't include the peer when the 1067 // event is received). 1068 srv.peerFeed.Send(&PeerEvent{ 1069 Type: PeerEventTypeDrop, 1070 Peer: p.ID(), 1071 Error: err.Error(), 1072 RemoteAddress: p.RemoteAddr().String(), 1073 LocalAddress: p.LocalAddr().String(), 1074 }) 1075 } 1076 1077 // NodeInfo represents a short summary of the information known about the host. 1078 type NodeInfo struct { 1079 ID string `json:"id"` // Unique node identifier (also the encryption key) 1080 Name string `json:"name"` // Name of the node, including client type, version, OS, custom data 1081 Enode string `json:"enode"` // Enode URL for adding this peer from remote peers 1082 ENR string `json:"enr"` // Ethereum Node Record 1083 IP string `json:"ip"` // IP address of the node 1084 Ports struct { 1085 Discovery int `json:"discovery"` // UDP listening port for discovery protocol 1086 Listener int `json:"listener"` // TCP listening port for RLPx 1087 } `json:"ports"` 1088 ListenAddr string `json:"listenAddr"` 1089 Protocols map[string]interface{} `json:"protocols"` 1090 } 1091 1092 // NodeInfo gathers and returns a collection of metadata known about the host. 1093 func (srv *Server) NodeInfo() *NodeInfo { 1094 // Gather and assemble the generic node infos 1095 node := srv.Self() 1096 info := &NodeInfo{ 1097 Name: srv.Name, 1098 Enode: node.URLv4(), 1099 ID: node.ID().String(), 1100 IP: node.IP().String(), 1101 ListenAddr: srv.ListenAddr, 1102 Protocols: make(map[string]interface{}), 1103 } 1104 info.Ports.Discovery = node.UDP() 1105 info.Ports.Listener = node.TCP() 1106 info.ENR = node.String() 1107 1108 // Gather all the running protocol infos (only once per protocol type) 1109 for _, proto := range srv.Protocols { 1110 if _, ok := info.Protocols[proto.Name]; !ok { 1111 nodeInfo := interface{}("unknown") 1112 if query := proto.NodeInfo; query != nil { 1113 nodeInfo = proto.NodeInfo() 1114 } 1115 info.Protocols[proto.Name] = nodeInfo 1116 } 1117 } 1118 return info 1119 } 1120 1121 // PeersInfo returns an array of metadata objects describing connected peers. 1122 func (srv *Server) PeersInfo() []*PeerInfo { 1123 // Gather all the generic and sub-protocol specific infos 1124 infos := make([]*PeerInfo, 0, srv.PeerCount()) 1125 for _, peer := range srv.Peers() { 1126 if peer != nil { 1127 infos = append(infos, peer.Info()) 1128 } 1129 } 1130 // Sort the result array alphabetically by node identifier 1131 for i := 0; i < len(infos); i++ { 1132 for j := i + 1; j < len(infos); j++ { 1133 if infos[i].ID > infos[j].ID { 1134 infos[i], infos[j] = infos[j], infos[i] 1135 } 1136 } 1137 } 1138 return infos 1139 }