github.com/theQRL/go-zond@v0.1.1/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 "sync" 28 "sync/atomic" 29 "time" 30 31 "github.com/theQRL/go-zond/common" 32 "github.com/theQRL/go-zond/common/mclock" 33 "github.com/theQRL/go-zond/crypto" 34 "github.com/theQRL/go-zond/event" 35 "github.com/theQRL/go-zond/log" 36 "github.com/theQRL/go-zond/p2p/discover" 37 "github.com/theQRL/go-zond/p2p/enode" 38 "github.com/theQRL/go-zond/p2p/enr" 39 "github.com/theQRL/go-zond/p2p/nat" 40 "github.com/theQRL/go-zond/p2p/netutil" 41 "golang.org/x/exp/slices" 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 } else { 775 dialSuccessMeter.Mark(1) 776 } 777 activePeerGauge.Inc(1) 778 } 779 c.cont <- err 780 781 case pd := <-srv.delpeer: 782 // A peer disconnected. 783 d := common.PrettyDuration(mclock.Now() - pd.created) 784 delete(peers, pd.ID()) 785 srv.log.Debug("Removing p2p peer", "peercount", len(peers), "id", pd.ID(), "duration", d, "req", pd.requested, "err", pd.err) 786 srv.dialsched.peerRemoved(pd.rw) 787 if pd.Inbound() { 788 inboundCount-- 789 } 790 activePeerGauge.Dec(1) 791 } 792 } 793 794 srv.log.Trace("P2P networking is spinning down") 795 796 // Terminate discovery. If there is a running lookup it will terminate soon. 797 if srv.ntab != nil { 798 srv.ntab.Close() 799 } 800 if srv.DiscV5 != nil { 801 srv.DiscV5.Close() 802 } 803 // Disconnect all peers. 804 for _, p := range peers { 805 p.Disconnect(DiscQuitting) 806 } 807 // Wait for peers to shut down. Pending connections and tasks are 808 // not handled here and will terminate soon-ish because srv.quit 809 // is closed. 810 for len(peers) > 0 { 811 p := <-srv.delpeer 812 p.log.Trace("<-delpeer (spindown)") 813 delete(peers, p.ID()) 814 } 815 } 816 817 func (srv *Server) postHandshakeChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error { 818 switch { 819 case !c.is(trustedConn) && len(peers) >= srv.MaxPeers: 820 return DiscTooManyPeers 821 case !c.is(trustedConn) && c.is(inboundConn) && inboundCount >= srv.maxInboundConns(): 822 return DiscTooManyPeers 823 case peers[c.node.ID()] != nil: 824 return DiscAlreadyConnected 825 case c.node.ID() == srv.localnode.ID(): 826 return DiscSelf 827 default: 828 return nil 829 } 830 } 831 832 func (srv *Server) addPeerChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error { 833 // Drop connections with no matching protocols. 834 if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 { 835 return DiscUselessPeer 836 } 837 // Repeat the post-handshake checks because the 838 // peer set might have changed since those checks were performed. 839 return srv.postHandshakeChecks(peers, inboundCount, c) 840 } 841 842 // listenLoop runs in its own goroutine and accepts 843 // inbound connections. 844 func (srv *Server) listenLoop() { 845 srv.log.Debug("TCP listener up", "addr", srv.listener.Addr()) 846 847 // The slots channel limits accepts of new connections. 848 tokens := defaultMaxPendingPeers 849 if srv.MaxPendingPeers > 0 { 850 tokens = srv.MaxPendingPeers 851 } 852 slots := make(chan struct{}, tokens) 853 for i := 0; i < tokens; i++ { 854 slots <- struct{}{} 855 } 856 857 // Wait for slots to be returned on exit. This ensures all connection goroutines 858 // are down before listenLoop returns. 859 defer srv.loopWG.Done() 860 defer func() { 861 for i := 0; i < cap(slots); i++ { 862 <-slots 863 } 864 }() 865 866 for { 867 // Wait for a free slot before accepting. 868 <-slots 869 870 var ( 871 fd net.Conn 872 err error 873 lastLog time.Time 874 ) 875 for { 876 fd, err = srv.listener.Accept() 877 if netutil.IsTemporaryError(err) { 878 if time.Since(lastLog) > 1*time.Second { 879 srv.log.Debug("Temporary read error", "err", err) 880 lastLog = time.Now() 881 } 882 time.Sleep(time.Millisecond * 200) 883 continue 884 } else if err != nil { 885 srv.log.Debug("Read error", "err", err) 886 slots <- struct{}{} 887 return 888 } 889 break 890 } 891 892 remoteIP := netutil.AddrIP(fd.RemoteAddr()) 893 if err := srv.checkInboundConn(remoteIP); err != nil { 894 srv.log.Debug("Rejected inbound connection", "addr", fd.RemoteAddr(), "err", err) 895 fd.Close() 896 slots <- struct{}{} 897 continue 898 } 899 if remoteIP != nil { 900 fd = newMeteredConn(fd) 901 serveMeter.Mark(1) 902 srv.log.Trace("Accepted connection", "addr", fd.RemoteAddr()) 903 } 904 go func() { 905 srv.SetupConn(fd, inboundConn, nil) 906 slots <- struct{}{} 907 }() 908 } 909 } 910 911 func (srv *Server) checkInboundConn(remoteIP net.IP) error { 912 if remoteIP == nil { 913 return nil 914 } 915 // Reject connections that do not match NetRestrict. 916 if srv.NetRestrict != nil && !srv.NetRestrict.Contains(remoteIP) { 917 return fmt.Errorf("not in netrestrict list") 918 } 919 // Reject Internet peers that try too often. 920 now := srv.clock.Now() 921 srv.inboundHistory.expire(now, nil) 922 if !netutil.IsLAN(remoteIP) && srv.inboundHistory.contains(remoteIP.String()) { 923 return fmt.Errorf("too many attempts") 924 } 925 srv.inboundHistory.add(remoteIP.String(), now.Add(inboundThrottleTime)) 926 return nil 927 } 928 929 // SetupConn runs the handshakes and attempts to add the connection 930 // as a peer. It returns when the connection has been added as a peer 931 // or the handshakes have failed. 932 func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *enode.Node) error { 933 c := &conn{fd: fd, flags: flags, cont: make(chan error)} 934 if dialDest == nil { 935 c.transport = srv.newTransport(fd, nil) 936 } else { 937 c.transport = srv.newTransport(fd, dialDest.Pubkey()) 938 } 939 940 err := srv.setupConn(c, flags, dialDest) 941 if err != nil { 942 if !c.is(inboundConn) { 943 markDialError(err) 944 } 945 c.close(err) 946 } 947 return err 948 } 949 950 func (srv *Server) setupConn(c *conn, flags connFlag, dialDest *enode.Node) error { 951 // Prevent leftover pending conns from entering the handshake. 952 srv.lock.Lock() 953 running := srv.running 954 srv.lock.Unlock() 955 if !running { 956 return errServerStopped 957 } 958 959 // If dialing, figure out the remote public key. 960 if dialDest != nil { 961 dialPubkey := new(ecdsa.PublicKey) 962 if err := dialDest.Load((*enode.Secp256k1)(dialPubkey)); err != nil { 963 err = fmt.Errorf("%w: dial destination doesn't have a secp256k1 public key", errEncHandshakeError) 964 srv.log.Trace("Setting up connection failed", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err) 965 return err 966 } 967 } 968 969 // Run the RLPx handshake. 970 remotePubkey, err := c.doEncHandshake(srv.PrivateKey) 971 if err != nil { 972 srv.log.Trace("Failed RLPx handshake", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err) 973 return fmt.Errorf("%w: %v", errEncHandshakeError, err) 974 } 975 if dialDest != nil { 976 c.node = dialDest 977 } else { 978 c.node = nodeFromConn(remotePubkey, c.fd) 979 } 980 clog := srv.log.New("id", c.node.ID(), "addr", c.fd.RemoteAddr(), "conn", c.flags) 981 err = srv.checkpoint(c, srv.checkpointPostHandshake) 982 if err != nil { 983 clog.Trace("Rejected peer", "err", err) 984 return err 985 } 986 987 // Run the capability negotiation handshake. 988 phs, err := c.doProtoHandshake(srv.ourHandshake) 989 if err != nil { 990 clog.Trace("Failed p2p handshake", "err", err) 991 return fmt.Errorf("%w: %v", errProtoHandshakeError, err) 992 } 993 if id := c.node.ID(); !bytes.Equal(crypto.Keccak256(phs.ID), id[:]) { 994 clog.Trace("Wrong devp2p handshake identity", "phsid", hex.EncodeToString(phs.ID)) 995 return DiscUnexpectedIdentity 996 } 997 c.caps, c.name = phs.Caps, phs.Name 998 err = srv.checkpoint(c, srv.checkpointAddPeer) 999 if err != nil { 1000 clog.Trace("Rejected peer", "err", err) 1001 return err 1002 } 1003 1004 return nil 1005 } 1006 1007 func nodeFromConn(pubkey *ecdsa.PublicKey, conn net.Conn) *enode.Node { 1008 var ip net.IP 1009 var port int 1010 if tcp, ok := conn.RemoteAddr().(*net.TCPAddr); ok { 1011 ip = tcp.IP 1012 port = tcp.Port 1013 } 1014 return enode.NewV4(pubkey, ip, port, port) 1015 } 1016 1017 // checkpoint sends the conn to run, which performs the 1018 // post-handshake checks for the stage (posthandshake, addpeer). 1019 func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error { 1020 select { 1021 case stage <- c: 1022 case <-srv.quit: 1023 return errServerStopped 1024 } 1025 return <-c.cont 1026 } 1027 1028 func (srv *Server) launchPeer(c *conn) *Peer { 1029 p := newPeer(srv.log, c, srv.Protocols) 1030 if srv.EnableMsgEvents { 1031 // If message events are enabled, pass the peerFeed 1032 // to the peer. 1033 p.events = &srv.peerFeed 1034 } 1035 go srv.runPeer(p) 1036 return p 1037 } 1038 1039 // runPeer runs in its own goroutine for each peer. 1040 func (srv *Server) runPeer(p *Peer) { 1041 if srv.newPeerHook != nil { 1042 srv.newPeerHook(p) 1043 } 1044 srv.peerFeed.Send(&PeerEvent{ 1045 Type: PeerEventTypeAdd, 1046 Peer: p.ID(), 1047 RemoteAddress: p.RemoteAddr().String(), 1048 LocalAddress: p.LocalAddr().String(), 1049 }) 1050 1051 // Run the per-peer main loop. 1052 remoteRequested, err := p.run() 1053 1054 // Announce disconnect on the main loop to update the peer set. 1055 // The main loop waits for existing peers to be sent on srv.delpeer 1056 // before returning, so this send should not select on srv.quit. 1057 srv.delpeer <- peerDrop{p, err, remoteRequested} 1058 1059 // Broadcast peer drop to external subscribers. This needs to be 1060 // after the send to delpeer so subscribers have a consistent view of 1061 // the peer set (i.e. Server.Peers() doesn't include the peer when the 1062 // event is received). 1063 srv.peerFeed.Send(&PeerEvent{ 1064 Type: PeerEventTypeDrop, 1065 Peer: p.ID(), 1066 Error: err.Error(), 1067 RemoteAddress: p.RemoteAddr().String(), 1068 LocalAddress: p.LocalAddr().String(), 1069 }) 1070 } 1071 1072 // NodeInfo represents a short summary of the information known about the host. 1073 type NodeInfo struct { 1074 ID string `json:"id"` // Unique node identifier (also the encryption key) 1075 Name string `json:"name"` // Name of the node, including client type, version, OS, custom data 1076 Enode string `json:"enode"` // Enode URL for adding this peer from remote peers 1077 ENR string `json:"enr"` // Ethereum Node Record 1078 IP string `json:"ip"` // IP address of the node 1079 Ports struct { 1080 Discovery int `json:"discovery"` // UDP listening port for discovery protocol 1081 Listener int `json:"listener"` // TCP listening port for RLPx 1082 } `json:"ports"` 1083 ListenAddr string `json:"listenAddr"` 1084 Protocols map[string]interface{} `json:"protocols"` 1085 } 1086 1087 // NodeInfo gathers and returns a collection of metadata known about the host. 1088 func (srv *Server) NodeInfo() *NodeInfo { 1089 // Gather and assemble the generic node infos 1090 node := srv.Self() 1091 info := &NodeInfo{ 1092 Name: srv.Name, 1093 Enode: node.URLv4(), 1094 ID: node.ID().String(), 1095 IP: node.IP().String(), 1096 ListenAddr: srv.ListenAddr, 1097 Protocols: make(map[string]interface{}), 1098 } 1099 info.Ports.Discovery = node.UDP() 1100 info.Ports.Listener = node.TCP() 1101 info.ENR = node.String() 1102 1103 // Gather all the running protocol infos (only once per protocol type) 1104 for _, proto := range srv.Protocols { 1105 if _, ok := info.Protocols[proto.Name]; !ok { 1106 nodeInfo := interface{}("unknown") 1107 if query := proto.NodeInfo; query != nil { 1108 nodeInfo = proto.NodeInfo() 1109 } 1110 info.Protocols[proto.Name] = nodeInfo 1111 } 1112 } 1113 return info 1114 } 1115 1116 // PeersInfo returns an array of metadata objects describing connected peers. 1117 func (srv *Server) PeersInfo() []*PeerInfo { 1118 // Gather all the generic and sub-protocol specific infos 1119 infos := make([]*PeerInfo, 0, srv.PeerCount()) 1120 for _, peer := range srv.Peers() { 1121 if peer != nil { 1122 infos = append(infos, peer.Info()) 1123 } 1124 } 1125 // Sort the result array alphabetically by node identifier 1126 for i := 0; i < len(infos); i++ { 1127 for j := i + 1; j < len(infos); j++ { 1128 if infos[i].ID > infos[j].ID { 1129 infos[i], infos[j] = infos[j], infos[i] 1130 } 1131 } 1132 } 1133 return infos 1134 }