@@ -152,50 +152,42 @@ func (s *Service) loop() {
152152 continue
153153 }
154154 // Authenticate the client with the server
155- in := json .NewDecoder (conn )
156- out := json .NewEncoder (conn )
157-
158- if err = s .login (in , out ); err != nil {
155+ if err = s .login (conn ); err != nil {
159156 log .Warn ("Stats login failed" , "err" , err )
160157 conn .Close ()
161158 time .Sleep (10 * time .Second )
162159 continue
163160 }
164- go s .readLoop (conn , in )
161+ go s .readLoop (conn )
165162
166163 // Send the initial stats so our node looks decent from the get go
167- if err = s .report (out ); err != nil {
164+ if err = s .report (conn ); err != nil {
168165 log .Warn ("Initial stats report failed" , "err" , err )
169166 conn .Close ()
170167 continue
171168 }
172- if err = s .reportHistory (out , nil ); err != nil {
173- log .Warn ("Initial history report failed" , "err" , err )
174- conn .Close ()
175- continue
176- }
177169 // Keep sending status updates until the connection breaks
178170 fullReport := time .NewTicker (15 * time .Second )
179171
180172 for err == nil {
181173 select {
182174 case <- fullReport .C :
183- if err = s .report (out ); err != nil {
175+ if err = s .report (conn ); err != nil {
184176 log .Warn ("Full stats report failed" , "err" , err )
185177 }
186178 case list := <- s .histCh :
187- if err = s .reportHistory (out , list ); err != nil {
179+ if err = s .reportHistory (conn , list ); err != nil {
188180 log .Warn ("Requested history report failed" , "err" , err )
189181 }
190182 case head , ok := <- headSub .Chan ():
191183 if ! ok { // node stopped
192184 conn .Close ()
193185 return
194186 }
195- if err = s .reportBlock (out , head .Data .(core.ChainHeadEvent ).Block ); err != nil {
187+ if err = s .reportBlock (conn , head .Data .(core.ChainHeadEvent ).Block ); err != nil {
196188 log .Warn ("Block stats report failed" , "err" , err )
197189 }
198- if err = s .reportPending (out ); err != nil {
190+ if err = s .reportPending (conn ); err != nil {
199191 log .Warn ("Post-block transaction stats report failed" , "err" , err )
200192 }
201193 case _ , ok := <- txSub .Chan ():
@@ -211,7 +203,7 @@ func (s *Service) loop() {
211203 exhausted = true
212204 }
213205 }
214- if err = s .reportPending (out ); err != nil {
206+ if err = s .reportPending (conn ); err != nil {
215207 log .Warn ("Transaction stats report failed" , "err" , err )
216208 }
217209 }
@@ -225,17 +217,18 @@ func (s *Service) loop() {
225217// from the network socket. If any of them match an active request, it forwards
226218// it, if they themselves are requests it initiates a reply, and lastly it drops
227219// unknown packets.
228- func (s * Service ) readLoop (conn * websocket.Conn , in * json. Decoder ) {
220+ func (s * Service ) readLoop (conn * websocket.Conn ) {
229221 // If the read loop exists, close the connection
230222 defer conn .Close ()
231223
232224 for {
233225 // Retrieve the next generic network packet and bail out on error
234226 var msg map [string ][]interface {}
235- if err := in . Decode ( & msg ); err != nil {
227+ if err := websocket . JSON . Receive ( conn , & msg ); err != nil {
236228 log .Warn ("Failed to decode stats server message" , "err" , err )
237229 return
238230 }
231+ log .Trace ("Received message from stats server" , "msg" , msg )
239232 if len (msg ["emit" ]) == 0 {
240233 log .Warn ("Stats server sent non-broadcast" , "msg" , msg )
241234 return
@@ -263,6 +256,7 @@ func (s *Service) readLoop(conn *websocket.Conn, in *json.Decoder) {
263256 request , ok := msg ["emit" ][1 ].(map [string ]interface {})
264257 if ! ok {
265258 log .Warn ("Invalid stats history request" , "msg" , msg ["emit" ][1 ])
259+ s .histCh <- nil
266260 continue // Ethstats sometime sends invalid history requests, ignore those
267261 }
268262 list , ok := request ["list" ].([]interface {})
@@ -314,7 +308,7 @@ type authMsg struct {
314308}
315309
316310// login tries to authorize the client at the remote server.
317- func (s * Service ) login (in * json. Decoder , out * json. Encoder ) error {
311+ func (s * Service ) login (conn * websocket. Conn ) error {
318312 // Construct and send the login authentication
319313 infos := s .server .NodeInfo ()
320314
@@ -345,12 +339,12 @@ func (s *Service) login(in *json.Decoder, out *json.Encoder) error {
345339 login := map [string ][]interface {}{
346340 "emit" : {"hello" , auth },
347341 }
348- if err := out . Encode ( login ); err != nil {
342+ if err := websocket . JSON . Send ( conn , login ); err != nil {
349343 return err
350344 }
351345 // Retrieve the remote ack or connection termination
352346 var ack map [string ][]string
353- if err := in . Decode ( & ack ); err != nil || len (ack ["emit" ]) != 1 || ack ["emit" ][0 ] != "ready" {
347+ if err := websocket . JSON . Receive ( conn , & ack ); err != nil || len (ack ["emit" ]) != 1 || ack ["emit" ][0 ] != "ready" {
354348 return errors .New ("unauthorized" )
355349 }
356350 return nil
@@ -359,25 +353,25 @@ func (s *Service) login(in *json.Decoder, out *json.Encoder) error {
359353// report collects all possible data to report and send it to the stats server.
360354// This should only be used on reconnects or rarely to avoid overloading the
361355// server. Use the individual methods for reporting subscribed events.
362- func (s * Service ) report (out * json. Encoder ) error {
363- if err := s .reportLatency (out ); err != nil {
356+ func (s * Service ) report (conn * websocket. Conn ) error {
357+ if err := s .reportLatency (conn ); err != nil {
364358 return err
365359 }
366- if err := s .reportBlock (out , nil ); err != nil {
360+ if err := s .reportBlock (conn , nil ); err != nil {
367361 return err
368362 }
369- if err := s .reportPending (out ); err != nil {
363+ if err := s .reportPending (conn ); err != nil {
370364 return err
371365 }
372- if err := s .reportStats (out ); err != nil {
366+ if err := s .reportStats (conn ); err != nil {
373367 return err
374368 }
375369 return nil
376370}
377371
378372// reportLatency sends a ping request to the server, measures the RTT time and
379373// finally sends a latency update.
380- func (s * Service ) reportLatency (out * json. Encoder ) error {
374+ func (s * Service ) reportLatency (conn * websocket. Conn ) error {
381375 // Send the current time to the ethstats server
382376 start := time .Now ()
383377
@@ -387,7 +381,7 @@ func (s *Service) reportLatency(out *json.Encoder) error {
387381 "clientTime" : start .String (),
388382 }},
389383 }
390- if err := out . Encode ( ping ); err != nil {
384+ if err := websocket . JSON . Send ( conn , ping ); err != nil {
391385 return err
392386 }
393387 // Wait for the pong request to arrive back
@@ -398,28 +392,35 @@ func (s *Service) reportLatency(out *json.Encoder) error {
398392 // Ping timeout, abort
399393 return errors .New ("ping timed out" )
400394 }
395+ latency := strconv .Itoa (int ((time .Since (start ) / time .Duration (2 )).Nanoseconds () / 1000000 ))
396+
401397 // Send back the measured latency
402- latency := map [string ][]interface {}{
398+ log .Trace ("Sending measured latency to ethstats" , "latency" , latency )
399+
400+ stats := map [string ][]interface {}{
403401 "emit" : {"latency" , map [string ]string {
404402 "id" : s .node ,
405- "latency" : strconv . Itoa ( int (( time . Since ( start ) / time . Duration ( 2 )). Nanoseconds () / 1000000 )) ,
403+ "latency" : latency ,
406404 }},
407405 }
408- return out . Encode ( latency )
406+ return websocket . JSON . Send ( conn , stats )
409407}
410408
411409// blockStats is the information to report about individual blocks.
412410type blockStats struct {
413- Number * big.Int `json:"number"`
414- Hash common.Hash `json:"hash"`
415- Timestamp * big.Int `json:"timestamp"`
416- Miner common.Address `json:"miner"`
417- GasUsed * big.Int `json:"gasUsed"`
418- GasLimit * big.Int `json:"gasLimit"`
419- Diff string `json:"difficulty"`
420- TotalDiff string `json:"totalDifficulty"`
421- Txs txStats `json:"transactions"`
422- Uncles uncleStats `json:"uncles"`
411+ Number * big.Int `json:"number"`
412+ Hash common.Hash `json:"hash"`
413+ ParentHash common.Hash `json:"parentHash"`
414+ Timestamp * big.Int `json:"timestamp"`
415+ Miner common.Address `json:"miner"`
416+ GasUsed * big.Int `json:"gasUsed"`
417+ GasLimit * big.Int `json:"gasLimit"`
418+ Diff string `json:"difficulty"`
419+ TotalDiff string `json:"totalDifficulty"`
420+ Txs txStats `json:"transactions"`
421+ TxHash common.Hash `json:"transactionsRoot"`
422+ Root common.Hash `json:"stateRoot"`
423+ Uncles uncleStats `json:"uncles"`
423424}
424425
425426// txStats is a custom wrapper around a transaction array to force serializing
@@ -445,16 +446,21 @@ func (s uncleStats) MarshalJSON() ([]byte, error) {
445446}
446447
447448// reportBlock retrieves the current chain head and repors it to the stats server.
448- func (s * Service ) reportBlock (out * json.Encoder , block * types.Block ) error {
449- // Assemble the block stats report and send it to the server
449+ func (s * Service ) reportBlock (conn * websocket.Conn , block * types.Block ) error {
450+ // Gather the block details from the header or block chain
451+ details := s .assembleBlockStats (block )
452+
453+ // Assemble the block report and send it to the server
454+ log .Trace ("Sending new block to ethstats" , "number" , details .Number , "hash" , details .Hash )
455+
450456 stats := map [string ]interface {}{
451457 "id" : s .node ,
452- "block" : s . assembleBlockStats ( block ) ,
458+ "block" : details ,
453459 }
454460 report := map [string ][]interface {}{
455461 "emit" : {"block" , stats },
456462 }
457- return out . Encode ( report )
463+ return websocket . JSON . Send ( conn , report )
458464}
459465
460466// assembleBlockStats retrieves any required metadata to report a single block
@@ -488,61 +494,66 @@ func (s *Service) assembleBlockStats(block *types.Block) *blockStats {
488494 }
489495 // Assemble and return the block stats
490496 return & blockStats {
491- Number : header .Number ,
492- Hash : header .Hash (),
493- Timestamp : header .Time ,
494- Miner : header .Coinbase ,
495- GasUsed : new (big.Int ).Set (header .GasUsed ),
496- GasLimit : new (big.Int ).Set (header .GasLimit ),
497- Diff : header .Difficulty .String (),
498- TotalDiff : td .String (),
499- Txs : txs ,
500- Uncles : uncles ,
497+ Number : header .Number ,
498+ Hash : header .Hash (),
499+ ParentHash : header .ParentHash ,
500+ Timestamp : header .Time ,
501+ Miner : header .Coinbase ,
502+ GasUsed : new (big.Int ).Set (header .GasUsed ),
503+ GasLimit : new (big.Int ).Set (header .GasLimit ),
504+ Diff : header .Difficulty .String (),
505+ TotalDiff : td .String (),
506+ Txs : txs ,
507+ TxHash : header .TxHash ,
508+ Root : header .Root ,
509+ Uncles : uncles ,
501510 }
502511}
503512
504513// reportHistory retrieves the most recent batch of blocks and reports it to the
505514// stats server.
506- func (s * Service ) reportHistory (out * json. Encoder , list []uint64 ) error {
515+ func (s * Service ) reportHistory (conn * websocket. Conn , list []uint64 ) error {
507516 // Figure out the indexes that need reporting
508517 indexes := make ([]uint64 , 0 , historyUpdateRange )
509518 if len (list ) > 0 {
510519 // Specific indexes requested, send them back in particular
511520 indexes = append (indexes , list ... )
512521 } else {
513522 // No indexes requested, send back the top ones
514- var head * types. Header
523+ var head int64
515524 if s .eth != nil {
516- head = s .eth .BlockChain ().CurrentHeader ()
525+ head = s .eth .BlockChain ().CurrentHeader (). Number . Int64 ()
517526 } else {
518- head = s .les .BlockChain ().CurrentHeader ()
527+ head = s .les .BlockChain ().CurrentHeader (). Number . Int64 ()
519528 }
520- start := head . Number . Int64 () - historyUpdateRange
529+ start := head - historyUpdateRange + 1
521530 if start < 0 {
522531 start = 0
523532 }
524- for i := uint64 (start ); i <= head . Number . Uint64 ( ); i ++ {
533+ for i := uint64 (start ); i <= uint64 ( head ); i ++ {
525534 indexes = append (indexes , i )
526535 }
527536 }
528537 // Gather the batch of blocks to report
529538 history := make ([]* blockStats , len (indexes ))
530539 for i , number := range indexes {
531540 if s .eth != nil {
532- history [i ] = s .assembleBlockStats (s .eth .BlockChain ().GetBlockByNumber (number ))
541+ history [len ( history ) - 1 - i ] = s .assembleBlockStats (s .eth .BlockChain ().GetBlockByNumber (number ))
533542 } else {
534- history [i ] = s .assembleBlockStats (types .NewBlockWithHeader (s .les .BlockChain ().GetHeaderByNumber (number )))
543+ history [len ( history ) - 1 - i ] = s .assembleBlockStats (types .NewBlockWithHeader (s .les .BlockChain ().GetHeaderByNumber (number )))
535544 }
536545 }
537546 // Assemble the history report and send it to the server
547+ log .Trace ("Sending historical blocks to ethstats" , "first" , history [0 ].Number , "last" , history [len (history )- 1 ].Number )
548+
538549 stats := map [string ]interface {}{
539550 "id" : s .node ,
540551 "history" : history ,
541552 }
542553 report := map [string ][]interface {}{
543554 "emit" : {"history" , stats },
544555 }
545- return out . Encode ( report )
556+ return websocket . JSON . Send ( conn , report )
546557}
547558
548559// pendStats is the information to report about pending transactions.
@@ -552,7 +563,7 @@ type pendStats struct {
552563
553564// reportPending retrieves the current number of pending transactions and reports
554565// it to the stats server.
555- func (s * Service ) reportPending (out * json. Encoder ) error {
566+ func (s * Service ) reportPending (conn * websocket. Conn ) error {
556567 // Retrieve the pending count from the local blockchain
557568 var pending int
558569 if s .eth != nil {
@@ -561,6 +572,8 @@ func (s *Service) reportPending(out *json.Encoder) error {
561572 pending = s .les .TxPool ().Stats ()
562573 }
563574 // Assemble the transaction stats and send it to the server
575+ log .Trace ("Sending pending transactions to ethstats" , "count" , pending )
576+
564577 stats := map [string ]interface {}{
565578 "id" : s .node ,
566579 "stats" : & pendStats {
@@ -570,10 +583,10 @@ func (s *Service) reportPending(out *json.Encoder) error {
570583 report := map [string ][]interface {}{
571584 "emit" : {"pending" , stats },
572585 }
573- return out . Encode ( report )
586+ return websocket . JSON . Send ( conn , report )
574587}
575588
576- // blockStats is the information to report about the local node.
589+ // nodeStats is the information to report about the local node.
577590type nodeStats struct {
578591 Active bool `json:"active"`
579592 Syncing bool `json:"syncing"`
@@ -586,7 +599,7 @@ type nodeStats struct {
586599
587600// reportPending retrieves various stats about the node at the networking and
588601// mining layer and reports it to the stats server.
589- func (s * Service ) reportStats (out * json. Encoder ) error {
602+ func (s * Service ) reportStats (conn * websocket. Conn ) error {
590603 // Gather the syncing and mining infos from the local miner instance
591604 var (
592605 mining bool
@@ -606,6 +619,9 @@ func (s *Service) reportStats(out *json.Encoder) error {
606619 sync := s .les .Downloader ().Progress ()
607620 syncing = s .les .BlockChain ().CurrentHeader ().Number .Uint64 () >= sync .HighestBlock
608621 }
622+ // Assemble the node stats and send it to the server
623+ log .Trace ("Sending node details to ethstats" )
624+
609625 stats := map [string ]interface {}{
610626 "id" : s .node ,
611627 "stats" : & nodeStats {
@@ -621,5 +637,5 @@ func (s *Service) reportStats(out *json.Encoder) error {
621637 report := map [string ][]interface {}{
622638 "emit" : {"stats" , stats },
623639 }
624- return out . Encode ( report )
640+ return websocket . JSON . Send ( conn , report )
625641}
0 commit comments