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