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