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