github.com/core-coin/go-core/v2@v2.1.9/p2p/server.go (about)

     1  // Copyright 2014 by the Authors
     2  // This file is part of the go-core library.
     3  //
     4  // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // Package p2p implements the Core p2p network protocols.
    18  package p2p
    19  
    20  import (
    21  	"bytes"
    22  	"encoding/hex"
    23  	"errors"
    24  	"fmt"
    25  	"net"
    26  	"sort"
    27  	"sync"
    28  	"sync/atomic"
    29  	"time"
    30  
    31  	"github.com/core-coin/go-core/v2/common"
    32  	"github.com/core-coin/go-core/v2/common/mclock"
    33  	"github.com/core-coin/go-core/v2/crypto"
    34  	"github.com/core-coin/go-core/v2/event"
    35  	"github.com/core-coin/go-core/v2/log"
    36  	"github.com/core-coin/go-core/v2/p2p/discover"
    37  	"github.com/core-coin/go-core/v2/p2p/discv5"
    38  	"github.com/core-coin/go-core/v2/p2p/enode"
    39  	"github.com/core-coin/go-core/v2/p2p/enr"
    40  	"github.com/core-coin/go-core/v2/p2p/nat"
    41  	"github.com/core-coin/go-core/v2/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 ed448 private key.
    72  	PrivateKey *crypto.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 []*discv5.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, *crypto.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    *discv5.Network
   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 *crypto.PrivateKey) (*crypto.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  // SubscribePeers 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 discv5.conn
   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 discv5.conn
   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 := srv.PrivateKey.PublicKey()
   494  	srv.ourHandshake = &protoHandshake{Version: baseProtocolVersion, Name: srv.Name, ID: pubkey[:]}
   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, "core 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.ListenUDP(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  		var ntab *discv5.Network
   599  		var err error
   600  		if sconn != nil {
   601  			ntab, err = discv5.ListenUDP(srv.PrivateKey, sconn, "", srv.NetRestrict)
   602  		} else {
   603  			ntab, err = discv5.ListenUDP(srv.PrivateKey, conn, "", srv.NetRestrict)
   604  		}
   605  		if err != nil {
   606  			return err
   607  		}
   608  		if err := ntab.SetFallbackNodes(srv.BootstrapNodesV5); err != nil {
   609  			return err
   610  		}
   611  		srv.DiscV5 = ntab
   612  	}
   613  	return nil
   614  }
   615  
   616  func (srv *Server) setupDialScheduler() {
   617  	config := dialConfig{
   618  		self:           srv.localnode.ID(),
   619  		maxDialPeers:   srv.maxDialedConns(),
   620  		maxActiveDials: srv.MaxPendingPeers,
   621  		log:            srv.Logger,
   622  		netRestrict:    srv.NetRestrict,
   623  		dialer:         srv.Dialer,
   624  		clock:          srv.clock,
   625  	}
   626  	if srv.ntab != nil {
   627  		config.resolver = srv.ntab
   628  	}
   629  	if config.dialer == nil {
   630  		config.dialer = tcpDialer{&net.Dialer{Timeout: defaultDialTimeout}}
   631  	}
   632  	srv.dialsched = newDialScheduler(config, srv.discmix, srv.SetupConn)
   633  	for _, n := range srv.StaticNodes {
   634  		srv.dialsched.addStatic(n)
   635  	}
   636  }
   637  
   638  func (srv *Server) maxInboundConns() int {
   639  	return srv.MaxPeers - srv.maxDialedConns()
   640  }
   641  
   642  func (srv *Server) maxDialedConns() (limit int) {
   643  	if srv.NoDial || srv.MaxPeers == 0 {
   644  		return 0
   645  	}
   646  	if srv.DialRatio == 0 {
   647  		limit = srv.MaxPeers / defaultDialRatio
   648  	} else {
   649  		limit = srv.MaxPeers / srv.DialRatio
   650  	}
   651  	if limit == 0 {
   652  		limit = 1
   653  	}
   654  	return limit
   655  }
   656  
   657  func (srv *Server) setupListening() error {
   658  	// Launch the listener.
   659  	listener, err := srv.listenFunc("tcp", srv.ListenAddr)
   660  	if err != nil {
   661  		return err
   662  	}
   663  	srv.listener = listener
   664  	srv.ListenAddr = listener.Addr().String()
   665  
   666  	// Update the local node record and map the TCP listening port if NAT is configured.
   667  	if tcp, ok := listener.Addr().(*net.TCPAddr); ok {
   668  		srv.localnode.Set(enr.TCP(tcp.Port))
   669  		if !tcp.IP.IsLoopback() && srv.NAT != nil {
   670  			srv.loopWG.Add(1)
   671  			go func() {
   672  				nat.Map(srv.NAT, srv.quit, "tcp", tcp.Port, tcp.Port, "core p2p")
   673  				srv.loopWG.Done()
   674  			}()
   675  		}
   676  	}
   677  
   678  	srv.loopWG.Add(1)
   679  	go srv.listenLoop()
   680  	return nil
   681  }
   682  
   683  // doPeerOp runs fn on the main loop.
   684  func (srv *Server) doPeerOp(fn peerOpFunc) {
   685  	select {
   686  	case srv.peerOp <- fn:
   687  		<-srv.peerOpDone
   688  	case <-srv.quit:
   689  	}
   690  }
   691  
   692  // run is the main loop of the server.
   693  func (srv *Server) run() {
   694  	srv.log.Info("Started P2P networking", "self", srv.localnode.Node().URLv4())
   695  	defer srv.loopWG.Done()
   696  	defer srv.nodedb.Close()
   697  	defer srv.discmix.Close()
   698  	defer srv.dialsched.stop()
   699  
   700  	var (
   701  		peers        = make(map[enode.ID]*Peer)
   702  		inboundCount = 0
   703  		trusted      = make(map[enode.ID]bool, len(srv.TrustedNodes))
   704  	)
   705  	// Put trusted nodes into a map to speed up checks.
   706  	// Trusted peers are loaded on startup or added via AddTrustedPeer RPC.
   707  	for _, n := range srv.TrustedNodes {
   708  		trusted[n.ID()] = true
   709  	}
   710  
   711  running:
   712  	for {
   713  		select {
   714  		case <-srv.quit:
   715  			// The server was stopped. Run the cleanup logic.
   716  			break running
   717  
   718  		case n := <-srv.addtrusted:
   719  			// This channel is used by AddTrustedPeer to add a node
   720  			// to the trusted node set.
   721  			srv.log.Trace("Adding trusted node", "node", n)
   722  			trusted[n.ID()] = true
   723  			if p, ok := peers[n.ID()]; ok {
   724  				p.rw.set(trustedConn, true)
   725  			}
   726  
   727  		case n := <-srv.removetrusted:
   728  			// This channel is used by RemoveTrustedPeer to remove a node
   729  			// from the trusted node set.
   730  			srv.log.Trace("Removing trusted node", "node", n)
   731  			delete(trusted, n.ID())
   732  			if p, ok := peers[n.ID()]; ok {
   733  				p.rw.set(trustedConn, false)
   734  			}
   735  
   736  		case op := <-srv.peerOp:
   737  			// This channel is used by Peers and PeerCount.
   738  			op(peers)
   739  			srv.peerOpDone <- struct{}{}
   740  
   741  		case c := <-srv.checkpointPostHandshake:
   742  			// A connection has passed the encryption handshake so
   743  			// the remote identity is known (but hasn't been verified yet).
   744  			if trusted[c.node.ID()] {
   745  				// Ensure that the trusted flag is set before checking against MaxPeers.
   746  				c.flags |= trustedConn
   747  			}
   748  			// TODO: track in-progress inbound node IDs (pre-Peer) to avoid dialing them.
   749  			c.cont <- srv.postHandshakeChecks(peers, inboundCount, c)
   750  
   751  		case c := <-srv.checkpointAddPeer:
   752  			// At this point the connection is past the protocol handshake.
   753  			// Its capabilities are known and the remote identity is verified.
   754  			err := srv.addPeerChecks(peers, inboundCount, c)
   755  			if err == nil {
   756  				// The handshakes are done and it passed all checks.
   757  				p := srv.launchPeer(c)
   758  				peers[c.node.ID()] = p
   759  				srv.log.Debug("Adding p2p peer", "peercount", len(peers), "id", p.ID(), "conn", c.flags, "addr", p.RemoteAddr(), "name", p.Name())
   760  				srv.dialsched.peerAdded(c)
   761  				if p.Inbound() {
   762  					inboundCount++
   763  				}
   764  			}
   765  			c.cont <- err
   766  
   767  		case pd := <-srv.delpeer:
   768  			// A peer disconnected.
   769  			d := common.PrettyDuration(mclock.Now() - pd.created)
   770  			delete(peers, pd.ID())
   771  			srv.log.Debug("Removing p2p peer", "peercount", len(peers), "id", pd.ID(), "duration", d, "req", pd.requested, "err", pd.err)
   772  			srv.dialsched.peerRemoved(pd.rw)
   773  			if pd.Inbound() {
   774  				inboundCount--
   775  			}
   776  		}
   777  	}
   778  
   779  	srv.log.Trace("P2P networking is spinning down")
   780  
   781  	// Terminate discovery. If there is a running lookup it will terminate soon.
   782  	if srv.ntab != nil {
   783  		srv.ntab.Close()
   784  	}
   785  	if srv.DiscV5 != nil {
   786  		srv.DiscV5.Close()
   787  	}
   788  	// Disconnect all peers.
   789  	for _, p := range peers {
   790  		p.Disconnect(DiscQuitting)
   791  	}
   792  	// Wait for peers to shut down. Pending connections and tasks are
   793  	// not handled here and will terminate soon-ish because srv.quit
   794  	// is closed.
   795  	for len(peers) > 0 {
   796  		p := <-srv.delpeer
   797  		p.log.Trace("<-delpeer (spindown)")
   798  		delete(peers, p.ID())
   799  	}
   800  }
   801  
   802  func (srv *Server) postHandshakeChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error {
   803  	switch {
   804  	case !c.is(trustedConn) && len(peers) >= srv.MaxPeers:
   805  		return DiscTooManyPeers
   806  	case !c.is(trustedConn) && c.is(inboundConn) && inboundCount >= srv.maxInboundConns():
   807  		return DiscTooManyInboundPeers
   808  	case peers[c.node.ID()] != nil:
   809  		return DiscAlreadyConnected
   810  	case c.node.ID() == srv.localnode.ID():
   811  		return DiscSelf
   812  	default:
   813  		return nil
   814  	}
   815  }
   816  
   817  func (srv *Server) addPeerChecks(peers map[enode.ID]*Peer, inboundCount int, c *conn) error {
   818  	// Drop connections with no matching protocols.
   819  	if len(srv.Protocols) > 0 && countMatchingProtocols(srv.Protocols, c.caps) == 0 {
   820  		return DiscUselessPeer
   821  	}
   822  	// Repeat the post-handshake checks because the
   823  	// peer set might have changed since those checks were performed.
   824  	return srv.postHandshakeChecks(peers, inboundCount, c)
   825  }
   826  
   827  // listenLoop runs in its own goroutine and accepts
   828  // inbound connections.
   829  func (srv *Server) listenLoop() {
   830  	srv.log.Debug("TCP listener up", "addr", srv.listener.Addr())
   831  
   832  	// The slots channel limits accepts of new connections.
   833  	tokens := defaultMaxPendingPeers
   834  	if srv.MaxPendingPeers > 0 {
   835  		tokens = srv.MaxPendingPeers
   836  	}
   837  	slots := make(chan struct{}, tokens)
   838  	for i := 0; i < tokens; i++ {
   839  		slots <- struct{}{}
   840  	}
   841  
   842  	// Wait for slots to be returned on exit. This ensures all connection goroutines
   843  	// are down before listenLoop returns.
   844  	defer srv.loopWG.Done()
   845  	defer func() {
   846  		for i := 0; i < cap(slots); i++ {
   847  			<-slots
   848  		}
   849  	}()
   850  
   851  	for {
   852  		// Wait for a free slot before accepting.
   853  		<-slots
   854  
   855  		var (
   856  			fd      net.Conn
   857  			err     error
   858  			lastLog time.Time
   859  		)
   860  		for {
   861  			fd, err = srv.listener.Accept()
   862  			if netutil.IsTemporaryError(err) {
   863  				if time.Since(lastLog) > 1*time.Second {
   864  					srv.log.Debug("Temporary read error", "err", err)
   865  					lastLog = time.Now()
   866  				}
   867  				time.Sleep(time.Millisecond * 200)
   868  				continue
   869  			} else if err != nil {
   870  				srv.log.Debug("Read error", "err", err)
   871  				slots <- struct{}{}
   872  				return
   873  			}
   874  			break
   875  		}
   876  
   877  		remoteIP := netutil.AddrIP(fd.RemoteAddr())
   878  		if err := srv.checkInboundConn(fd, remoteIP); err != nil {
   879  			srv.log.Debug("Rejected inbound connnection", "addr", fd.RemoteAddr(), "err", err)
   880  			fd.Close()
   881  			slots <- struct{}{}
   882  			continue
   883  		}
   884  		if remoteIP != nil {
   885  			var addr *net.TCPAddr
   886  			if tcp, ok := fd.RemoteAddr().(*net.TCPAddr); ok {
   887  				addr = tcp
   888  			}
   889  			fd = newMeteredConn(fd, true, addr)
   890  			srv.log.Trace("Accepted connection", "addr", fd.RemoteAddr())
   891  		}
   892  		go func() {
   893  			srv.SetupConn(fd, inboundConn, nil)
   894  			slots <- struct{}{}
   895  		}()
   896  	}
   897  }
   898  
   899  func (srv *Server) checkInboundConn(fd net.Conn, remoteIP net.IP) error {
   900  	if remoteIP == nil {
   901  		return nil
   902  	}
   903  	// Reject connections that do not match NetRestrict.
   904  	if srv.NetRestrict != nil && !srv.NetRestrict.Contains(remoteIP) {
   905  		return fmt.Errorf("not whitelisted in NetRestrict")
   906  	}
   907  	// Reject Internet peers that try too often.
   908  	now := srv.clock.Now()
   909  	srv.inboundHistory.expire(now, nil)
   910  	if !netutil.IsLAN(remoteIP) && srv.inboundHistory.contains(remoteIP.String()) {
   911  		return fmt.Errorf("too many attempts")
   912  	}
   913  	srv.inboundHistory.add(remoteIP.String(), now.Add(inboundThrottleTime))
   914  	return nil
   915  }
   916  
   917  // SetupConn runs the handshakes and attempts to add the connection
   918  // as a peer. It returns when the connection has been added as a peer
   919  // or the handshakes have failed.
   920  func (srv *Server) SetupConn(fd net.Conn, flags connFlag, dialDest *enode.Node) error {
   921  	c := &conn{fd: fd, flags: flags, cont: make(chan error)}
   922  	if dialDest == nil {
   923  		c.transport = srv.newTransport(fd, nil)
   924  	} else {
   925  		c.transport = srv.newTransport(fd, dialDest.Pubkey())
   926  	}
   927  
   928  	err := srv.setupConn(c, flags, dialDest)
   929  	if err != nil {
   930  		c.close(err)
   931  	}
   932  	return err
   933  }
   934  
   935  func (srv *Server) setupConn(c *conn, flags connFlag, dialDest *enode.Node) error {
   936  	// Prevent leftover pending conns from entering the handshake.
   937  	srv.lock.Lock()
   938  	running := srv.running
   939  	srv.lock.Unlock()
   940  	if !running {
   941  		return errServerStopped
   942  	}
   943  
   944  	// If dialing, figure out the remote public key.
   945  	var dialPubkey *crypto.PublicKey
   946  	if dialDest != nil {
   947  		dialPubkey = new(crypto.PublicKey)
   948  		if err := dialDest.Load((*enode.Ed448)(dialPubkey)); err != nil {
   949  			err = errors.New("dial destination doesn't have a ed448 public key")
   950  			srv.log.Trace("Setting up connection failed", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err)
   951  			return err
   952  		}
   953  	}
   954  
   955  	// Run the RLPx handshake.
   956  	remotePubkey, err := c.doEncHandshake(srv.PrivateKey)
   957  	if err != nil {
   958  		srv.log.Trace("Failed RLPx handshake", "addr", c.fd.RemoteAddr(), "conn", c.flags, "err", err)
   959  		return err
   960  	}
   961  	if dialDest != nil {
   962  		c.node = dialDest
   963  	} else {
   964  		c.node = nodeFromConn(remotePubkey, c.fd)
   965  	}
   966  	clog := srv.log.New("id", c.node.ID(), "addr", c.fd.RemoteAddr(), "conn", c.flags)
   967  	err = srv.checkpoint(c, srv.checkpointPostHandshake)
   968  	if err != nil {
   969  		clog.Trace("Rejected peer", "err", err)
   970  		return err
   971  	}
   972  
   973  	// Run the capability negotiation handshake.
   974  	phs, err := c.doProtoHandshake(srv.ourHandshake)
   975  	if err != nil {
   976  		clog.Trace("Failed p2p handshake", "err", err)
   977  		return err
   978  	}
   979  	if id := c.node.ID(); !bytes.Equal(crypto.SHA3(phs.ID), id[:]) {
   980  		clog.Trace("Wrong devp2p handshake identity", "phsid", hex.EncodeToString(phs.ID))
   981  		return DiscUnexpectedIdentity
   982  	}
   983  	c.caps, c.name = phs.Caps, phs.Name
   984  	err = srv.checkpoint(c, srv.checkpointAddPeer)
   985  	if err != nil {
   986  		clog.Trace("Rejected peer", "err", err)
   987  		return err
   988  	}
   989  
   990  	return nil
   991  }
   992  
   993  func nodeFromConn(pubkey *crypto.PublicKey, conn net.Conn) *enode.Node {
   994  	var ip net.IP
   995  	var port int
   996  	if tcp, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
   997  		ip = tcp.IP
   998  		port = tcp.Port
   999  	}
  1000  	return enode.NewV4(pubkey, ip, port, port)
  1001  }
  1002  
  1003  // checkpoint sends the conn to run, which performs the
  1004  // post-handshake checks for the stage (posthandshake, addpeer).
  1005  func (srv *Server) checkpoint(c *conn, stage chan<- *conn) error {
  1006  	select {
  1007  	case stage <- c:
  1008  	case <-srv.quit:
  1009  		return errServerStopped
  1010  	}
  1011  	return <-c.cont
  1012  }
  1013  
  1014  func (srv *Server) launchPeer(c *conn) *Peer {
  1015  	p := newPeer(srv.log, c, srv.Protocols)
  1016  	if srv.EnableMsgEvents {
  1017  		// If message events are enabled, pass the peerFeed
  1018  		// to the peer.
  1019  		p.events = &srv.peerFeed
  1020  	}
  1021  	go srv.runPeer(p)
  1022  	return p
  1023  }
  1024  
  1025  // runPeer runs in its own goroutine for each peer.
  1026  func (srv *Server) runPeer(p *Peer) {
  1027  	if srv.newPeerHook != nil {
  1028  		srv.newPeerHook(p)
  1029  	}
  1030  	srv.peerFeed.Send(&PeerEvent{
  1031  		Type:          PeerEventTypeAdd,
  1032  		Peer:          p.ID(),
  1033  		RemoteAddress: p.RemoteAddr().String(),
  1034  		LocalAddress:  p.LocalAddr().String(),
  1035  	})
  1036  
  1037  	// Run the per-peer main loop.
  1038  	remoteRequested, err := p.run()
  1039  
  1040  	// Announce disconnect on the main loop to update the peer set.
  1041  	// The main loop waits for existing peers to be sent on srv.delpeer
  1042  	// before returning, so this send should not select on srv.quit.
  1043  	srv.delpeer <- peerDrop{p, err, remoteRequested}
  1044  
  1045  	// Broadcast peer drop to external subscribers. This needs to be
  1046  	// after the send to delpeer so subscribers have a consistent view of
  1047  	// the peer set (i.e. Server.Peers() doesn't include the peer when the
  1048  	// event is received.
  1049  	srv.peerFeed.Send(&PeerEvent{
  1050  		Type:          PeerEventTypeDrop,
  1051  		Peer:          p.ID(),
  1052  		Error:         err.Error(),
  1053  		RemoteAddress: p.RemoteAddr().String(),
  1054  		LocalAddress:  p.LocalAddr().String(),
  1055  	})
  1056  }
  1057  
  1058  // NodeInfo represents a short summary of the information known about the host.
  1059  type NodeInfo struct {
  1060  	ID    string `json:"id"`    // Unique node identifier (also the encryption key)
  1061  	Name  string `json:"name"`  // Name of the node, including client type, version, OS, custom data
  1062  	Enode string `json:"enode"` // Enode URL for adding this peer from remote peers
  1063  	ENR   string `json:"enr"`   // Core Node Record
  1064  	IP    string `json:"ip"`    // IP address of the node
  1065  	Ports struct {
  1066  		Discovery int `json:"discovery"` // UDP listening port for discovery protocol
  1067  		Listener  int `json:"listener"`  // TCP listening port for RLPx
  1068  	} `json:"ports"`
  1069  	ListenAddr string                 `json:"listenAddr"`
  1070  	Protocols  map[string]interface{} `json:"protocols"`
  1071  }
  1072  
  1073  // NodeInfo gathers and returns a collection of metadata known about the host.
  1074  func (srv *Server) NodeInfo() *NodeInfo {
  1075  	// Gather and assemble the generic node infos
  1076  	node := srv.Self()
  1077  	info := &NodeInfo{
  1078  		Name:       srv.Name,
  1079  		Enode:      node.URLv4(),
  1080  		ID:         node.ID().String(),
  1081  		IP:         node.IP().String(),
  1082  		ListenAddr: srv.ListenAddr,
  1083  		Protocols:  make(map[string]interface{}),
  1084  	}
  1085  	info.Ports.Discovery = node.UDP()
  1086  	info.Ports.Listener = node.TCP()
  1087  	info.ENR = node.String()
  1088  
  1089  	// Gather all the running protocol infos (only once per protocol type)
  1090  	for _, proto := range srv.Protocols {
  1091  		if _, ok := info.Protocols[proto.Name]; !ok {
  1092  			nodeInfo := interface{}("unknown")
  1093  			if query := proto.NodeInfo; query != nil {
  1094  				nodeInfo = proto.NodeInfo()
  1095  			}
  1096  			info.Protocols[proto.Name] = nodeInfo
  1097  		}
  1098  	}
  1099  	return info
  1100  }
  1101  
  1102  // PeersInfo returns an array of metadata objects describing connected peers.
  1103  func (srv *Server) PeersInfo() []*PeerInfo {
  1104  	// Gather all the generic and sub-protocol specific infos
  1105  	infos := make([]*PeerInfo, 0, srv.PeerCount())
  1106  	for _, peer := range srv.Peers() {
  1107  		if peer != nil {
  1108  			infos = append(infos, peer.Info())
  1109  		}
  1110  	}
  1111  	// Sort the result array alphabetically by node identifier
  1112  	for i := 0; i < len(infos); i++ {
  1113  		for j := i + 1; j < len(infos); j++ {
  1114  			if infos[i].ID > infos[j].ID {
  1115  				infos[i], infos[j] = infos[j], infos[i]
  1116  			}
  1117  		}
  1118  	}
  1119  	return infos
  1120  }