github.1485827954.workers.dev/ethereum/go-ethereum@v1.14.3/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/log" 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 48 const ( 49 // historyUpdateRange is the number of blocks a node should report upon login or 50 // history request. 51 historyUpdateRange = 50 52 53 // txChanSize is the size of channel listening to NewTxsEvent. 54 // The number is referenced from the size of tx pool. 55 txChanSize = 4096 56 // chainHeadChanSize is the size of channel listening to ChainHeadEvent. 57 chainHeadChanSize = 10 58 59 messageSizeLimit = 15 * 1024 * 1024 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 BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) 78 CurrentBlock() *types.Header 79 SuggestGasTipCap(ctx context.Context) (*big.Int, error) 80 } 81 82 // Service implements an Ethereum netstats reporting daemon that pushes local 83 // chain statistics up to a monitoring server. 84 type Service struct { 85 server *p2p.Server // Peer-to-peer server to retrieve networking infos 86 backend backend 87 engine consensus.Engine // Consensus engine to retrieve variadic block fields 88 89 node string // Name of the node to display on the monitoring page 90 pass string // Password to authorize access to the monitoring page 91 host string // Remote address of the monitoring service 92 93 pongCh chan struct{} // Pong notifications are fed into this channel 94 histCh chan []uint64 // History request block numbers are fed into this channel 95 96 headSub event.Subscription 97 txSub event.Subscription 98 } 99 100 // connWrapper is a wrapper to prevent concurrent-write or concurrent-read on the 101 // websocket. 102 // 103 // From Gorilla websocket docs: 104 // 105 // Connections support one concurrent reader and one concurrent writer. Applications are 106 // responsible for ensuring that 107 // - no more than one goroutine calls the write methods 108 // NextWriter, SetWriteDeadline, WriteMessage, WriteJSON, EnableWriteCompression, 109 // SetCompressionLevel concurrently; and 110 // - that no more than one goroutine calls the 111 // read methods NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, 112 // SetPingHandler concurrently. 113 // 114 // The Close and WriteControl methods can be called concurrently with all other methods. 115 type connWrapper struct { 116 conn *websocket.Conn 117 118 rlock sync.Mutex 119 wlock sync.Mutex 120 } 121 122 func newConnectionWrapper(conn *websocket.Conn) *connWrapper { 123 conn.SetReadLimit(messageSizeLimit) 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 return errors.New("no eth protocol available") 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 timer := time.NewTimer(5 * time.Second) 548 defer timer.Stop() 549 550 select { 551 case <-s.pongCh: 552 // Pong delivered, report the latency 553 case <-timer.C: 554 // Ping timeout, abort 555 return errors.New("ping timed out") 556 } 557 latency := strconv.Itoa(int((time.Since(start) / time.Duration(2)).Nanoseconds() / 1000000)) 558 559 // Send back the measured latency 560 log.Trace("Sending measured latency to ethstats", "latency", latency) 561 562 stats := map[string][]interface{}{ 563 "emit": {"latency", map[string]string{ 564 "id": s.node, 565 "latency": latency, 566 }}, 567 } 568 return conn.WriteJSON(stats) 569 } 570 571 // blockStats is the information to report about individual blocks. 572 type blockStats struct { 573 Number *big.Int `json:"number"` 574 Hash common.Hash `json:"hash"` 575 ParentHash common.Hash `json:"parentHash"` 576 Timestamp *big.Int `json:"timestamp"` 577 Miner common.Address `json:"miner"` 578 GasUsed uint64 `json:"gasUsed"` 579 GasLimit uint64 `json:"gasLimit"` 580 Diff string `json:"difficulty"` 581 TotalDiff string `json:"totalDifficulty"` 582 Txs []txStats `json:"transactions"` 583 TxHash common.Hash `json:"transactionsRoot"` 584 Root common.Hash `json:"stateRoot"` 585 Uncles uncleStats `json:"uncles"` 586 } 587 588 // txStats is the information to report about individual transactions. 589 type txStats struct { 590 Hash common.Hash `json:"hash"` 591 } 592 593 // uncleStats is a custom wrapper around an uncle array to force serializing 594 // empty arrays instead of returning null for them. 595 type uncleStats []*types.Header 596 597 func (s uncleStats) MarshalJSON() ([]byte, error) { 598 if uncles := ([]*types.Header)(s); len(uncles) > 0 { 599 return json.Marshal(uncles) 600 } 601 return []byte("[]"), nil 602 } 603 604 // reportBlock retrieves the current chain head and reports it to the stats server. 605 func (s *Service) reportBlock(conn *connWrapper, block *types.Block) error { 606 // Gather the block details from the header or block chain 607 details := s.assembleBlockStats(block) 608 609 // Short circuit if the block detail is not available. 610 if details == nil { 611 return nil 612 } 613 // Assemble the block report and send it to the server 614 log.Trace("Sending new block to ethstats", "number", details.Number, "hash", details.Hash) 615 616 stats := map[string]interface{}{ 617 "id": s.node, 618 "block": details, 619 } 620 report := map[string][]interface{}{ 621 "emit": {"block", stats}, 622 } 623 return conn.WriteJSON(report) 624 } 625 626 // assembleBlockStats retrieves any required metadata to report a single block 627 // and assembles the block stats. If block is nil, the current head is processed. 628 func (s *Service) assembleBlockStats(block *types.Block) *blockStats { 629 // Gather the block infos from the local blockchain 630 var ( 631 header *types.Header 632 td *big.Int 633 txs []txStats 634 uncles []*types.Header 635 ) 636 637 // check if backend is a full node 638 fullBackend, ok := s.backend.(fullNodeBackend) 639 if ok { 640 // Retrieve current chain head if no block is given. 641 if block == nil { 642 head := fullBackend.CurrentBlock() 643 block, _ = fullBackend.BlockByNumber(context.Background(), rpc.BlockNumber(head.Number.Uint64())) 644 } 645 // Short circuit if no block is available. It might happen when 646 // the blockchain is reorging. 647 if block == nil { 648 return nil 649 } 650 header = block.Header() 651 td = fullBackend.GetTd(context.Background(), header.Hash()) 652 653 txs = make([]txStats, len(block.Transactions())) 654 for i, tx := range block.Transactions() { 655 txs[i].Hash = tx.Hash() 656 } 657 uncles = block.Uncles() 658 } else { 659 // Light nodes would need on-demand lookups for transactions/uncles, skip 660 if block != nil { 661 header = block.Header() 662 } else { 663 header = s.backend.CurrentHeader() 664 } 665 td = s.backend.GetTd(context.Background(), header.Hash()) 666 txs = []txStats{} 667 } 668 669 // Assemble and return the block stats 670 author, _ := s.engine.Author(header) 671 672 return &blockStats{ 673 Number: header.Number, 674 Hash: header.Hash(), 675 ParentHash: header.ParentHash, 676 Timestamp: new(big.Int).SetUint64(header.Time), 677 Miner: author, 678 GasUsed: header.GasUsed, 679 GasLimit: header.GasLimit, 680 Diff: header.Difficulty.String(), 681 TotalDiff: td.String(), 682 Txs: txs, 683 TxHash: header.TxHash, 684 Root: header.Root, 685 Uncles: uncles, 686 } 687 } 688 689 // reportHistory retrieves the most recent batch of blocks and reports it to the 690 // stats server. 691 func (s *Service) reportHistory(conn *connWrapper, list []uint64) error { 692 // Figure out the indexes that need reporting 693 indexes := make([]uint64, 0, historyUpdateRange) 694 if len(list) > 0 { 695 // Specific indexes requested, send them back in particular 696 indexes = append(indexes, list...) 697 } else { 698 // No indexes requested, send back the top ones 699 head := s.backend.CurrentHeader().Number.Int64() 700 start := head - historyUpdateRange + 1 701 if start < 0 { 702 start = 0 703 } 704 for i := uint64(start); i <= uint64(head); i++ { 705 indexes = append(indexes, i) 706 } 707 } 708 // Gather the batch of blocks to report 709 history := make([]*blockStats, len(indexes)) 710 for i, number := range indexes { 711 fullBackend, ok := s.backend.(fullNodeBackend) 712 // Retrieve the next block if it's known to us 713 var block *types.Block 714 if ok { 715 block, _ = fullBackend.BlockByNumber(context.Background(), rpc.BlockNumber(number)) // TODO ignore error here ? 716 } else { 717 if header, _ := s.backend.HeaderByNumber(context.Background(), rpc.BlockNumber(number)); header != nil { 718 block = types.NewBlockWithHeader(header) 719 } 720 } 721 // If we do have the block, add to the history and continue 722 if block != nil { 723 history[len(history)-1-i] = s.assembleBlockStats(block) 724 continue 725 } 726 // Ran out of blocks, cut the report short and send 727 history = history[len(history)-i:] 728 break 729 } 730 // Assemble the history report and send it to the server 731 if len(history) > 0 { 732 log.Trace("Sending historical blocks to ethstats", "first", history[0].Number, "last", history[len(history)-1].Number) 733 } else { 734 log.Trace("No history to send to stats server") 735 } 736 stats := map[string]interface{}{ 737 "id": s.node, 738 "history": history, 739 } 740 report := map[string][]interface{}{ 741 "emit": {"history", stats}, 742 } 743 return conn.WriteJSON(report) 744 } 745 746 // pendStats is the information to report about pending transactions. 747 type pendStats struct { 748 Pending int `json:"pending"` 749 } 750 751 // reportPending retrieves the current number of pending transactions and reports 752 // it to the stats server. 753 func (s *Service) reportPending(conn *connWrapper) error { 754 // Retrieve the pending count from the local blockchain 755 pending, _ := s.backend.Stats() 756 // Assemble the transaction stats and send it to the server 757 log.Trace("Sending pending transactions to ethstats", "count", pending) 758 759 stats := map[string]interface{}{ 760 "id": s.node, 761 "stats": &pendStats{ 762 Pending: pending, 763 }, 764 } 765 report := map[string][]interface{}{ 766 "emit": {"pending", stats}, 767 } 768 return conn.WriteJSON(report) 769 } 770 771 // nodeStats is the information to report about the local node. 772 type nodeStats struct { 773 Active bool `json:"active"` 774 Syncing bool `json:"syncing"` 775 Peers int `json:"peers"` 776 GasPrice int `json:"gasPrice"` 777 Uptime int `json:"uptime"` 778 } 779 780 // reportStats retrieves various stats about the node at the networking layer 781 // and reports it to the stats server. 782 func (s *Service) reportStats(conn *connWrapper) error { 783 // Gather the syncing infos from the local miner instance 784 var ( 785 syncing bool 786 gasprice int 787 ) 788 // check if backend is a full node 789 if fullBackend, ok := s.backend.(fullNodeBackend); ok { 790 sync := fullBackend.SyncProgress() 791 syncing = !sync.Done() 792 793 price, _ := fullBackend.SuggestGasTipCap(context.Background()) 794 gasprice = int(price.Uint64()) 795 if basefee := fullBackend.CurrentHeader().BaseFee; basefee != nil { 796 gasprice += int(basefee.Uint64()) 797 } 798 } else { 799 sync := s.backend.SyncProgress() 800 syncing = !sync.Done() 801 } 802 // Assemble the node stats and send it to the server 803 log.Trace("Sending node details to ethstats") 804 805 stats := map[string]interface{}{ 806 "id": s.node, 807 "stats": &nodeStats{ 808 Active: true, 809 Peers: s.server.PeerCount(), 810 GasPrice: gasprice, 811 Syncing: syncing, 812 Uptime: 100, 813 }, 814 } 815 report := map[string][]interface{}{ 816 "emit": {"stats", stats}, 817 } 818 return conn.WriteJSON(report) 819 }