github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/ethstats/ethstats.go (about)

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