ethstats.go 22 KB

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