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