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