gitlab.com/aquachain/aquachain@v1.17.16-rc3.0.20221018032414-e3ddf1e1c055/p2p/server.go (about)

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