ethstats.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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. //must pass engine protocol name for quorum
  411. p := s.engine.Protocol()
  412. if info := infos.Protocols[p.Name]; info != nil {
  413. network = fmt.Sprintf("%d", info.(*ethproto.NodeInfo).Network)
  414. } else {
  415. network = fmt.Sprintf("%d", infos.Protocols["les"].(*les.NodeInfo).Network)
  416. }
  417. auth := &authMsg{
  418. ID: s.node,
  419. Info: nodeInfo{
  420. Name: s.node,
  421. Node: infos.Name,
  422. Port: infos.Ports.Listener,
  423. Network: network,
  424. Protocol: strings.Join(protocols, ", "),
  425. API: "No",
  426. Os: runtime.GOOS,
  427. OsVer: runtime.GOARCH,
  428. Client: "0.1.1",
  429. History: true,
  430. },
  431. Secret: s.pass,
  432. }
  433. login := map[string][]interface{}{
  434. "emit": {"hello", auth},
  435. }
  436. if err := conn.WriteJSON(login); err != nil {
  437. return err
  438. }
  439. // Retrieve the remote ack or connection termination
  440. var ack map[string][]string
  441. if err := conn.ReadJSON(&ack); err != nil || len(ack["emit"]) != 1 || ack["emit"][0] != "ready" {
  442. return errors.New("unauthorized")
  443. }
  444. return nil
  445. }
  446. // report collects all possible data to report and send it to the stats server.
  447. // This should only be used on reconnects or rarely to avoid overloading the
  448. // server. Use the individual methods for reporting subscribed events.
  449. func (s *Service) report(conn *connWrapper) error {
  450. if err := s.reportLatency(conn); err != nil {
  451. return err
  452. }
  453. if err := s.reportBlock(conn, nil); err != nil {
  454. return err
  455. }
  456. if err := s.reportPending(conn); err != nil {
  457. return err
  458. }
  459. if err := s.reportStats(conn); err != nil {
  460. return err
  461. }
  462. return nil
  463. }
  464. // reportLatency sends a ping request to the server, measures the RTT time and
  465. // finally sends a latency update.
  466. func (s *Service) reportLatency(conn *connWrapper) error {
  467. // Send the current time to the ethstats server
  468. start := time.Now()
  469. ping := map[string][]interface{}{
  470. "emit": {"node-ping", map[string]string{
  471. "id": s.node,
  472. "clientTime": start.String(),
  473. }},
  474. }
  475. if err := conn.WriteJSON(ping); err != nil {
  476. return err
  477. }
  478. // Wait for the pong request to arrive back
  479. select {
  480. case <-s.pongCh:
  481. // Pong delivered, report the latency
  482. case <-time.After(5 * time.Second):
  483. // Ping timeout, abort
  484. return errors.New("ping timed out")
  485. }
  486. latency := strconv.Itoa(int((time.Since(start) / time.Duration(2)).Nanoseconds() / 1000000))
  487. // Send back the measured latency
  488. log.Trace("Sending measured latency to ethstats", "latency", latency)
  489. stats := map[string][]interface{}{
  490. "emit": {"latency", map[string]string{
  491. "id": s.node,
  492. "latency": latency,
  493. }},
  494. }
  495. return conn.WriteJSON(stats)
  496. }
  497. // blockStats is the information to report about individual blocks.
  498. type blockStats struct {
  499. Number *big.Int `json:"number"`
  500. Hash common.Hash `json:"hash"`
  501. ParentHash common.Hash `json:"parentHash"`
  502. Timestamp *big.Int `json:"timestamp"`
  503. Miner common.Address `json:"miner"`
  504. GasUsed uint64 `json:"gasUsed"`
  505. GasLimit uint64 `json:"gasLimit"`
  506. Diff string `json:"difficulty"`
  507. TotalDiff string `json:"totalDifficulty"`
  508. Txs []txStats `json:"transactions"`
  509. TxHash common.Hash `json:"transactionsRoot"`
  510. Root common.Hash `json:"stateRoot"`
  511. Uncles uncleStats `json:"uncles"`
  512. }
  513. // txStats is the information to report about individual transactions.
  514. type txStats struct {
  515. Hash common.Hash `json:"hash"`
  516. }
  517. // uncleStats is a custom wrapper around an uncle array to force serializing
  518. // empty arrays instead of returning null for them.
  519. type uncleStats []*types.Header
  520. func (s uncleStats) MarshalJSON() ([]byte, error) {
  521. if uncles := ([]*types.Header)(s); len(uncles) > 0 {
  522. return json.Marshal(uncles)
  523. }
  524. return []byte("[]"), nil
  525. }
  526. // reportBlock retrieves the current chain head and reports it to the stats server.
  527. func (s *Service) reportBlock(conn *connWrapper, block *types.Block) error {
  528. // Gather the block details from the header or block chain
  529. details := s.assembleBlockStats(block)
  530. // Assemble the block report and send it to the server
  531. log.Trace("Sending new block to ethstats", "number", details.Number, "hash", details.Hash)
  532. stats := map[string]interface{}{
  533. "id": s.node,
  534. "block": details,
  535. }
  536. report := map[string][]interface{}{
  537. "emit": {"block", stats},
  538. }
  539. return conn.WriteJSON(report)
  540. }
  541. // assembleBlockStats retrieves any required metadata to report a single block
  542. // and assembles the block stats. If block is nil, the current head is processed.
  543. func (s *Service) assembleBlockStats(block *types.Block) *blockStats {
  544. // Gather the block infos from the local blockchain
  545. var (
  546. header *types.Header
  547. td *big.Int
  548. txs []txStats
  549. uncles []*types.Header
  550. )
  551. // check if backend is a full node
  552. fullBackend, ok := s.backend.(fullNodeBackend)
  553. if ok {
  554. if block == nil {
  555. block = fullBackend.CurrentBlock()
  556. }
  557. header = block.Header()
  558. td = fullBackend.GetTd(context.Background(), header.Hash())
  559. txs = make([]txStats, len(block.Transactions()))
  560. for i, tx := range block.Transactions() {
  561. txs[i].Hash = tx.Hash()
  562. }
  563. uncles = block.Uncles()
  564. } else {
  565. // Light nodes would need on-demand lookups for transactions/uncles, skip
  566. if block != nil {
  567. header = block.Header()
  568. } else {
  569. header = s.backend.CurrentHeader()
  570. }
  571. td = s.backend.GetTd(context.Background(), header.Hash())
  572. txs = []txStats{}
  573. }
  574. // Assemble and return the block stats
  575. author, _ := s.engine.Author(header)
  576. return &blockStats{
  577. Number: header.Number,
  578. Hash: header.Hash(),
  579. ParentHash: header.ParentHash,
  580. Timestamp: new(big.Int).SetUint64(header.Time),
  581. Miner: author,
  582. GasUsed: header.GasUsed,
  583. GasLimit: header.GasLimit,
  584. Diff: header.Difficulty.String(),
  585. TotalDiff: td.String(),
  586. Txs: txs,
  587. TxHash: header.TxHash,
  588. Root: header.Root,
  589. Uncles: uncles,
  590. }
  591. }
  592. // reportHistory retrieves the most recent batch of blocks and reports it to the
  593. // stats server.
  594. func (s *Service) reportHistory(conn *connWrapper, list []uint64) error {
  595. // Figure out the indexes that need reporting
  596. indexes := make([]uint64, 0, historyUpdateRange)
  597. if len(list) > 0 {
  598. // Specific indexes requested, send them back in particular
  599. indexes = append(indexes, list...)
  600. } else {
  601. // No indexes requested, send back the top ones
  602. head := s.backend.CurrentHeader().Number.Int64()
  603. start := head - historyUpdateRange + 1
  604. if start < 0 {
  605. start = 0
  606. }
  607. for i := uint64(start); i <= uint64(head); i++ {
  608. indexes = append(indexes, i)
  609. }
  610. }
  611. // Gather the batch of blocks to report
  612. history := make([]*blockStats, len(indexes))
  613. for i, number := range indexes {
  614. fullBackend, ok := s.backend.(fullNodeBackend)
  615. // Retrieve the next block if it's known to us
  616. var block *types.Block
  617. if ok {
  618. block, _ = fullBackend.BlockByNumber(context.Background(), rpc.BlockNumber(number)) // TODO ignore error here ?
  619. } else {
  620. if header, _ := s.backend.HeaderByNumber(context.Background(), rpc.BlockNumber(number)); header != nil {
  621. block = types.NewBlockWithHeader(header)
  622. }
  623. }
  624. // If we do have the block, add to the history and continue
  625. if block != nil {
  626. history[len(history)-1-i] = s.assembleBlockStats(block)
  627. continue
  628. }
  629. // Ran out of blocks, cut the report short and send
  630. history = history[len(history)-i:]
  631. break
  632. }
  633. // Assemble the history report and send it to the server
  634. if len(history) > 0 {
  635. log.Trace("Sending historical blocks to ethstats", "first", history[0].Number, "last", history[len(history)-1].Number)
  636. } else {
  637. log.Trace("No history to send to stats server")
  638. }
  639. stats := map[string]interface{}{
  640. "id": s.node,
  641. "history": history,
  642. }
  643. report := map[string][]interface{}{
  644. "emit": {"history", stats},
  645. }
  646. return conn.WriteJSON(report)
  647. }
  648. // pendStats is the information to report about pending transactions.
  649. type pendStats struct {
  650. Pending int `json:"pending"`
  651. }
  652. // reportPending retrieves the current number of pending transactions and reports
  653. // it to the stats server.
  654. func (s *Service) reportPending(conn *connWrapper) error {
  655. // Retrieve the pending count from the local blockchain
  656. pending, _ := s.backend.Stats()
  657. // Assemble the transaction stats and send it to the server
  658. log.Trace("Sending pending transactions to ethstats", "count", pending)
  659. stats := map[string]interface{}{
  660. "id": s.node,
  661. "stats": &pendStats{
  662. Pending: pending,
  663. },
  664. }
  665. report := map[string][]interface{}{
  666. "emit": {"pending", stats},
  667. }
  668. return conn.WriteJSON(report)
  669. }
  670. // nodeStats is the information to report about the local node.
  671. type nodeStats struct {
  672. Active bool `json:"active"`
  673. Syncing bool `json:"syncing"`
  674. Mining bool `json:"mining"`
  675. Hashrate int `json:"hashrate"`
  676. Peers int `json:"peers"`
  677. GasPrice int `json:"gasPrice"`
  678. Uptime int `json:"uptime"`
  679. }
  680. // reportStats retrieves various stats about the node at the networking and
  681. // mining layer and reports it to the stats server.
  682. func (s *Service) reportStats(conn *connWrapper) error {
  683. // Gather the syncing and mining infos from the local miner instance
  684. var (
  685. mining bool
  686. hashrate int
  687. syncing bool
  688. gasprice int
  689. )
  690. // check if backend is a full node
  691. fullBackend, ok := s.backend.(fullNodeBackend)
  692. if ok {
  693. mining = fullBackend.Miner().Mining()
  694. hashrate = int(fullBackend.Miner().Hashrate())
  695. sync := fullBackend.Downloader().Progress()
  696. syncing = fullBackend.CurrentHeader().Number.Uint64() >= sync.HighestBlock
  697. price, _ := fullBackend.SuggestPrice(context.Background())
  698. gasprice = int(price.Uint64())
  699. } else {
  700. sync := s.backend.Downloader().Progress()
  701. syncing = s.backend.CurrentHeader().Number.Uint64() >= sync.HighestBlock
  702. }
  703. // Assemble the node stats and send it to the server
  704. log.Trace("Sending node details to ethstats")
  705. stats := map[string]interface{}{
  706. "id": s.node,
  707. "stats": &nodeStats{
  708. Active: true,
  709. Mining: mining,
  710. Hashrate: hashrate,
  711. Peers: s.server.PeerCount(),
  712. GasPrice: gasprice,
  713. Syncing: syncing,
  714. Uptime: 100,
  715. },
  716. }
  717. report := map[string][]interface{}{
  718. "emit": {"stats", stats},
  719. }
  720. return conn.WriteJSON(report)
  721. }