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