ethstats.go 21 KB

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