ethstats.go 24 KB

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