Skip to content

Commit 81bf9f9

Browse files
authored
downloader: extract findAncestor search functions (#21744)
This is a simple refactoring, extracting common ancestor negotiation logic to named function
1 parent 7da8f75 commit 81bf9f9

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

eth/downloader/downloader.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ var (
9090
errCanceled = errors.New("syncing canceled (requested)")
9191
errNoSyncActive = errors.New("no sync active")
9292
errTooOld = errors.New("peer's protocol version too old")
93+
errNoAncestorFound = errors.New("no common ancestor found")
9394
)
9495

9596
type Downloader struct {
@@ -814,6 +815,26 @@ func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header)
814815
}
815816
}
816817

818+
ancestor, err := d.findAncestorSpanSearch(p, mode, remoteHeight, localHeight, floor)
819+
if err == nil {
820+
return ancestor, nil
821+
}
822+
// The returned error was not nil.
823+
// If the error returned does not reflect that a common ancestor was not found, return it.
824+
// If the error reflects that a common ancestor was not found, continue to binary search,
825+
// where the error value will be reassigned.
826+
if !errors.Is(err, errNoAncestorFound) {
827+
return 0, err
828+
}
829+
830+
ancestor, err = d.findAncestorBinarySearch(p, mode, remoteHeight, floor)
831+
if err != nil {
832+
return 0, err
833+
}
834+
return ancestor, nil
835+
}
836+
837+
func (d *Downloader) findAncestorSpanSearch(p *peerConnection, mode SyncMode, remoteHeight, localHeight uint64, floor int64) (commonAncestor uint64, err error) {
817838
from, count, skip, max := calculateRequestSpan(remoteHeight, localHeight)
818839

819840
p.log.Trace("Span searching for common ancestor", "count", count, "from", from, "skip", skip)
@@ -894,6 +915,12 @@ func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header)
894915
p.log.Debug("Found common ancestor", "number", number, "hash", hash)
895916
return number, nil
896917
}
918+
return 0, errNoAncestorFound
919+
}
920+
921+
func (d *Downloader) findAncestorBinarySearch(p *peerConnection, mode SyncMode, remoteHeight uint64, floor int64) (commonAncestor uint64, err error) {
922+
hash := common.Hash{}
923+
897924
// Ancestor not found, we need to binary search over our chain
898925
start, end := uint64(0), remoteHeight
899926
if floor > 0 {

0 commit comments

Comments
 (0)