github.com/ethereum/go-ethereum@v1.16.1/ethstats/ethstats.go (about)

     1  // Copyright 2016 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 ethstats implements the network stats reporting service.
    18  package ethstats
    19  
    20  import (
    21  	"context"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"math/big"
    26  	"net/http"
    27  	"runtime"
    28  	"strconv"
    29  	"strings"
    30  	"sync"
    31  	"time"
    32  
    33  	"github.com/ethereum/go-ethereum"
    34  	"github.com/ethereum/go-ethereum/common"
    35  	"github.com/ethereum/go-ethereum/common/mclock"
    36  	"github.com/ethereum/go-ethereum/consensus"
    37  	"github.com/ethereum/go-ethereum/core"
    38  	"github.com/ethereum/go-ethereum/core/types"
    39  	ethproto "github.com/ethereum/go-ethereum/eth/protocols/eth"
    40  	"github.com/ethereum/go-ethereum/event"
    41  	"github.com/ethereum/go-ethereum/log"
    42  	"github.com/ethereum/go-ethereum/node"
    43  	"github.com/ethereum/go-ethereum/p2p"
    44  	"github.com/ethereum/go-ethereum/rpc"
    45  	"github.com/gorilla/websocket"
    46  )
    47  
    48  const (
    49  	// historyUpdateRange is the number of blocks a node should report upon login or
    50  	// history request.
    51  	historyUpdateRange = 50
    52  
    53  	// txChanSize is the size of channel listening to NewTxsEvent.
    54  	// The number is referenced from the size of tx pool.
    55  	txChanSize = 4096
    56  	// chainHeadChanSize is the size of channel listening to ChainHeadEvent.
    57  	chainHeadChanSize = 10
    58  
    59  	messageSizeLimit = 15 * 1024 * 1024
    60  )
    61  
    62  // backend encompasses the bare-minimum functionality needed for ethstats reporting
    63  type backend interface {
    64  	SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription
    65  	SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription
    66  	CurrentHeader() *types.Header
    67  	HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error)
    68  	Stats() (pending int, queued int)
    69  	SyncProgress(ctx context.Context) ethereum.SyncProgress
    70  }
    71  
    72  // fullNodeBackend encompasses the functionality necessary for a full node
    73  // reporting to ethstats
    74  type fullNodeBackend interface {
    75  	backend
    76  	BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error)
    77  	CurrentBlock() *types.Header
    78  	SuggestGasTipCap(ctx context.Context) (*big.Int, error)
    79  }
    80  
    81  // Service implements an Ethereum netstats reporting daemon that pushes local
    82  // chain statistics up to a monitoring server.
    83  type Service struct {
    84  	server  *p2p.Server // Peer-to-peer server to retrieve networking infos
    85  	backend backend
    86  	engine  consensus.Engine // Consensus engine to retrieve variadic block fields
    87  
    88  	node string // Name of the node to display on the monitoring page
    89  	pass string // Password to authorize access to the monitoring page
    90  	host string // Remote address of the monitoring service
    91  
    92  	pongCh chan struct{} // Pong notifications are fed into this channel
    93  	histCh chan []uint64 // History request block numbers are fed into this channel
    94  
    95  	headSub event.Subscription
    96  	txSub   event.Subscription
    97  }
    98  
    99  // connWrapper is a wrapper to prevent concurrent-write or concurrent-read on the
   100  // websocket.
   101  //
   102  // From Gorilla websocket docs:
   103  //
   104  // Connections support one concurrent reader and one concurrent writer. Applications are
   105  // responsible for ensuring that
   106  //   - no more than one goroutine calls the write methods
   107  //     NextWriter, SetWriteDeadline, WriteMessage, WriteJSON, EnableWriteCompression,
   108  //     SetCompressionLevel concurrently; and
   109  //   - that no more than one goroutine calls the
   110  //     read methods NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler,
   111  //     SetPingHandler concurrently.
   112  //
   113  // The Close and WriteControl methods can be called concurrently with all other methods.
   114  type connWrapper struct {
   115  	conn *websocket.Conn
   116  
   117  	rlock sync.Mutex
   118  	wlock sync.Mutex
   119  }
   120  
   121  func newConnectionWrapper(conn *websocket.Conn) *connWrapper {
   122  	conn.SetReadLimit(messageSizeLimit)
   123  	return &connWrapper{conn: conn}
   124  }
   125  
   126  // WriteJSON wraps corresponding method on the websocket but is safe for concurrent calling
   127  func (w *connWrapper) WriteJSON(v interface{}) error {
   128  	w.wlock.Lock()
   129  	defer w.wlock.Unlock()
   130  
   131  	return w.conn.WriteJSON(v)
   132  }
   133  
   134  // ReadJSON wraps corresponding method on the websocket but is safe for concurrent calling
   135  func (w *connWrapper) ReadJSON(v interface{}) error {
   136  	w.rlock.Lock()
   137  	defer w.rlock.Unlock()
   138  
   139  	return w.conn.ReadJSON(v)
   140  }
   141  
   142  // Close wraps corresponding method on the websocket but is safe for concurrent calling
   143  func (w *connWrapper) Close() error {
   144  	// The Close and WriteControl methods can be called concurrently with all other methods,
   145  	// so the mutex is not used here
   146  	return w.conn.Close()
   147  }
   148  
   149  // parseEthstatsURL parses the netstats connection url.
   150  // URL argument should be of the form <nodename:secret@host:port>
   151  // If non-erroring, the returned slice contains 3 elements: [nodename, pass, host]
   152  func parseEthstatsURL(url string) (parts []string, err error) {
   153  	err = fmt.Errorf("invalid netstats url: \"%s\", should be nodename:secret@host:port", url)
   154  
   155  	hostIndex := strings.LastIndex(url, "@")
   156  	if hostIndex == -1 || hostIndex == len(url)-1 {
   157  		return nil, err
   158  	}
   159  	preHost, host := url[:hostIndex], url[hostIndex+1:]
   160  
   161  	passIndex := strings.LastIndex(preHost, ":")
   162  	if passIndex == -1 {
   163  		return []string{preHost, "", host}, nil
   164  	}
   165  	nodename, pass := preHost[:passIndex], ""
   166  	if passIndex != len(preHost)-1 {
   167  		pass = preHost[passIndex+1:]
   168  	}
   169  
   170  	return []string{nodename, pass, host}, nil
   171  }
   172  
   173  // New returns a monitoring service ready for stats reporting.
   174  func New(node *node.Node, backend backend, engine consensus.Engine, url string) error {
   175  	parts, err := parseEthstatsURL(url)
   176  	if err != nil {
   177  		return err
   178  	}
   179  	ethstats := &Service{
   180  		backend: backend,
   181  		engine:  engine,
   182  		server:  node.Server(),
   183  		node:    parts[0],
   184  		pass:    parts[1],
   185  		host:    parts[2],
   186  		pongCh:  make(chan struct{}),
   187  		histCh:  make(chan []uint64, 1),
   188  	}
   189  
   190  	node.RegisterLifecycle(ethstats)
   191  	return nil
   192  }
   193  
   194  // Start implements node.Lifecycle, starting up the monitoring and reporting daemon.
   195  func (s *Service) Start() error {
   196  	// Subscribe to chain events to execute updates on
   197  	chainHeadCh := make(chan core.ChainHeadEvent, chainHeadChanSize)
   198  	s.headSub = s.backend.SubscribeChainHeadEvent(chainHeadCh)
   199  	txEventCh := make(chan core.NewTxsEvent, txChanSize)
   200  	s.txSub = s.backend.SubscribeNewTxsEvent(txEventCh)
   201  	go s.loop(chainHeadCh, txEventCh)
   202  
   203  	log.Info("Stats daemon started")
   204  	return nil
   205  }
   206  
   207  // Stop implements node.Lifecycle, terminating the monitoring and reporting daemon.
   208  func (s *Service) Stop() error {
   209  	s.headSub.Unsubscribe()
   210  	s.txSub.Unsubscribe()
   211  	log.Info("Stats daemon stopped")
   212  	return nil
   213  }
   214  
   215  // loop keeps trying to connect to the netstats server, reporting chain events
   216  // until termination.
   217  func (s *Service) loop(chainHeadCh chan core.ChainHeadEvent, txEventCh chan core.NewTxsEvent) {
   218  	// Start a goroutine that exhausts the subscriptions to avoid events piling up
   219  	var (
   220  		quitCh = make(chan struct{})
   221  		headCh = make(chan *types.Header, 1)
   222  		txCh   = make(chan struct{}, 1)
   223  	)
   224  	go func() {
   225  		var lastTx mclock.AbsTime
   226  
   227  	HandleLoop:
   228  		for {
   229  			select {
   230  			// Notify of chain head events, but drop if too frequent
   231  			case head := <-chainHeadCh:
   232  				select {
   233  				case headCh <- head.Header:
   234  				default:
   235  				}
   236  
   237  			// Notify of new transaction events, but drop if too frequent
   238  			case <-txEventCh:
   239  				if time.Duration(mclock.Now()-lastTx) < time.Second {
   240  					continue
   241  				}
   242  				lastTx = mclock.Now()
   243  
   244  				select {
   245  				case txCh <- struct{}{}:
   246  				default:
   247  				}
   248  
   249  			// node stopped
   250  			case <-s.txSub.Err():
   251  				break HandleLoop
   252  			case <-s.headSub.Err():
   253  				break HandleLoop
   254  			}
   255  		}
   256  		close(quitCh)
   257  	}()
   258  
   259  	// Resolve the URL, defaulting to TLS, but falling back to none too
   260  	path := fmt.Sprintf("%s/api", s.host)
   261  	urls := []string{path}
   262  
   263  	// url.Parse and url.IsAbs is unsuitable (https://github.com/golang/go/issues/19779)
   264  	if !strings.Contains(path, "://") {
   265  		urls = []string{"wss://" + path, "ws://" + path}
   266  	}
   267  
   268  	errTimer := time.NewTimer(0)
   269  	defer errTimer.Stop()
   270  	// Loop reporting until termination
   271  	for {
   272  		select {
   273  		case <-quitCh:
   274  			return
   275  		case <-errTimer.C:
   276  			// Establish a websocket connection to the server on any supported URL
   277  			var (
   278  				conn *connWrapper
   279  				err  error
   280  			)
   281  			dialer := websocket.Dialer{HandshakeTimeout: 5 * time.Second}
   282  			header := make(http.Header)
   283  			header.Set("origin", "http://localhost")
   284  			for _, url := range urls {
   285  				c, _, e := dialer.Dial(url, header)
   286  				err = e
   287  				if err == nil {
   288  					conn = newConnectionWrapper(c)
   289  					break
   290  				}
   291  			}
   292  			if err != nil {
   293  				log.Warn("Stats server unreachable", "err", err)
   294  				errTimer.Reset(10 * time.Second)
   295  				continue
   296  			}
   297  			// Authenticate the client with the server
   298  			if err = s.login(conn); err != nil {
   299  				log.Warn("Stats login failed", "err", err)
   300  				conn.Close()
   301  				errTimer.Reset(10 * time.Second)
   302  				continue
   303  			}
   304  			go s.readLoop(conn)
   305  
   306  			// Send the initial stats so our node looks decent from the get go
   307  			if err = s.report(conn); err != nil {
   308  				log.Warn("Initial stats report failed", "err", err)
   309  				conn.Close()
   310  				errTimer.Reset(0)
   311  				continue
   312  			}
   313  			// Keep sending status updates until the connection breaks
   314  			fullReport := time.NewTicker(15 * time.Second)
   315  
   316  			for err == nil {
   317  				select {
   318  				case <-quitCh:
   319  					fullReport.Stop()
   320  					// Make sure the connection is closed
   321  					conn.Close()
   322  					return
   323  
   324  				case <-fullReport.C:
   325  					if err = s.report(conn); err != nil {
   326  						log.Warn("Full stats report failed", "err", err)
   327  					}
   328  				case list := <-s.histCh:
   329  					if err = s.reportHistory(conn, list); err != nil {
   330  						log.Warn("Requested history report failed", "err", err)
   331  					}
   332  				case head := <-headCh:
   333  					if err = s.reportBlock(conn, head); err != nil {
   334  						log.Warn("Block stats report failed", "err", err)
   335  					}
   336  					if err = s.reportPending(conn); err != nil {
   337  						log.Warn("Post-block transaction stats report failed", "err", err)
   338  					}
   339  				case <-txCh:
   340  					if err = s.reportPending(conn); err != nil {
   341  						log.Warn("Transaction stats report failed", "err", err)
   342  					}
   343  				}
   344  			}
   345  			fullReport.Stop()
   346  
   347  			// Close the current connection and establish a new one
   348  			conn.Close()
   349  			errTimer.Reset(0)
   350  		}
   351  	}
   352  }
   353  
   354  // readLoop loops as long as the connection is alive and retrieves data packets
   355  // from the network socket. If any of them match an active request, it forwards
   356  // it, if they themselves are requests it initiates a reply, and lastly it drops
   357  // unknown packets.
   358  func (s *Service) readLoop(conn *connWrapper) {
   359  	// If the read loop exits, close the connection
   360  	defer conn.Close()
   361  
   362  	for {
   363  		// Retrieve the next generic network packet and bail out on error
   364  		var blob json.RawMessage
   365  		if err := conn.ReadJSON(&blob); err != nil {
   366  			log.Warn("Failed to retrieve stats server message", "err", err)
   367  			return
   368  		}
   369  		// If the network packet is a system ping, respond to it directly
   370  		var ping string
   371  		if err := json.Unmarshal(blob, &ping); err == nil && strings.HasPrefix(ping, "primus::ping::") {
   372  			if err := conn.WriteJSON(strings.ReplaceAll(ping, "ping", "pong")); err != nil {
   373  				log.Warn("Failed to respond to system ping message", "err", err)
   374  				return
   375  			}
   376  			continue
   377  		}
   378  		// Not a system ping, try to decode an actual state message
   379  		var msg map[string][]interface{}
   380  		if err := json.Unmarshal(blob, &msg); err != nil {
   381  			log.Warn("Failed to decode stats server message", "err", err)
   382  			return
   383  		}
   384  		log.Trace("Received message from stats server", "msg", msg)
   385  		if len(msg["emit"]) == 0 {
   386  			log.Warn("Stats server sent non-broadcast", "msg", msg)
   387  			return
   388  		}
   389  		command, ok := msg["emit"][0].(string)
   390  		if !ok {
   391  			log.Warn("Invalid stats server message type", "type", msg["emit"][0])
   392  			return
   393  		}
   394  		// If the message is a ping reply, deliver (someone must be listening!)
   395  		if len(msg["emit"]) == 2 && command == "node-pong" {
   396  			select {
   397  			case s.pongCh <- struct{}{}:
   398  				// Pong delivered, continue listening
   399  				continue
   400  			default:
   401  				// Ping routine dead, abort
   402  				log.Warn("Stats server pinger seems to have died")
   403  				return
   404  			}
   405  		}
   406  		// If the message is a history request, forward to the event processor
   407  		if len(msg["emit"]) == 2 && command == "history" {
   408  			// Make sure the request is valid and doesn't crash us
   409  			request, ok := msg["emit"][1].(map[string]interface{})
   410  			if !ok {
   411  				log.Warn("Invalid stats history request", "msg", msg["emit"][1])
   412  				select {
   413  				case s.histCh <- nil: // Treat it as an no indexes request
   414  				default:
   415  				}
   416  				continue
   417  			}
   418  			list, ok := request["list"].([]interface{})
   419  			if !ok {
   420  				log.Warn("Invalid stats history block list", "list", request["list"])
   421  				return
   422  			}
   423  			// Convert the block number list to an integer list
   424  			numbers := make([]uint64, len(list))
   425  			for i, num := range list {
   426  				n, ok := num.(float64)
   427  				if !ok {
   428  					log.Warn("Invalid stats history block number", "number", num)
   429  					return
   430  				}
   431  				numbers[i] = uint64(n)
   432  			}
   433  			select {
   434  			case s.histCh <- numbers:
   435  				continue
   436  			default:
   437  			}
   438  		}
   439  		// Report anything else and continue
   440  		log.Info("Unknown stats message", "msg", msg)
   441  	}
   442  }
   443  
   444  // nodeInfo is the collection of meta information about a node that is displayed
   445  // on the monitoring page.
   446  type nodeInfo struct {
   447  	Name     string `json:"name"`
   448  	Node     string `json:"node"`
   449  	Port     int    `json:"port"`
   450  	Network  string `json:"net"`
   451  	Protocol string `json:"protocol"`
   452  	API      string `json:"api"`
   453  	Os       string `json:"os"`
   454  	OsVer    string `json:"os_v"`
   455  	Client   string `json:"client"`
   456  	History  bool   `json:"canUpdateHistory"`
   457  }
   458  
   459  // authMsg is the authentication infos needed to login to a monitoring server.
   460  type authMsg struct {
   461  	ID     string   `json:"id"`
   462  	Info   nodeInfo `json:"info"`
   463  	Secret string   `json:"secret"`
   464  }
   465  
   466  // login tries to authorize the client at the remote server.
   467  func (s *Service) login(conn *connWrapper) error {
   468  	// Construct and send the login authentication
   469  	infos := s.server.NodeInfo()
   470  
   471  	var protocols []string
   472  	for _, proto := range s.server.Protocols {
   473  		protocols = append(protocols, fmt.Sprintf("%s/%d", proto.Name, proto.Version))
   474  	}
   475  	var network string
   476  	if info := infos.Protocols["eth"]; info != nil {
   477  		network = fmt.Sprintf("%d", info.(*ethproto.NodeInfo).Network)
   478  	} else {
   479  		return errors.New("no eth protocol available")
   480  	}
   481  	auth := &authMsg{
   482  		ID: s.node,
   483  		Info: nodeInfo{
   484  			Name:     s.node,
   485  			Node:     infos.Name,
   486  			Port:     infos.Ports.Listener,
   487  			Network:  network,
   488  			Protocol: strings.Join(protocols, ", "),
   489  			API:      "No",
   490  			Os:       runtime.GOOS,
   491  			OsVer:    runtime.GOARCH,
   492  			Client:   "0.1.1",
   493  			History:  true,
   494  		},
   495  		Secret: s.pass,
   496  	}
   497  	login := map[string][]interface{}{
   498  		"emit": {"hello", auth},
   499  	}
   500  	if err := conn.WriteJSON(login); err != nil {
   501  		return err
   502  	}
   503  	// Retrieve the remote ack or connection termination
   504  	var ack map[string][]string
   505  	if err := conn.ReadJSON(&ack); err != nil || len(ack["emit"]) != 1 || ack["emit"][0] != "ready" {
   506  		return errors.New("unauthorized")
   507  	}
   508  	return nil
   509  }
   510  
   511  // report collects all possible data to report and send it to the stats server.
   512  // This should only be used on reconnects or rarely to avoid overloading the
   513  // server. Use the individual methods for reporting subscribed events.
   514  func (s *Service) report(conn *connWrapper) error {
   515  	if err := s.reportLatency(conn); err != nil {
   516  		return err
   517  	}
   518  	if err := s.reportBlock(conn, nil); err != nil {
   519  		return err
   520  	}
   521  	if err := s.reportPending(conn); err != nil {
   522  		return err
   523  	}
   524  	if err := s.reportStats(conn); err != nil {
   525  		return err
   526  	}
   527  	return nil
   528  }
   529  
   530  // reportLatency sends a ping request to the server, measures the RTT time and
   531  // finally sends a latency update.
   532  func (s *Service) reportLatency(conn *connWrapper) error {
   533  	// Send the current time to the ethstats server
   534  	start := time.Now()
   535  
   536  	ping := map[string][]interface{}{
   537  		"emit": {"node-ping", map[string]string{
   538  			"id":         s.node,
   539  			"clientTime": start.String(),
   540  		}},
   541  	}
   542  	if err := conn.WriteJSON(ping); err != nil {
   543  		return err
   544  	}
   545  	// Wait for the pong request to arrive back
   546  	timer := time.NewTimer(5 * time.Second)
   547  	defer timer.Stop()
   548  
   549  	select {
   550  	case <-s.pongCh:
   551  		// Pong delivered, report the latency
   552  	case <-timer.C:
   553  		// Ping timeout, abort
   554  		return errors.New("ping timed out")
   555  	}
   556  	latency := strconv.Itoa(int((time.Since(start) / time.Duration(2)).Nanoseconds() / 1000000))
   557  
   558  	// Send back the measured latency
   559  	log.Trace("Sending measured latency to ethstats", "latency", latency)
   560  
   561  	stats := map[string][]interface{}{
   562  		"emit": {"latency", map[string]string{
   563  			"id":      s.node,
   564  			"latency": latency,
   565  		}},
   566  	}
   567  	return conn.WriteJSON(stats)
   568  }
   569  
   570  // blockStats is the information to report about individual blocks.
   571  type blockStats struct {
   572  	Number     *big.Int       `json:"number"`
   573  	Hash       common.Hash    `json:"hash"`
   574  	ParentHash common.Hash    `json:"parentHash"`
   575  	Timestamp  *big.Int       `json:"timestamp"`
   576  	Miner      common.Address `json:"miner"`
   577  	GasUsed    uint64         `json:"gasUsed"`
   578  	GasLimit   uint64         `json:"gasLimit"`
   579  	Diff       string         `json:"difficulty"`
   580  	TotalDiff  string         `json:"totalDifficulty"`
   581  	Txs        []txStats      `json:"transactions"`
   582  	TxHash     common.Hash    `json:"transactionsRoot"`
   583  	Root       common.Hash    `json:"stateRoot"`
   584  	Uncles     uncleStats     `json:"uncles"`
   585  }
   586  
   587  // txStats is the information to report about individual transactions.
   588  type txStats struct {
   589  	Hash common.Hash `json:"hash"`
   590  }
   591  
   592  // uncleStats is a custom wrapper around an uncle array to force serializing
   593  // empty arrays instead of returning null for them.
   594  type uncleStats []*types.Header
   595  
   596  func (s uncleStats) MarshalJSON() ([]byte, error) {
   597  	if uncles := ([]*types.Header)(s); len(uncles) > 0 {
   598  		return json.Marshal(uncles)
   599  	}
   600  	return []byte("[]"), nil
   601  }
   602  
   603  // reportBlock retrieves the current chain head and reports it to the stats server.
   604  func (s *Service) reportBlock(conn *connWrapper, header *types.Header) error {
   605  	// Gather the block details from the header or block chain
   606  	details := s.assembleBlockStats(header)
   607  
   608  	// Short circuit if the block detail is not available.
   609  	if details == nil {
   610  		return nil
   611  	}
   612  	// Assemble the block report and send it to the server
   613  	log.Trace("Sending new block to ethstats", "number", details.Number, "hash", details.Hash)
   614  
   615  	stats := map[string]interface{}{
   616  		"id":    s.node,
   617  		"block": details,
   618  	}
   619  	report := map[string][]interface{}{
   620  		"emit": {"block", stats},
   621  	}
   622  	return conn.WriteJSON(report)
   623  }
   624  
   625  // assembleBlockStats retrieves any required metadata to report a single block
   626  // and assembles the block stats. If block is nil, the current head is processed.
   627  func (s *Service) assembleBlockStats(header *types.Header) *blockStats {
   628  	// Gather the block infos from the local blockchain
   629  	var (
   630  		txs    []txStats
   631  		uncles []*types.Header
   632  	)
   633  
   634  	// check if backend is a full node
   635  	fullBackend, ok := s.backend.(fullNodeBackend)
   636  	if ok {
   637  		// Retrieve current chain head if no block is given.
   638  		if header == nil {
   639  			header = fullBackend.CurrentBlock()
   640  		}
   641  		block, _ := fullBackend.BlockByNumber(context.Background(), rpc.BlockNumber(header.Number.Uint64()))
   642  		if block == nil {
   643  			return nil
   644  		}
   645  		txs = make([]txStats, len(block.Transactions()))
   646  		for i, tx := range block.Transactions() {
   647  			txs[i].Hash = tx.Hash()
   648  		}
   649  		uncles = block.Uncles()
   650  	} else {
   651  		// Light nodes would need on-demand lookups for transactions/uncles, skip
   652  		if header == nil {
   653  			header = s.backend.CurrentHeader()
   654  		}
   655  		txs = []txStats{}
   656  	}
   657  	// Assemble and return the block stats
   658  	author, _ := s.engine.Author(header)
   659  
   660  	return &blockStats{
   661  		Number:     header.Number,
   662  		Hash:       header.Hash(),
   663  		ParentHash: header.ParentHash,
   664  		Timestamp:  new(big.Int).SetUint64(header.Time),
   665  		Miner:      author,
   666  		GasUsed:    header.GasUsed,
   667  		GasLimit:   header.GasLimit,
   668  		Diff:       header.Difficulty.String(),
   669  		TotalDiff:  "0", // unknown post-merge with pruned chain tail
   670  		Txs:        txs,
   671  		TxHash:     header.TxHash,
   672  		Root:       header.Root,
   673  		Uncles:     uncles,
   674  	}
   675  }
   676  
   677  // reportHistory retrieves the most recent batch of blocks and reports it to the
   678  // stats server.
   679  func (s *Service) reportHistory(conn *connWrapper, list []uint64) error {
   680  	// Figure out the indexes that need reporting
   681  	indexes := make([]uint64, 0, historyUpdateRange)
   682  	if len(list) > 0 {
   683  		// Specific indexes requested, send them back in particular
   684  		indexes = append(indexes, list...)
   685  	} else {
   686  		// No indexes requested, send back the top ones
   687  		head := s.backend.CurrentHeader().Number.Int64()
   688  		start := head - historyUpdateRange + 1
   689  		if start < 0 {
   690  			start = 0
   691  		}
   692  		for i := uint64(start); i <= uint64(head); i++ {
   693  			indexes = append(indexes, i)
   694  		}
   695  	}
   696  	// Gather the batch of blocks to report
   697  	history := make([]*blockStats, len(indexes))
   698  	for i, number := range indexes {
   699  		// Retrieve the next block if it's known to us
   700  		header, _ := s.backend.HeaderByNumber(context.Background(), rpc.BlockNumber(number))
   701  		if header != nil {
   702  			history[len(history)-1-i] = s.assembleBlockStats(header)
   703  			continue
   704  		}
   705  		// Ran out of blocks, cut the report short and send
   706  		history = history[len(history)-i:]
   707  		break
   708  	}
   709  	// Assemble the history report and send it to the server
   710  	if len(history) > 0 {
   711  		log.Trace("Sending historical blocks to ethstats", "first", history[0].Number, "last", history[len(history)-1].Number)
   712  	} else {
   713  		log.Trace("No history to send to stats server")
   714  	}
   715  	stats := map[string]interface{}{
   716  		"id":      s.node,
   717  		"history": history,
   718  	}
   719  	report := map[string][]interface{}{
   720  		"emit": {"history", stats},
   721  	}
   722  	return conn.WriteJSON(report)
   723  }
   724  
   725  // pendStats is the information to report about pending transactions.
   726  type pendStats struct {
   727  	Pending int `json:"pending"`
   728  }
   729  
   730  // reportPending retrieves the current number of pending transactions and reports
   731  // it to the stats server.
   732  func (s *Service) reportPending(conn *connWrapper) error {
   733  	// Retrieve the pending count from the local blockchain
   734  	pending, _ := s.backend.Stats()
   735  	// Assemble the transaction stats and send it to the server
   736  	log.Trace("Sending pending transactions to ethstats", "count", pending)
   737  
   738  	stats := map[string]interface{}{
   739  		"id": s.node,
   740  		"stats": &pendStats{
   741  			Pending: pending,
   742  		},
   743  	}
   744  	report := map[string][]interface{}{
   745  		"emit": {"pending", stats},
   746  	}
   747  	return conn.WriteJSON(report)
   748  }
   749  
   750  // nodeStats is the information to report about the local node.
   751  type nodeStats struct {
   752  	Active   bool `json:"active"`
   753  	Syncing  bool `json:"syncing"`
   754  	Peers    int  `json:"peers"`
   755  	GasPrice int  `json:"gasPrice"`
   756  	Uptime   int  `json:"uptime"`
   757  }
   758  
   759  // reportStats retrieves various stats about the node at the networking layer
   760  // and reports it to the stats server.
   761  func (s *Service) reportStats(conn *connWrapper) error {
   762  	// Gather the syncing infos from the local miner instance
   763  	var (
   764  		syncing  bool
   765  		gasprice int
   766  	)
   767  	// check if backend is a full node
   768  	if fullBackend, ok := s.backend.(fullNodeBackend); ok {
   769  		sync := fullBackend.SyncProgress(context.Background())
   770  		syncing = !sync.Done()
   771  
   772  		price, _ := fullBackend.SuggestGasTipCap(context.Background())
   773  		gasprice = int(price.Uint64())
   774  		if basefee := fullBackend.CurrentHeader().BaseFee; basefee != nil {
   775  			gasprice += int(basefee.Uint64())
   776  		}
   777  	} else {
   778  		sync := s.backend.SyncProgress(context.Background())
   779  		syncing = !sync.Done()
   780  	}
   781  	// Assemble the node stats and send it to the server
   782  	log.Trace("Sending node details to ethstats")
   783  
   784  	stats := map[string]interface{}{
   785  		"id": s.node,
   786  		"stats": &nodeStats{
   787  			Active:   true,
   788  			Peers:    s.server.PeerCount(),
   789  			GasPrice: gasprice,
   790  			Syncing:  syncing,
   791  			Uptime:   100,
   792  		},
   793  	}
   794  	report := map[string][]interface{}{
   795  		"emit": {"stats", stats},
   796  	}
   797  	return conn.WriteJSON(report)
   798  }