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