github.com/Unheilbar/quorum@v1.0.0/p2p/server.go (about)

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