Fix panic on nil block in ethstats (#1360)

This commit is contained in:
Jerry 2024-10-24 23:11:10 -07:00 committed by GitHub
parent 356e77454c
commit 698f22fd18
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 73 additions and 0 deletions

View file

@ -729,6 +729,10 @@ func (s *Service) assembleBlockStats(block *types.Block) *blockStats {
} }
} }
if block == nil {
return nil
}
header = block.Header() header = block.Header()
td = fullBackend.GetTd(context.Background(), header.Hash()) td = fullBackend.GetTd(context.Background(), header.Hash())

View file

@ -17,8 +17,17 @@
package ethstats package ethstats
import ( import (
"context"
"math/big"
"strconv" "strconv"
"testing" "testing"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/rpc"
) )
func TestParseEthstatsURL(t *testing.T) { func TestParseEthstatsURL(t *testing.T) {
@ -83,3 +92,63 @@ func TestParseEthstatsURL(t *testing.T) {
} }
} }
} }
// MockBackend is a mock implementation of the backend interface
type MockFullNodeBackend struct{}
func (m *MockFullNodeBackend) SubscribeChainHeadEvent(ch chan<- core.ChainHeadEvent) event.Subscription {
return nil
}
func (m *MockFullNodeBackend) SubscribeNewTxsEvent(ch chan<- core.NewTxsEvent) event.Subscription {
return nil
}
func (m *MockFullNodeBackend) CurrentHeader() *types.Header {
return &types.Header{}
}
func (m *MockFullNodeBackend) HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error) {
return nil, nil
}
func (m *MockFullNodeBackend) GetTd(ctx context.Context, hash common.Hash) *big.Int {
return big.NewInt(0)
}
func (m *MockFullNodeBackend) Stats() (pending int, queued int) {
return 0, 0
}
func (m *MockFullNodeBackend) SyncProgress() ethereum.SyncProgress {
return ethereum.SyncProgress{}
}
func (m *MockFullNodeBackend) SubscribeChain2HeadEvent(ch chan<- core.Chain2HeadEvent) event.Subscription {
return nil
}
func (m *MockFullNodeBackend) BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) {
return nil, nil
}
func (m *MockFullNodeBackend) CurrentBlock() *types.Header {
return &types.Header{Number: big.NewInt(1)}
}
func (m *MockFullNodeBackend) SuggestGasTipCap(ctx context.Context) (*big.Int, error) {
return big.NewInt(0), nil
}
func TestAssembleBlockStats_NilBlock(t *testing.T) {
mockBackend := &MockFullNodeBackend{}
service := &Service{
backend: mockBackend,
}
result := service.assembleBlockStats(nil)
if result != nil {
t.Errorf("Expected nil, got %v", result)
}
}