ethstats.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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/http"
  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. "github.com/gorilla/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 subscriptions 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. // Resolve the URL, defaulting to TLS, but falling back to none too
  174. path := fmt.Sprintf("%s/api", s.host)
  175. urls := []string{path}
  176. // url.Parse and url.IsAbs is unsuitable (https://github.com/golang/go/issues/19779)
  177. if !strings.Contains(path, "://") {
  178. urls = []string{"wss://" + path, "ws://" + path}
  179. }
  180. // Loop reporting until termination
  181. for {
  182. // Establish a websocket connection to the server on any supported URL
  183. var (
  184. conn *websocket.Conn
  185. err error
  186. )
  187. dialer := websocket.Dialer{HandshakeTimeout: 5 * time.Second}
  188. header := make(http.Header)
  189. header.Set("origin", "http://localhost")
  190. for _, url := range urls {
  191. conn, _, err = dialer.Dial(url, header)
  192. if 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. fullReport.Stop()
  221. // Make sure the connection is closed
  222. conn.Close()
  223. return
  224. case <-fullReport.C:
  225. if err = s.report(conn); err != nil {
  226. log.Warn("Full stats report failed", "err", err)
  227. }
  228. case list := <-s.histCh:
  229. if err = s.reportHistory(conn, list); err != nil {
  230. log.Warn("Requested history report failed", "err", err)
  231. }
  232. case head := <-headCh:
  233. if err = s.reportBlock(conn, head); err != nil {
  234. log.Warn("Block stats report failed", "err", err)
  235. }
  236. if err = s.reportPending(conn); err != nil {
  237. log.Warn("Post-block transaction stats report failed", "err", err)
  238. }
  239. case <-txCh:
  240. if err = s.reportPending(conn); err != nil {
  241. log.Warn("Transaction stats report failed", "err", err)
  242. }
  243. }
  244. }
  245. fullReport.Stop()
  246. // Make sure the connection is closed
  247. conn.Close()
  248. }
  249. }
  250. // readLoop loops as long as the connection is alive and retrieves data packets
  251. // from the network socket. If any of them match an active request, it forwards
  252. // it, if they themselves are requests it initiates a reply, and lastly it drops
  253. // unknown packets.
  254. func (s *Service) readLoop(conn *websocket.Conn) {
  255. // If the read loop exists, close the connection
  256. defer conn.Close()
  257. for {
  258. // Retrieve the next generic network packet and bail out on error
  259. var msg map[string][]interface{}
  260. if err := conn.ReadJSON(&msg); err != nil {
  261. log.Warn("Failed to decode stats server message", "err", err)
  262. return
  263. }
  264. log.Trace("Received message from stats server", "msg", msg)
  265. if len(msg["emit"]) == 0 {
  266. log.Warn("Stats server sent non-broadcast", "msg", msg)
  267. return
  268. }
  269. command, ok := msg["emit"][0].(string)
  270. if !ok {
  271. log.Warn("Invalid stats server message type", "type", msg["emit"][0])
  272. return
  273. }
  274. // If the message is a ping reply, deliver (someone must be listening!)
  275. if len(msg["emit"]) == 2 && command == "node-pong" {
  276. select {
  277. case s.pongCh <- struct{}{}:
  278. // Pong delivered, continue listening
  279. continue
  280. default:
  281. // Ping routine dead, abort
  282. log.Warn("Stats server pinger seems to have died")
  283. return
  284. }
  285. }
  286. // If the message is a history request, forward to the event processor
  287. if len(msg["emit"]) == 2 && command == "history" {
  288. // Make sure the request is valid and doesn't crash us
  289. request, ok := msg["emit"][1].(map[string]interface{})
  290. if !ok {
  291. log.Warn("Invalid stats history request", "msg", msg["emit"][1])
  292. select {
  293. case s.histCh <- nil: // Treat it as an no indexes request
  294. default:
  295. }
  296. continue
  297. }
  298. list, ok := request["list"].([]interface{})
  299. if !ok {
  300. log.Warn("Invalid stats history block list", "list", request["list"])
  301. return
  302. }
  303. // Convert the block number list to an integer list
  304. numbers := make([]uint64, len(list))
  305. for i, num := range list {
  306. n, ok := num.(float64)
  307. if !ok {
  308. log.Warn("Invalid stats history block number", "number", num)
  309. return
  310. }
  311. numbers[i] = uint64(n)
  312. }
  313. select {
  314. case s.histCh <- numbers:
  315. continue
  316. default:
  317. }
  318. }
  319. // Report anything else and continue
  320. log.Info("Unknown stats message", "msg", msg)
  321. }
  322. }
  323. // nodeInfo is the collection of meta information about a node that is displayed
  324. // on the monitoring page.
  325. type nodeInfo struct {
  326. Name string `json:"name"`
  327. Node string `json:"node"`
  328. Port int `json:"port"`
  329. Network string `json:"net"`
  330. Protocol string `json:"protocol"`
  331. API string `json:"api"`
  332. Os string `json:"os"`
  333. OsVer string `json:"os_v"`
  334. Client string `json:"client"`
  335. History bool `json:"canUpdateHistory"`
  336. }
  337. // authMsg is the authentication infos needed to login to a monitoring server.
  338. type authMsg struct {
  339. ID string `json:"id"`
  340. Info nodeInfo `json:"info"`
  341. Secret string `json:"secret"`
  342. }
  343. // login tries to authorize the client at the remote server.
  344. func (s *Service) login(conn *websocket.Conn) error {
  345. // Construct and send the login authentication
  346. infos := s.server.NodeInfo()
  347. var network, protocol string
  348. if info := infos.Protocols["eth"]; info != nil {
  349. network = fmt.Sprintf("%d", info.(*eth.NodeInfo).Network)
  350. protocol = fmt.Sprintf("eth/%d", eth.ProtocolVersions[0])
  351. } else {
  352. network = fmt.Sprintf("%d", infos.Protocols["les"].(*les.NodeInfo).Network)
  353. protocol = fmt.Sprintf("les/%d", les.ClientProtocolVersions[0])
  354. }
  355. auth := &authMsg{
  356. ID: s.node,
  357. Info: nodeInfo{
  358. Name: s.node,
  359. Node: infos.Name,
  360. Port: infos.Ports.Listener,
  361. Network: network,
  362. Protocol: protocol,
  363. API: "No",
  364. Os: runtime.GOOS,
  365. OsVer: runtime.GOARCH,
  366. Client: "0.1.1",
  367. History: true,
  368. },
  369. Secret: s.pass,
  370. }
  371. login := map[string][]interface{}{
  372. "emit": {"hello", auth},
  373. }
  374. if err := conn.WriteJSON(login); err != nil {
  375. return err
  376. }
  377. // Retrieve the remote ack or connection termination
  378. var ack map[string][]string
  379. if err := conn.ReadJSON(&ack); err != nil || len(ack["emit"]) != 1 || ack["emit"][0] != "ready" {
  380. return errors.New("unauthorized")
  381. }
  382. return nil
  383. }
  384. // report collects all possible data to report and send it to the stats server.
  385. // This should only be used on reconnects or rarely to avoid overloading the
  386. // server. Use the individual methods for reporting subscribed events.
  387. func (s *Service) report(conn *websocket.Conn) error {
  388. if err := s.reportLatency(conn); err != nil {
  389. return err
  390. }
  391. if err := s.reportBlock(conn, nil); err != nil {
  392. return err
  393. }
  394. if err := s.reportPending(conn); err != nil {
  395. return err
  396. }
  397. if err := s.reportStats(conn); err != nil {
  398. return err
  399. }
  400. return nil
  401. }
  402. // reportLatency sends a ping request to the server, measures the RTT time and
  403. // finally sends a latency update.
  404. func (s *Service) reportLatency(conn *websocket.Conn) error {
  405. // Send the current time to the ethstats server
  406. start := time.Now()
  407. ping := map[string][]interface{}{
  408. "emit": {"node-ping", map[string]string{
  409. "id": s.node,
  410. "clientTime": start.String(),
  411. }},
  412. }
  413. if err := conn.WriteJSON(ping); err != nil {
  414. return err
  415. }
  416. // Wait for the pong request to arrive back
  417. select {
  418. case <-s.pongCh:
  419. // Pong delivered, report the latency
  420. case <-time.After(5 * time.Second):
  421. // Ping timeout, abort
  422. return errors.New("ping timed out")
  423. }
  424. latency := strconv.Itoa(int((time.Since(start) / time.Duration(2)).Nanoseconds() / 1000000))
  425. // Send back the measured latency
  426. log.Trace("Sending measured latency to ethstats", "latency", latency)
  427. stats := map[string][]interface{}{
  428. "emit": {"latency", map[string]string{
  429. "id": s.node,
  430. "latency": latency,
  431. }},
  432. }
  433. return conn.WriteJSON(stats)
  434. }
  435. // blockStats is the information to report about individual blocks.
  436. type blockStats struct {
  437. Number *big.Int `json:"number"`
  438. Hash common.Hash `json:"hash"`
  439. ParentHash common.Hash `json:"parentHash"`
  440. Timestamp *big.Int `json:"timestamp"`
  441. Miner common.Address `json:"miner"`
  442. GasUsed uint64 `json:"gasUsed"`
  443. GasLimit uint64 `json:"gasLimit"`
  444. Diff string `json:"difficulty"`
  445. TotalDiff string `json:"totalDifficulty"`
  446. Txs []txStats `json:"transactions"`
  447. TxHash common.Hash `json:"transactionsRoot"`
  448. Root common.Hash `json:"stateRoot"`
  449. Uncles uncleStats `json:"uncles"`
  450. }
  451. // txStats is the information to report about individual transactions.
  452. type txStats struct {
  453. Hash common.Hash `json:"hash"`
  454. }
  455. // uncleStats is a custom wrapper around an uncle array to force serializing
  456. // empty arrays instead of returning null for them.
  457. type uncleStats []*types.Header
  458. func (s uncleStats) MarshalJSON() ([]byte, error) {
  459. if uncles := ([]*types.Header)(s); len(uncles) > 0 {
  460. return json.Marshal(uncles)
  461. }
  462. return []byte("[]"), nil
  463. }
  464. // reportBlock retrieves the current chain head and reports it to the stats server.
  465. func (s *Service) reportBlock(conn *websocket.Conn, block *types.Block) error {
  466. // Gather the block details from the header or block chain
  467. details := s.assembleBlockStats(block)
  468. // Assemble the block report and send it to the server
  469. log.Trace("Sending new block to ethstats", "number", details.Number, "hash", details.Hash)
  470. stats := map[string]interface{}{
  471. "id": s.node,
  472. "block": details,
  473. }
  474. report := map[string][]interface{}{
  475. "emit": {"block", stats},
  476. }
  477. return conn.WriteJSON(report)
  478. }
  479. // assembleBlockStats retrieves any required metadata to report a single block
  480. // and assembles the block stats. If block is nil, the current head is processed.
  481. func (s *Service) assembleBlockStats(block *types.Block) *blockStats {
  482. // Gather the block infos from the local blockchain
  483. var (
  484. header *types.Header
  485. td *big.Int
  486. txs []txStats
  487. uncles []*types.Header
  488. )
  489. if s.eth != nil {
  490. // Full nodes have all needed information available
  491. if block == nil {
  492. block = s.eth.BlockChain().CurrentBlock()
  493. }
  494. header = block.Header()
  495. td = s.eth.BlockChain().GetTd(header.Hash(), header.Number.Uint64())
  496. txs = make([]txStats, len(block.Transactions()))
  497. for i, tx := range block.Transactions() {
  498. txs[i].Hash = tx.Hash()
  499. }
  500. uncles = block.Uncles()
  501. } else {
  502. // Light nodes would need on-demand lookups for transactions/uncles, skip
  503. if block != nil {
  504. header = block.Header()
  505. } else {
  506. header = s.les.BlockChain().CurrentHeader()
  507. }
  508. td = s.les.BlockChain().GetTd(header.Hash(), header.Number.Uint64())
  509. txs = []txStats{}
  510. }
  511. // Assemble and return the block stats
  512. author, _ := s.engine.Author(header)
  513. return &blockStats{
  514. Number: header.Number,
  515. Hash: header.Hash(),
  516. ParentHash: header.ParentHash,
  517. Timestamp: new(big.Int).SetUint64(header.Time),
  518. Miner: author,
  519. GasUsed: header.GasUsed,
  520. GasLimit: header.GasLimit,
  521. Diff: header.Difficulty.String(),
  522. TotalDiff: td.String(),
  523. Txs: txs,
  524. TxHash: header.TxHash,
  525. Root: header.Root,
  526. Uncles: uncles,
  527. }
  528. }
  529. // reportHistory retrieves the most recent batch of blocks and reports it to the
  530. // stats server.
  531. func (s *Service) reportHistory(conn *websocket.Conn, list []uint64) error {
  532. // Figure out the indexes that need reporting
  533. indexes := make([]uint64, 0, historyUpdateRange)
  534. if len(list) > 0 {
  535. // Specific indexes requested, send them back in particular
  536. indexes = append(indexes, list...)
  537. } else {
  538. // No indexes requested, send back the top ones
  539. var head int64
  540. if s.eth != nil {
  541. head = s.eth.BlockChain().CurrentHeader().Number.Int64()
  542. } else {
  543. head = s.les.BlockChain().CurrentHeader().Number.Int64()
  544. }
  545. start := head - historyUpdateRange + 1
  546. if start < 0 {
  547. start = 0
  548. }
  549. for i := uint64(start); i <= uint64(head); i++ {
  550. indexes = append(indexes, i)
  551. }
  552. }
  553. // Gather the batch of blocks to report
  554. history := make([]*blockStats, len(indexes))
  555. for i, number := range indexes {
  556. // Retrieve the next block if it's known to us
  557. var block *types.Block
  558. if s.eth != nil {
  559. block = s.eth.BlockChain().GetBlockByNumber(number)
  560. } else {
  561. if header := s.les.BlockChain().GetHeaderByNumber(number); header != nil {
  562. block = types.NewBlockWithHeader(header)
  563. }
  564. }
  565. // If we do have the block, add to the history and continue
  566. if block != nil {
  567. history[len(history)-1-i] = s.assembleBlockStats(block)
  568. continue
  569. }
  570. // Ran out of blocks, cut the report short and send
  571. history = history[len(history)-i:]
  572. break
  573. }
  574. // Assemble the history report and send it to the server
  575. if len(history) > 0 {
  576. log.Trace("Sending historical blocks to ethstats", "first", history[0].Number, "last", history[len(history)-1].Number)
  577. } else {
  578. log.Trace("No history to send to stats server")
  579. }
  580. stats := map[string]interface{}{
  581. "id": s.node,
  582. "history": history,
  583. }
  584. report := map[string][]interface{}{
  585. "emit": {"history", stats},
  586. }
  587. return conn.WriteJSON(report)
  588. }
  589. // pendStats is the information to report about pending transactions.
  590. type pendStats struct {
  591. Pending int `json:"pending"`
  592. }
  593. // reportPending retrieves the current number of pending transactions and reports
  594. // it to the stats server.
  595. func (s *Service) reportPending(conn *websocket.Conn) error {
  596. // Retrieve the pending count from the local blockchain
  597. var pending int
  598. if s.eth != nil {
  599. pending, _ = s.eth.TxPool().Stats()
  600. } else {
  601. pending = s.les.TxPool().Stats()
  602. }
  603. // Assemble the transaction stats and send it to the server
  604. log.Trace("Sending pending transactions to ethstats", "count", pending)
  605. stats := map[string]interface{}{
  606. "id": s.node,
  607. "stats": &pendStats{
  608. Pending: pending,
  609. },
  610. }
  611. report := map[string][]interface{}{
  612. "emit": {"pending", stats},
  613. }
  614. return conn.WriteJSON(report)
  615. }
  616. // nodeStats is the information to report about the local node.
  617. type nodeStats struct {
  618. Active bool `json:"active"`
  619. Syncing bool `json:"syncing"`
  620. Mining bool `json:"mining"`
  621. Hashrate int `json:"hashrate"`
  622. Peers int `json:"peers"`
  623. GasPrice int `json:"gasPrice"`
  624. Uptime int `json:"uptime"`
  625. }
  626. // reportPending retrieves various stats about the node at the networking and
  627. // mining layer and reports it to the stats server.
  628. func (s *Service) reportStats(conn *websocket.Conn) error {
  629. // Gather the syncing and mining infos from the local miner instance
  630. var (
  631. mining bool
  632. hashrate int
  633. syncing bool
  634. gasprice int
  635. )
  636. if s.eth != nil {
  637. mining = s.eth.Miner().Mining()
  638. hashrate = int(s.eth.Miner().HashRate())
  639. sync := s.eth.Downloader().Progress()
  640. syncing = s.eth.BlockChain().CurrentHeader().Number.Uint64() >= sync.HighestBlock
  641. price, _ := s.eth.APIBackend.SuggestPrice(context.Background())
  642. gasprice = int(price.Uint64())
  643. } else {
  644. sync := s.les.Downloader().Progress()
  645. syncing = s.les.BlockChain().CurrentHeader().Number.Uint64() >= sync.HighestBlock
  646. }
  647. // Assemble the node stats and send it to the server
  648. log.Trace("Sending node details to ethstats")
  649. stats := map[string]interface{}{
  650. "id": s.node,
  651. "stats": &nodeStats{
  652. Active: true,
  653. Mining: mining,
  654. Hashrate: hashrate,
  655. Peers: s.server.PeerCount(),
  656. GasPrice: gasprice,
  657. Syncing: syncing,
  658. Uptime: 100,
  659. },
  660. }
  661. report := map[string][]interface{}{
  662. "emit": {"stats", stats},
  663. }
  664. return conn.WriteJSON(report)
  665. }