Skip to content

ethstats/ethstats.go

Type MOD
Upstream Lines 844
Changed +11 -1

Add GetTd to the backend interface and report total difficulty (with nil-safe fallback)

diff --git a/ethstats/ethstats.go b/ethstats/ethstats.go
index c17e22516..a73013865 100644
--- a/ethstats/ethstats.go
+++ b/ethstats/ethstats.go
@@ -66,6 +66,7 @@ type backend interface {
    SubscribeNewPayloadEvent(ch chan<- core.NewPayloadEvent) event.Subscription
    CurrentHeader() *types.Header
    HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error)
+   GetTd(ctx context.Context, hash common.Hash) *big.Int
    Stats() (pending int, queued int)
    SyncProgress(ctx context.Context) ethereum.SyncProgress
 }
@@ -673,6 +674,7 @@ func (s *Service) reportBlock(conn *connWrapper, header *types.Header) error {
 func (s *Service) assembleBlockStats(header *types.Header) *blockStats {
    // Gather the block infos from the local blockchain
    var (
+       td     *big.Int
        txs    []txStats
        uncles []*types.Header
    )
@@ -688,6 +690,7 @@ func (s *Service) assembleBlockStats(header *types.Header) *blockStats {
        if block == nil {
            return nil
        }
+       td = s.backend.GetTd(context.Background(), header.Hash())
        txs = make([]txStats, len(block.Transactions()))
        for i, tx := range block.Transactions() {
            txs[i].Hash = tx.Hash()
@@ -698,11 +701,18 @@ func (s *Service) assembleBlockStats(header *types.Header) *blockStats {
        if header == nil {
            header = s.backend.CurrentHeader()
        }
+       td = s.backend.GetTd(context.Background(), header.Hash())
        txs = []txStats{}
    }
    // Assemble and return the block stats
    author, _ := s.engine.Author(header)

+   // Handle nil TD gracefully (shouldn't happen but be safe)
+   tdStr := "0"
+   if td != nil {
+       tdStr = td.String()
+   }
+
    return &blockStats{
        Number:     header.Number,
        Hash:       header.Hash(),
@@ -712,7 +722,7 @@ func (s *Service) assembleBlockStats(header *types.Header) *blockStats {
        GasUsed:    header.GasUsed,
        GasLimit:   header.GasLimit,
        Diff:       header.Difficulty.String(),
-       TotalDiff:  "0", // unknown post-merge with pruned chain tail
+       TotalDiff:  tdStr,
        Txs:        txs,
        TxHash:     header.TxHash,
        Root:       header.Root,

← Back to RPC & API