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