From 20924b3caaad0158930f113fd6d361eb20ff54c5 Mon Sep 17 00:00:00 2001 From: Arkadiusz Osowski Date: Fri, 26 Apr 2024 12:23:48 +0200 Subject: [PATCH] fix(SPV-769): check sql.select results length --- database/sql/headers.go | 15 ++++++++------- service/header_service.go | 4 ++-- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/database/sql/headers.go b/database/sql/headers.go index 0bccab38..4a6d9271 100644 --- a/database/sql/headers.go +++ b/database/sql/headers.go @@ -335,6 +335,10 @@ func (h *HeadersDb) GetTip(ctx context.Context) (*dto.DbBlockHeader, error) { h.log.Error().Msgf("sql error: %v", err) return nil, errors.Wrap(err, "failed to get tip") } + if len(tip) == 0 { + return nil, errors.New("could not find tip") + } + return &tip[0], nil } @@ -342,12 +346,9 @@ func (h *HeadersDb) GetTip(ctx context.Context) (*dto.DbBlockHeader, error) { func (h *HeadersDb) GetAncestorOnHeight(hash string, height int32) (*dto.DbBlockHeader, error) { var bh []*dto.DbBlockHeader if err := h.db.Select(&bh, h.db.Rebind(sqlSelectAncestorOnHeight), hash, int(height), int(height)); err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, errors.New("could not find ancestors for a providen hash") - } return nil, errors.Wrapf(err, "failed to get ancestors using given hash: %s ", hash) } - if bh == nil { + if len(bh) == 0 { return nil, errors.New("could not find ancestors for a providen hash") } return bh[0], nil @@ -366,11 +367,11 @@ func (h *HeadersDb) GetAllTips() ([]*dto.DbBlockHeader, error) { func (h *HeadersDb) GetChainBetweenTwoHashes(low string, high string) ([]*dto.DbBlockHeader, error) { var bh []*dto.DbBlockHeader if err := h.db.Select(&bh, h.db.Rebind(sqlChainBetweenTwoHashes), high, low, low); err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, errors.New("could not find headers in given range") - } return nil, errors.Wrapf(err, "failed to get headers using given range from: %s to: %s", low, high) } + if len(bh) == 0 { + return nil, errors.New("could not find headers in given range") + } return bh, nil } diff --git a/service/header_service.go b/service/header_service.go index 3614b7e2..60f989e6 100644 --- a/service/header_service.go +++ b/service/header_service.go @@ -66,12 +66,12 @@ func (hs *HeaderService) IsCurrent() bool { // Not current if the latest main (best) chain height is before the // latest known good checkpoint (when checkpoints are enabled). checkpoints := hs.checkpoints - checkpoint := &checkpoints[len(checkpoints)-1] + checkpoint := checkpoints[len(checkpoints)-1] tip := hs.GetTip() if tip == nil { return true } - if checkpoint != nil && tip.Height < checkpoint.Height { + if tip.Height < checkpoint.Height { return false }