ethstats.go 20 KB

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