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