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