github.com/bcnmy/go-ethereum@v1.10.27/p2p/server.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package p2p implements the Ethereum p2p network protocols.
    18  package p2p
    19  
    20  import (
    21  	"bytes"
    22  	"crypto/ecdsa"
    23  	"encoding/hex"
    24  	"errors"
    25  	"fmt"
    26  	"net"
    27  	"sort"
    28  	"sync"
    29  	"sync/atomic"
    30  	"time"
    31  
    32  	"github.com/ethereum/go-ethereum/common"
    33  	"github.com/ethereum/go-ethereum/common/mclock"
    34  	"github.com/ethereum/go-ethereum/crypto"
    35  	"github.com/ethereum/go-ethereum/event"
    36  	"github.com/ethereum/go-ethereum/log"
    37  	"github.com/ethereum/go-ethereum/p2p/discover"
    38  	"github.com/ethereum/go-ethereum/p2p/enode"
    39  	"github.com/ethereum/go-ethereum/p2p/enr"
    40  	"github.com/ethereum/go-ethereum/p2p/nat"
    41  	"github.com/ethereum/go-ethereum/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:"-" json:"-"`
   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 DiscAddr is set to a non-nil value, the server will use ListenAddr
   140  	// for TCP and DiscAddr for the UDP discovery protocol.
   141  	DiscAddr 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 trusted list 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  // SubscribeEvents 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  	srv.loopWG.Wait()
   410  }
   411  
   412  // sharedUDPConn implements a shared connection. Write sends messages to the underlying connection while read returns
   413  // messages that were found unprocessable and sent to the unhandled channel by the primary listener.
   414  type sharedUDPConn struct {
   415  	*net.UDPConn
   416  	unhandled chan discover.ReadPacket
   417  }
   418  
   419  // ReadFromUDP implements discover.UDPConn
   420  func (s *sharedUDPConn) ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error) {
   421  	packet, ok := <-s.unhandled
   422  	if !ok {
   423  		return 0, nil, errors.New("connection was closed")
   424  	}
   425  	l := len(packet.Data)
   426  	if l > len(b) {
   427  		l = len(b)
   428  	}
   429  	copy(b[:l], packet.Data[:l])
   430  	return l, packet.Addr, nil
   431  }
   432  
   433  // Close implements discover.UDPConn
   434  func (s *sharedUDPConn) Close() error {
   435  	return nil
   436  }
   437  
   438  // Start starts running the server.
   439  // Servers can not be re-used after stopping.
   440  func (srv *Server) Start() (err error) {
   441  	srv.lock.Lock()
   442  	defer srv.lock.Unlock()
   443  	if srv.running {
   444  		return errors.New("server already running")
   445  	}
   446  	srv.running = true
   447  	srv.log = srv.Config.Logger
   448  	if srv.log == nil {
   449  		srv.log = log.Root()
   450  	}
   451  	if srv.clock == nil {
   452  		srv.clock = mclock.System{}
   453  	}
   454  	if srv.NoDial && srv.ListenAddr == "" {
   455  		srv.log.Warn("P2P server will be useless, neither dialing nor listening")
   456  	}
   457  
   458  	// static fields
   459  	if srv.PrivateKey == nil {
   460  		return errors.New("Server.PrivateKey must be set to a non-nil key")
   461  	}
   462  	if srv.newTransport == nil {
   463  		srv.newTransport = newRLPX
   464  	}
   465  	if srv.listenFunc == nil {
   466  		srv.listenFunc = net.Listen
   467  	}
   468  	srv.quit = make(chan struct{})
   469  	srv.delpeer = make(chan peerDrop)
   470  	srv.checkpointPostHandshake = make(chan *conn)
   471  	srv.checkpointAddPeer = make(chan *conn)
   472  	srv.addtrusted = make(chan *enode.Node)
   473  	srv.removetrusted = make(chan *enode.Node)
   474  	srv.peerOp = make(chan peerOpFunc)
   475  	srv.peerOpDone = make(chan struct{})
   476  
   477  	if err := srv.setupLocalNode(); err != nil {
   478  		return err
   479  	}
   480  	if srv.ListenAddr != "" {
   481  		if err := srv.setupListening(); err != nil {
   482  			return err
   483  		}
   484  	}
   485  	if err := srv.setupDiscovery(); err != nil {
   486  		return err
   487  	}
   488  	srv.setupDialScheduler()
   489  
   490  	srv.loopWG.Add(1)
   491  	go srv.run()
   492  	return nil
   493  }
   494  
   495  func (srv *Server) setupLocalNode() error {
   496  	// Create the devp2p handshake.
   497  	pubkey := crypto.FromECDSAPub(&srv.PrivateKey.PublicKey)
   498  	srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: pubkey[1:]}
   499  	for _, p := range srv.Protocols {
   500  		srv.ourHandshake.Caps = append(srv.ourHandshake.Caps, p.cap())
   501  	}
   502  	sort.Sort(capsByNameAndVersion(srv.ourHandshake.Caps))
   503  
   504  	// Create the local node.
   505  	db, err := enode.OpenDB(srv.Config.NodeDatabase)
   506  	if err != nil {
   507  		return err
   508  	}
   509  	srv.nodedb = db
   510  	srv.localnode = enode.NewLocalNode(db, srv.PrivateKey)
   511  	srv.localnode.SetFallbackIP(net.IP{127, 0, 0, 1})
   512  	// TODO: check conflicts
   513  	for _, p := range srv.Protocols {
   514  		for _, e := range p.Attributes {
   515  			srv.localnode.Set(e)
   516  		}
   517  	}
   518  	switch srv.NAT.(type) {
   519  	case nil:
   520  		// No NAT interface, do nothing.
   521  	case nat.ExtIP:
   522  		// ExtIP doesn't block, set the IP right away.
   523  		ip, _ := srv.NAT.ExternalIP()
   524  		srv.localnode.SetStaticIP(ip)
   525  	default:
   526  		// Ask the router about the IP. This takes a while and blocks startup,
   527  		// do it in the background.
   528  		srv.loopWG.Add(1)
   529  		go func() {
   530  			defer srv.loopWG.Done()
   531  			if ip, err := srv.NAT.ExternalIP(); err == nil {
   532  				srv.localnode.SetStaticIP(ip)
   533  			}
   534  		}()
   535  	}
   536  	return nil
   537  }
   538  
   539  func (srv *Server) setupDiscovery() error {
   540  	srv.discmix = enode.NewFairMix(discmixTimeout)
   541  
   542  	// Add protocol-specific discovery sources.
   543  	added := make(map[string]bool)
   544  	for _, proto := range srv.Protocols {
   545  		if proto.DialCandidates != nil && !added[proto.Name] {
   546  			srv.discmix.AddSource(proto.DialCandidates)
   547  			added[proto.Name] = true
   548  		}
   549  	}
   550  
   551  	// Don't listen on UDP endpoint if DHT is disabled.
   552  	if srv.NoDiscovery && !srv.DiscoveryV5 {
   553  		return nil
   554  	}
   555  
   556  	listenAddr := srv.ListenAddr
   557  
   558  	// Use an alternate listening address for UDP if
   559  	// a custom discovery address is configured.
   560  	if srv.DiscAddr != "" {
   561  		listenAddr = srv.DiscAddr
   562  	}
   563  
   564  	addr, err := net.ResolveUDPAddr("udp", listenAddr)
   565  	if err != nil {
   566  		return err
   567  	}
   568  	conn, err := net.ListenUDP("udp", addr)
   569  	if err != nil {
   570  		return err
   571  	}
   572  	realaddr := conn.LocalAddr().(*net.UDPAddr)
   573  	srv.log.Debug("UDP listener up", "addr", realaddr)
   574  	if srv.NAT != nil {
   575  		if !realaddr.IP.IsLoopback() {
   576  			srv.loopWG.Add(1)
   577  			go func() {
   578  				nat.Map(srv.NAT, srv.quit, "udp", realaddr.Port, realaddr.Port, "ethereum discovery")
   579  				srv.loopWG.Done()
   580  			}()
   581  		}
   582  	}
   583  	srv.localnode.SetFallbackUDP(realaddr.Port)
   584  
   585  	// Discovery V4
   586  	var unhandled chan discover.ReadPacket
   587  	var sconn *sharedUDPConn
   588  	if !srv.NoDiscovery {
   589  		if srv.DiscoveryV5 {
   590  			unhandled = make(chan discover.ReadPacket, 100)
   591  			sconn = &sharedUDPConn{conn, unhandled}
   592  		}
   593  		cfg := discover.Config{
   594  			PrivateKey:  srv.PrivateKey,
   595  			NetRestrict: srv.NetRestrict,
   596  			Bootnodes:   srv.BootstrapNodes,
   597  			Unhandled:   unhandled,
   598  			Log:         srv.log,
   599  		}
   600  		ntab, err := discover.ListenV4(conn, srv.localnode, cfg)
   601  		if err != nil {
   602  			return err
   603  		}
   604  		srv.ntab = ntab
   605  		srv.discmix.AddSource(ntab.RandomNodes())
   606  	}
   607  
   608  	// Discovery V5
   609  	if srv.DiscoveryV5 {
   610  		cfg := discover.Config{
   611  			PrivateKey:  srv.PrivateKey,
   612  			NetRestrict: srv.NetRestrict,
   613  			Bootnodes:   srv.BootstrapNodesV5,
   614  			Log:         srv.log,
   615  		}
   616  		var err error
   617  		if sconn != nil {
   618  			srv.DiscV5, err = discover.ListenV5(sconn, srv.localnode, cfg)
   619  		} else {
   620  			srv.DiscV5, err = discover.ListenV5(conn, srv.localnode, cfg)
   621  		}
   622  		if err != nil {
   623  			return err
   624  		}
   625  	}
   626  	return nil
   627  }
   628  
   629  func (srv *Server) setupDialScheduler() {
   630  	config := dialConfig{
   631  		self:           srv.localnode.ID(),
   632  		maxDialPeers:   srv.maxDialedConns(),
   633  		maxActiveDials: srv.MaxPendingPeers,
   634  		log:            srv.Logger,
   635  		netRestrict:    srv.NetRestrict,
   636  		dialer:         srv.Dialer,
   637  		clock:          srv.clock,
   638  	}
   639  	if srv.ntab != nil {
   640  		config.resolver = srv.ntab
   641  	}
   642  	if config.dialer == nil {
   643  		config.dialer = tcpDialer{&net.Dialer{Timeout: defaultDialTimeout}}
   644  	}
   645  	srv.dialsched = newDialScheduler(config, srv.discmix, srv.SetupConn)
   646  	for _, n := range srv.StaticNodes {
   647  		srv.dialsched.addStatic(n)
   648  	}
   649  }
   650  
   651  func (srv *Server) maxInboundConns() int {
   652  	return srv.MaxPeers - srv.maxDialedConns()
   653  }
   654  
   655  func (srv *Server) maxDialedConns() (limit int) {
   656  	if srv.NoDial || srv.MaxPeers == 0 {
   657  		return 0
   658  	}
   659  	if srv.DialRatio == 0 {
   660  		limit = srv.MaxPeers / defaultDialRatio
   661  	} else {
   662  		limit = srv.MaxPeers / srv.DialRatio
   663  	}
   664  	if limit == 0 {
   665  		limit = 1
   666  	}
   667  	return limit
   668  }
   669  
   670  func (srv *Server) setupListening() error {
   671  	// Launch the listener.
   672  	listener, err := srv.listenFunc("tcp", srv.ListenAddr)
   673  	if err != nil {
   674  		return err
   675  	}
   676  	srv.listener = listener
   677  	srv.ListenAddr = listener.Addr().String()
   678  
   679  	// Update the local node record and map the TCP listening port if NAT is configured.
   680  	if tcp, ok := listener.Addr().(*net.TCPAddr); ok {
   681  		srv.localnode.Set(enr.TCP(tcp.Port))
   682  		if !tcp.IP.IsLoopback() && srv.NAT != nil {
   683  			srv.loopWG.Add(1)
   684  			go func() {
   685  				nat.Map(srv.NAT, srv.quit, "tcp", tcp.Port, tcp.Port, "ethereum p2p")
   686  				srv.loopWG.Done()
   687  			}()
   688  		}
   689  	}
   690  
   691  	srv.loopWG.Add(1)
   692  	go srv.listenLoop()
   693  	return nil
   694  }
   695  
   696  // doPeerOp runs fn on the main loop.
   697  func (srv *Server) doPeerOp(fn peerOpFunc) {
   698  	select {
   699  	case srv.peerOp <- fn:
   700  		<-srv.peerOpDone
   701  	case <-srv.quit:
   702  	}
   703  }
   704  
   705  // run is the main loop of the server.
   706  func (srv *Server) run() {
   707  	srv.log.Info("Started P2P networking", "self", srv.localnode.Node().URLv4())
   708  	defer srv.loopWG.Done()
   709  	defer srv.nodedb.Close()
   710  	defer srv.discmix.Close()
   711  	defer srv.dialsched.stop()
   712  
   713  	var (
   714  		peers        = make(map[enode.ID]*Peer)
   715  		inboundCount = 0
   716  		trusted      = make(map[enode.ID]bool, len(srv.TrustedNodes))
   717  	)
   718  	// Put trusted nodes into a map to speed up checks.
   719  	// Trusted peers are loaded on startup or added via AddTrustedPeer RPC.
   720  	for _, n := range srv.TrustedNodes {
   721  		trusted[n.ID()] = true
   722  	}
   723  
   724  running:
   725  	for {
   726  		select {
   727  		case <-srv.quit:
   728  			// The server was stopped. Run the cleanup logic.
   729  			break running
   730  
   731  		case n := <-srv.addtrusted:
   732  			// This channel is used by AddTrustedPeer to add a node
   733  			// to the trusted node set.
   734  			srv.log.Trace("Adding trusted node", "node", n)
   735  			trusted[n.ID()] = true
   736  			if p, ok := peers[n.ID()]; ok {
   737  				p.rw.set(trustedConn, true)
   738  			}
   739  
   740  		case n := <-srv.removetrusted:
   741  			// This channel is used by RemoveTrustedPeer to remove a node
   742  			// from the trusted node set.
   743  			srv.log.Trace("Removing trusted node", "node", n)
   744  			delete(trusted, n.ID())
   745  			if p, ok := peers[n.ID()]; ok {
   746  				p.rw.set(trustedConn, false)
   747  			}
   748  
   749  		case op := <-srv.peerOp:
   750  			// This channel is used by Peers and PeerCount.
   751  			op(peers)
   752  			srv.peerOpDone <- struct{}{}
   753  
   754  		case c := <-srv.checkpointPostHandshake:
   755  			// A connection has passed the encryption handshake so
   756  			// the remote identity is known (but hasn't been verified yet).
   757  			if trusted[c.node.ID()] {
   758  				// Ensure that the trusted flag is set before checking against MaxPeers.
   759  				c.flags |= trustedConn
   760  			}
   761  			// TODO: track in-progress inbound node IDs (pre-Peer) to avoid dialing them.
   762  			c.cont <- srv.postHandshakeChecks(peers, inboundCount, c)
   763  
   764  		case c := <-srv.checkpointAddPeer:
   765  			// At this point the connection is past the protocol handshake.
   766  			// Its capabilities are known and the remote identity is verified.
   767  			err := srv.addPeerChecks(peers, inboundCount, c)
   768  			if err == nil {
   769  				// The handshakes are done and it passed all checks.
   770  				p := srv.launchPeer(c)
   771  				peers[c.node.ID()] = p
   772  				srv.log.Debug("Adding p2p peer", "peercount", len(peers), "id", p.ID(), "conn", c.flags, "addr", p.RemoteAddr(), "name", p.Name())
   773  				srv.dialsched.peerAdded(c)
   774  				if p.Inbound() {
   775  					inboundCount++
   776  				}
   777  			}
   778  			c.cont <- err
   779  
   780  		case pd := <-srv.delpeer:
   781  			// A peer disconnected.
   782  			d := common.PrettyDuration(mclock.Now() - pd.created)
   783  			delete(peers, pd.ID())
   784  			srv.log.Debug("Removing p2p peer", "peercount", len(peers), "id", pd.ID(), "duration", d, "req", pd.requested, "err", pd.err)
   785  			srv.dialsched.peerRemoved(pd.rw)
   786  			if pd.Inbound() {
   787  				inboundCount--
   788  			}
   789  		}
   790  	}
   791  
   792  	srv.log.Trace("P2P networking is spinning down")
   793  
   794  	// Terminate discovery. If there is a running lookup it will terminate soon.
   795  	if srv.ntab != nil {
   796  		srv.ntab.Close()
   797  	}
   798  	if srv.DiscV5 != nil {
   799  		srv.DiscV5.Close()
   800  	}
   801  	// Disconnect all peers.
   802  	for _, p := range peers {
   803  		p.Disconnect(DiscQuitting)
   804  	}
   805  	// Wait for peers to shut down. Pending connections and tasks are
   806  	// not handled here and will terminate soon-ish because srv.quit
   807  	// is closed.
   808  	for len(peers) > 0 {
   809  		p := <-srv.delpeer
   810  		p.log.Trace("<-delpeer (spindown)")
   811  		delete(peers, p.ID())
   812  	}
   813  }
   814  
   815  func (srv *Server) postHandshakeChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error {
   816  	switch {
   817  	case !c.is(trustedConn) && len(peers) >= srv.MaxPeers:
   818  		return DiscTooManyPeers
   819  	case !c.is(trustedConn) && c.is(inboundConn) && inboundCount >= srv.maxInboundConns():
   820  		return DiscTooManyPeers
   821  	case peers[c.node.ID()] != nil:
   822  		return DiscAlreadyConnected
   823  	case c.node.ID() == srv.localnode.ID():
   824  		return DiscSelf
   825  	default:
   826  		return nil
   827  	}
   828  }
   829  
   830  func (srv *Server) addPeerChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error {
   831  	// Drop connections with no matching protocols.
   832  	if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 {
   833  		return DiscUselessPeer
   834  	}
   835  	// Repeat the post-handshake checks because the
   836  	// peer set might have changed since those checks were performed.
   837  	return srv.postHandshakeChecks(peers, inboundCount, c)
   838  }
   839  
   840  // listenLoop runs in its own goroutine and accepts
   841  // inbound connections.
   842  func (srv *Server) listenLoop() {
   843  	srv.log.Debug("TCP listener up", "addr", srv.listener.Addr())
   844  
   845  	// The slots channel limits accepts of new connections.
   846  	tokens := defaultMaxPendingPeers
   847  	if srv.MaxPendingPeers > 0 {
   848  		tokens = srv.MaxPendingPeers
   849  	}
   850  	slots := make(chan struct{}, tokens)
   851  	for i := 0; i < tokens; i++ {
   852  		slots <- struct{}{}
   853  	}
   854  
   855  	// Wait for slots to be returned on exit. This ensures all connection goroutines
   856  	// are down before listenLoop returns.
   857  	defer srv.loopWG.Done()
   858  	defer func() {
   859  		for i := 0; i < cap(slots); i++ {
   860  			<-slots
   861  		}
   862  	}()
   863  
   864  	for {
   865  		// Wait for a free slot before accepting.
   866  		<-slots
   867  
   868  		var (
   869  			fd      net.Conn
   870  			err     error
   871  			lastLog time.Time
   872  		)
   873  		for {
   874  			fd, err = srv.listener.Accept()
   875  			if netutil.IsTemporaryError(err) {
   876  				if time.Since(lastLog) > 1*time.Second {
   877  					srv.log.Debug("Temporary read error", "err", err)
   878  					lastLog = time.Now()
   879  				}
   880  				time.Sleep(time.Millisecond * 200)
   881  				continue
   882  			} else if err != nil {
   883  				srv.log.Debug("Read error", "err", err)
   884  				slots <- struct{}{}
   885  				return
   886  			}
   887  			break
   888  		}
   889  
   890  		remoteIP := netutil.AddrIP(fd.RemoteAddr())
   891  		if err := srv.checkInboundConn(remoteIP); err != nil {
   892  			srv.log.Debug("Rejected inbound connection", "addr", fd.RemoteAddr(), "err", err)
   893  			fd.Close()
   894  			slots <- struct{}{}
   895  			continue
   896  		}
   897  		if remoteIP != nil {
   898  			var addr *net.TCPAddr
   899  			if tcp, ok := fd.RemoteAddr().(*net.TCPAddr); ok {
   900  				addr = tcp
   901  			}
   902  			fd = newMeteredConn(fd, true, addr)
   903  			srv.log.Trace("Accepted connection", "addr", fd.RemoteAddr())
   904  		}
   905  		go func() {
   906  			srv.SetupConn(fd, inboundConn, nil)
   907  			slots <- struct{}{}
   908  		}()
   909  	}
   910  }
   911  
   912  func (srv *Server) checkInboundConn(remoteIP net.IP) error {
   913  	if remoteIP == nil {
   914  		return nil
   915  	}
   916  	// Reject connections that do not match NetRestrict.
   917  	if srv.NetRestrict != nil && !srv.NetRestrict.Contains(remoteIP) {
   918  		return fmt.Errorf("not in netrestrict list")
   919  	}
   920  	// Reject Internet peers that try too often.
   921  	now := srv.clock.Now()
   922  	srv.inboundHistory.expire(now, nil)
   923  	if !netutil.IsLAN(remoteIP) && srv.inboundHistory.contains(remoteIP.String()) {
   924  		return fmt.Errorf("too many attempts")
   925  	}
   926  	srv.inboundHistory.add(remoteIP.String(), now.Add(inboundThrottleTime))
   927  	return nil
   928  }
   929  
   930  // SetupConn runs the handshakes and attempts to add the connection
   931  // as a peer. It returns when the connection has been added as a peer
   932  // or the handshakes have failed.
   933  func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *enode.Node) error {
   934  	c := &conn{fd: fd, flags: flags, cont: make(chan error)}
   935  	if dialDest == nil {
   936  		c.transport = srv.newTransport(fd, nil)
   937  	} else {
   938  		c.transport = srv.newTransport(fd, dialDest.Pubkey())
   939  	}
   940  
   941  	err := srv.setupConn(c, flags, dialDest)
   942  	if err != nil {
   943  		c.close(err)
   944  	}
   945  	return err
   946  }
   947  
   948  func (srv *Server) setupConn(c *conn, flags connFlag, dialDest *enode.Node) error {
   949  	// Prevent leftover pending conns from entering the handshake.
   950  	srv.lock.Lock()
   951  	running := srv.running
   952  	srv.lock.Unlock()
   953  	if !running {
   954  		return errServerStopped
   955  	}
   956  
   957  	// If dialing, figure out the remote public key.
   958  	if dialDest != nil {
   959  		dialPubkey := new(ecdsa.PublicKey)
   960  		if err := dialDest.Load((*enode.Secp256k1)(dialPubkey)); err != nil {
   961  			err = errors.New("dial destination doesn't have a secp256k1 public key")
   962  			srv.log.Trace("Setting up connection failed", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err)
   963  			return err
   964  		}
   965  	}
   966  
   967  	// Run the RLPx handshake.
   968  	remotePubkey, err := c.doEncHandshake(srv.PrivateKey)
   969  	if err != nil {
   970  		srv.log.Trace("Failed RLPx handshake", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err)
   971  		return err
   972  	}
   973  	if dialDest != nil {
   974  		c.node = dialDest
   975  	} else {
   976  		c.node = nodeFromConn(remotePubkey, c.fd)
   977  	}
   978  	clog := srv.log.New("id", c.node.ID(), "addr", c.fd.RemoteAddr(), "conn", c.flags)
   979  	err = srv.checkpoint(c, srv.checkpointPostHandshake)
   980  	if err != nil {
   981  		clog.Trace("Rejected peer", "err", err)
   982  		return err
   983  	}
   984  
   985  	// Run the capability negotiation handshake.
   986  	phs, err := c.doProtoHandshake(srv.ourHandshake)
   987  	if err != nil {
   988  		clog.Trace("Failed p2p handshake", "err", err)
   989  		return err
   990  	}
   991  	if id := c.node.ID(); !bytes.Equal(crypto.Keccak256(phs.ID), id[:]) {
   992  		clog.Trace("Wrong devp2p handshake identity", "phsid", hex.EncodeToString(phs.ID))
   993  		return DiscUnexpectedIdentity
   994  	}
   995  	c.caps, c.name = phs.Caps, phs.Name
   996  	err = srv.checkpoint(c, srv.checkpointAddPeer)
   997  	if err != nil {
   998  		clog.Trace("Rejected peer", "err", err)
   999  		return err
  1000  	}
  1001  
  1002  	return nil
  1003  }
  1004  
  1005  func nodeFromConn(pubkey *ecdsa.PublicKey, conn net.Conn) *enode.Node {
  1006  	var ip net.IP
  1007  	var port int
  1008  	if tcp, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
  1009  		ip = tcp.IP
  1010  		port = tcp.Port
  1011  	}
  1012  	return enode.NewV4(pubkey, ip, port, port)
  1013  }
  1014  
  1015  // checkpoint sends the conn to run, which performs the
  1016  // post-handshake checks for the stage (posthandshake, addpeer).
  1017  func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error {
  1018  	select {
  1019  	case stage <- c:
  1020  	case <-srv.quit:
  1021  		return errServerStopped
  1022  	}
  1023  	return <-c.cont
  1024  }
  1025  
  1026  func (srv *Server) launchPeer(c *conn) *Peer {
  1027  	p := newPeer(srv.log, c, srv.Protocols)
  1028  	if srv.EnableMsgEvents {
  1029  		// If message events are enabled, pass the peerFeed
  1030  		// to the peer.
  1031  		p.events = &srv.peerFeed
  1032  	}
  1033  	go srv.runPeer(p)
  1034  	return p
  1035  }
  1036  
  1037  // runPeer runs in its own goroutine for each peer.
  1038  func (srv *Server) runPeer(p *Peer) {
  1039  	if srv.newPeerHook != nil {
  1040  		srv.newPeerHook(p)
  1041  	}
  1042  	srv.peerFeed.Send(&PeerEvent{
  1043  		Type:          PeerEventTypeAdd,
  1044  		Peer:          p.ID(),
  1045  		RemoteAddress: p.RemoteAddr().String(),
  1046  		LocalAddress:  p.LocalAddr().String(),
  1047  	})
  1048  
  1049  	// Run the per-peer main loop.
  1050  	remoteRequested, err := p.run()
  1051  
  1052  	// Announce disconnect on the main loop to update the peer set.
  1053  	// The main loop waits for existing peers to be sent on srv.delpeer
  1054  	// before returning, so this send should not select on srv.quit.
  1055  	srv.delpeer <- peerDrop{p, err, remoteRequested}
  1056  
  1057  	// Broadcast peer drop to external subscribers. This needs to be
  1058  	// after the send to delpeer so subscribers have a consistent view of
  1059  	// the peer set (i.e. Server.Peers() doesn't include the peer when the
  1060  	// event is received.
  1061  	srv.peerFeed.Send(&PeerEvent{
  1062  		Type:          PeerEventTypeDrop,
  1063  		Peer:          p.ID(),
  1064  		Error:         err.Error(),
  1065  		RemoteAddress: p.RemoteAddr().String(),
  1066  		LocalAddress:  p.LocalAddr().String(),
  1067  	})
  1068  }
  1069  
  1070  // NodeInfo represents a short summary of the information known about the host.
  1071  type NodeInfo struct {
  1072  	ID    string `json:"id"`    // Unique node identifier (also the encryption key)
  1073  	Name  string `json:"name"`  // Name of the node, including client type, version, OS, custom data
  1074  	Enode string `json:"enode"` // Enode URL for adding this peer from remote peers
  1075  	ENR   string `json:"enr"`   // Ethereum Node Record
  1076  	IP    string `json:"ip"`    // IP address of the node
  1077  	Ports struct {
  1078  		Discovery int `json:"discovery"` // UDP listening port for discovery protocol
  1079  		Listener  int `json:"listener"`  // TCP listening port for RLPx
  1080  	} `json:"ports"`
  1081  	ListenAddr string                 `json:"listenAddr"`
  1082  	Protocols  map[string]interface{} `json:"protocols"`
  1083  }
  1084  
  1085  // NodeInfo gathers and returns a collection of metadata known about the host.
  1086  func (srv *Server) NodeInfo() *NodeInfo {
  1087  	// Gather and assemble the generic node infos
  1088  	node := srv.Self()
  1089  	info := &NodeInfo{
  1090  		Name:       srv.Name,
  1091  		Enode:      node.URLv4(),
  1092  		ID:         node.ID().String(),
  1093  		IP:         node.IP().String(),
  1094  		ListenAddr: srv.ListenAddr,
  1095  		Protocols:  make(map[string]interface{}),
  1096  	}
  1097  	info.Ports.Discovery = node.UDP()
  1098  	info.Ports.Listener = node.TCP()
  1099  	info.ENR = node.String()
  1100  
  1101  	// Gather all the running protocol infos (only once per protocol type)
  1102  	for _, proto := range srv.Protocols {
  1103  		if _, ok := info.Protocols[proto.Name]; !ok {
  1104  			nodeInfo := interface{}("unknown")
  1105  			if query := proto.NodeInfo; query != nil {
  1106  				nodeInfo = proto.NodeInfo()
  1107  			}
  1108  			info.Protocols[proto.Name] = nodeInfo
  1109  		}
  1110  	}
  1111  	return info
  1112  }
  1113  
  1114  // PeersInfo returns an array of metadata objects describing connected peers.
  1115  func (srv *Server) PeersInfo() []*PeerInfo {
  1116  	// Gather all the generic and sub-protocol specific infos
  1117  	infos := make([]*PeerInfo, 0, srv.PeerCount())
  1118  	for _, peer := range srv.Peers() {
  1119  		if peer != nil {
  1120  			infos = append(infos, peer.Info())
  1121  		}
  1122  	}
  1123  	// Sort the result array alphabetically by node identifier
  1124  	for i := 0; i < len(infos); i++ {
  1125  		for j := i + 1; j < len(infos); j++ {
  1126  			if infos[i].ID > infos[j].ID {
  1127  				infos[i], infos[j] = infos[j], infos[i]
  1128  			}
  1129  		}
  1130  	}
  1131  	return infos
  1132  }