From d9d3f17ab733d96c50fc84f18755ad5eb044b762 Mon Sep 17 00:00:00 2001 From: Matheus Degiovani Date: Mon, 13 Nov 2023 08:08:04 -0300 Subject: [PATCH] spv: Validate header chain diff earlier This moves the header chain difficulty validation to an earlier point in time of the initial sync process. This is preferable so that less work is performed in case invalid headers are received. --- spv/sync.go | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/spv/sync.go b/spv/sync.go index 5b06d9b64..813ef8f48 100644 --- a/spv/sync.go +++ b/spv/sync.go @@ -1338,6 +1338,22 @@ func (s *Syncer) getHeaders(ctx context.Context, rp *p2p.RemotePeer) error { } } + // Verify the sidechain that includes the received headers has + // the correct difficulty. + s.sidechainMu.Lock() + fullsc, err := s.sidechains.FullSideChain(nodes) + if err != nil { + s.sidechainMu.Unlock() + return err + } + _, err = s.wallet.ValidateHeaderChainDifficulties(ctx, fullsc, 0) + if err != nil { + s.sidechainMu.Unlock() + rp.Disconnect(err) + return err + } + s.sidechainMu.Unlock() + g, ctx := errgroup.WithContext(ctx) for i := range headers { i := i @@ -1408,12 +1424,6 @@ func (s *Syncer) getHeaders(ctx context.Context, rp *p2p.RemotePeer) error { continue } - _, err = s.wallet.ValidateHeaderChainDifficulties(ctx, bestChain, 0) - if err != nil { - s.sidechainMu.Unlock() - return err - } - prevChain, err := s.wallet.ChainSwitch(ctx, &s.sidechains, bestChain, nil) if err != nil { s.sidechainMu.Unlock()