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