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