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