ethstats.go 21 KB

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