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