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