@@ -138,7 +138,10 @@ type Downloader struct {
138138 receiptWakeCh chan bool // [eth/63] Channel to signal the receipt fetcher of new tasks
139139 headerProcCh chan []* types.Header // [eth/62] Channel to feed the header processor new tasks
140140
141- // for stateFetcher
141+ // State sync
142+ pivotHeader * types.Header // Pivot block header to dynamically push the syncing state root
143+ pivotLock sync.RWMutex // Lock protecting pivot header reads from updates
144+
142145 stateSyncStart chan * stateSync
143146 trackStateReq chan * stateReq
144147 stateCh chan dataPack // [eth/63] Channel receiving inbound node state data
@@ -451,10 +454,17 @@ func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.I
451454 }(time .Now ())
452455
453456 // Look up the sync boundaries: the common ancestor and the target block
454- latest , err := d .fetchHeight (p )
457+ latest , pivot , err := d .fetchHead (p )
455458 if err != nil {
456459 return err
457460 }
461+ if mode == FastSync && pivot == nil {
462+ // If no pivot block was returned, the head is below the min full block
463+ // threshold (i.e. new chian). In that case we won't really fast sync
464+ // anyway, but still need a valid pivot block to avoid some code hitting
465+ // nil panics on an access.
466+ pivot = d .blockchain .CurrentBlock ().Header ()
467+ }
458468 height := latest .Number .Uint64 ()
459469
460470 origin , err := d .findAncestor (p , latest )
@@ -469,22 +479,21 @@ func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.I
469479 d .syncStatsLock .Unlock ()
470480
471481 // Ensure our origin point is below any fast sync pivot point
472- pivot := uint64 (0 )
473482 if mode == FastSync {
474483 if height <= uint64 (fsMinFullBlocks ) {
475484 origin = 0
476485 } else {
477- pivot = height - uint64 ( fsMinFullBlocks )
478- if pivot <= origin {
479- origin = pivot - 1
486+ pivotNumber := pivot . Number . Uint64 ( )
487+ if pivotNumber <= origin {
488+ origin = pivotNumber - 1
480489 }
481490 // Write out the pivot into the database so a rollback beyond it will
482491 // reenable fast sync
483- rawdb .WriteLastPivotNumber (d .stateDB , pivot )
492+ rawdb .WriteLastPivotNumber (d .stateDB , pivotNumber )
484493 }
485494 }
486495 d .committed = 1
487- if mode == FastSync && pivot != 0 {
496+ if mode == FastSync && pivot . Number . Uint64 () != 0 {
488497 d .committed = 0
489498 }
490499 if mode == FastSync {
@@ -530,13 +539,17 @@ func (d *Downloader) syncWithPeer(p *peerConnection, hash common.Hash, td *big.I
530539 d .syncInitHook (origin , height )
531540 }
532541 fetchers := []func () error {
533- func () error { return d .fetchHeaders (p , origin + 1 , pivot ) }, // Headers are always retrieved
534- func () error { return d .fetchBodies (origin + 1 ) }, // Bodies are retrieved during normal and fast sync
535- func () error { return d .fetchReceipts (origin + 1 ) }, // Receipts are retrieved during fast sync
536- func () error { return d .processHeaders (origin + 1 , pivot , td ) },
542+ func () error { return d .fetchHeaders (p , origin + 1 ) }, // Headers are always retrieved
543+ func () error { return d .fetchBodies (origin + 1 ) }, // Bodies are retrieved during normal and fast sync
544+ func () error { return d .fetchReceipts (origin + 1 ) }, // Receipts are retrieved during fast sync
545+ func () error { return d .processHeaders (origin + 1 , td ) },
537546 }
538547 if mode == FastSync {
539- fetchers = append (fetchers , func () error { return d .processFastSyncContent (latest ) })
548+ d .pivotLock .Lock ()
549+ d .pivotHeader = pivot
550+ d .pivotLock .Unlock ()
551+
552+ fetchers = append (fetchers , func () error { return d .processFastSyncContent () })
540553 } else if mode == FullSync {
541554 fetchers = append (fetchers , d .processFullSyncContent )
542555 }
@@ -617,46 +630,63 @@ func (d *Downloader) Terminate() {
617630 d .Cancel ()
618631}
619632
620- // fetchHeight retrieves the head header of the remote peer to aid in estimating
621- // the total time a pending synchronisation would take.
622- func (d * Downloader ) fetchHeight (p * peerConnection ) (* types.Header , error ) {
623- p .log .Debug ("Retrieving remote chain height" )
633+ // fetchHead retrieves the head header and prior pivot block (if available) from
634+ // a remote peer.
635+ func (d * Downloader ) fetchHead (p * peerConnection ) (head * types.Header , pivot * types.Header , err error ) {
636+ p .log .Debug ("Retrieving remote chain head" )
637+ mode := d .getMode ()
624638
625639 // Request the advertised remote head block and wait for the response
626- head , _ := p .peer .Head ()
627- go p .peer .RequestHeadersByHash (head , 1 , 0 , false )
640+ latest , _ := p .peer .Head ()
641+ fetch := 1
642+ if mode == FastSync {
643+ fetch = 2 // head + pivot headers
644+ }
645+ go p .peer .RequestHeadersByHash (latest , fetch , fsMinFullBlocks - 1 , true )
628646
629647 ttl := d .requestTTL ()
630648 timeout := time .After (ttl )
631- mode := d .getMode ()
632649 for {
633650 select {
634651 case <- d .cancelCh :
635- return nil , errCanceled
652+ return nil , nil , errCanceled
636653
637654 case packet := <- d .headerCh :
638655 // Discard anything not from the origin peer
639656 if packet .PeerId () != p .id {
640657 log .Debug ("Received headers from incorrect peer" , "peer" , packet .PeerId ())
641658 break
642659 }
643- // Make sure the peer actually gave something valid
660+ // Make sure the peer gave us at least one and at most the requested headers
644661 headers := packet .(* headerPack ).headers
645- if len (headers ) != 1 {
646- p .log .Warn ("Multiple headers for single request" , "headers" , len (headers ))
647- return nil , fmt .Errorf ("%w: multiple headers (%d) for single request" , errBadPeer , len (headers ))
662+ if len (headers ) == 0 || len (headers ) > fetch {
663+ return nil , nil , fmt .Errorf ("%w: returned headers %d != requested %d" , errBadPeer , len (headers ), fetch )
648664 }
665+ // The first header needs to be the head, validate against the checkpoint
666+ // and request. If only 1 header was returned, make sure there's no pivot
667+ // or there was not one requested.
649668 head := headers [0 ]
650669 if (mode == FastSync || mode == LightSync ) && head .Number .Uint64 () < d .checkpoint {
651- p .log .Warn ("Remote head below checkpoint" , "number" , head .Number , "hash" , head .Hash ())
652- return nil , errUnsyncedPeer
670+ return nil , nil , fmt .Errorf ("%w: remote head %d below checkpoint %d" , errUnsyncedPeer , head .Number , d .checkpoint )
671+ }
672+ if len (headers ) == 1 {
673+ if mode == FastSync && head .Number .Uint64 () > uint64 (fsMinFullBlocks ) {
674+ return nil , nil , fmt .Errorf ("%w: no pivot included along head header" , errBadPeer )
675+ }
676+ p .log .Debug ("Remote head identified, no pivot" , "number" , head .Number , "hash" , head .Hash ())
677+ return head , nil , nil
678+ }
679+ // At this point we have 2 headers in total and the first is the
680+ // validated head of the chian. Check the pivot number and return,
681+ pivot := headers [1 ]
682+ if pivot .Number .Uint64 () != head .Number .Uint64 ()- uint64 (fsMinFullBlocks ) {
683+ return nil , nil , fmt .Errorf ("%w: remote pivot %d != requested %d" , errInvalidChain , pivot .Number , head .Number .Uint64 ()- uint64 (fsMinFullBlocks ))
653684 }
654- p .log .Debug ("Remote head header identified" , "number" , head .Number , "hash" , head .Hash ())
655- return head , nil
685+ return head , pivot , nil
656686
657687 case <- timeout :
658688 p .log .Debug ("Waiting for head header timed out" , "elapsed" , ttl )
659- return nil , errTimeout
689+ return nil , nil , errTimeout
660690
661691 case <- d .bodyCh :
662692 case <- d .receiptCh :
@@ -871,14 +901,14 @@ func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header)
871901 case <- d .cancelCh :
872902 return 0 , errCanceled
873903
874- case packer := <- d .headerCh :
904+ case packet := <- d .headerCh :
875905 // Discard anything not from the origin peer
876- if packer .PeerId () != p .id {
877- log .Debug ("Received headers from incorrect peer" , "peer" , packer .PeerId ())
906+ if packet .PeerId () != p .id {
907+ log .Debug ("Received headers from incorrect peer" , "peer" , packet .PeerId ())
878908 break
879909 }
880910 // Make sure the peer actually gave something valid
881- headers := packer .(* headerPack ).headers
911+ headers := packet .(* headerPack ).headers
882912 if len (headers ) != 1 {
883913 p .log .Warn ("Multiple headers for single request" , "headers" , len (headers ))
884914 return 0 , fmt .Errorf ("%w: multiple headers (%d) for single request" , errBadPeer , len (headers ))
@@ -937,12 +967,13 @@ func (d *Downloader) findAncestor(p *peerConnection, remoteHeader *types.Header)
937967// other peers are only accepted if they map cleanly to the skeleton. If no one
938968// can fill in the skeleton - not even the origin peer - it's assumed invalid and
939969// the origin is dropped.
940- func (d * Downloader ) fetchHeaders (p * peerConnection , from uint64 , pivot uint64 ) error {
970+ func (d * Downloader ) fetchHeaders (p * peerConnection , from uint64 ) error {
941971 p .log .Debug ("Directing header downloads" , "origin" , from )
942972 defer p .log .Debug ("Header download terminated" )
943973
944974 // Create a timeout timer, and the associated header fetcher
945975 skeleton := true // Skeleton assembly phase or finishing up
976+ pivoting := false // Whether the next request is pivot verification
946977 request := time .Now () // time of the last skeleton fetch request
947978 timeout := time .NewTimer (0 ) // timer to dump a non-responsive active peer
948979 <- timeout .C // timeout channel should be initially empty
@@ -963,6 +994,20 @@ func (d *Downloader) fetchHeaders(p *peerConnection, from uint64, pivot uint64)
963994 go p .peer .RequestHeadersByNumber (from , MaxHeaderFetch , 0 , false )
964995 }
965996 }
997+ getNextPivot := func () {
998+ pivoting = true
999+ request = time .Now ()
1000+
1001+ ttl = d .requestTTL ()
1002+ timeout .Reset (ttl )
1003+
1004+ d .pivotLock .RLock ()
1005+ pivot := d .pivotHeader .Number .Uint64 ()
1006+ d .pivotLock .RUnlock ()
1007+
1008+ p .log .Trace ("Fetching next pivot header" , "number" , pivot + uint64 (fsMinFullBlocks ))
1009+ go p .peer .RequestHeadersByNumber (pivot + uint64 (fsMinFullBlocks ), 2 , fsMinFullBlocks - 9 , false ) // move +64 when it's 2x64-8 deep
1010+ }
9661011 // Start pulling the header chain skeleton until all is done
9671012 ancestor := from
9681013 getHeaders (from )
@@ -982,8 +1027,46 @@ func (d *Downloader) fetchHeaders(p *peerConnection, from uint64, pivot uint64)
9821027 headerReqTimer .UpdateSince (request )
9831028 timeout .Stop ()
9841029
1030+ // If the pivot is being checked, move if it became stale and run the real retrieval
1031+ var pivot uint64
1032+
1033+ d .pivotLock .RLock ()
1034+ if d .pivotHeader != nil {
1035+ pivot = d .pivotHeader .Number .Uint64 ()
1036+ }
1037+ d .pivotLock .RUnlock ()
1038+
1039+ if pivoting {
1040+ if packet .Items () == 2 {
1041+ // Retrieve the headers and do some sanity checks, just in case
1042+ headers := packet .(* headerPack ).headers
1043+
1044+ if have , want := headers [0 ].Number .Uint64 (), pivot + uint64 (fsMinFullBlocks ); have != want {
1045+ log .Warn ("Peer sent invalid next pivot" , "have" , have , "want" , want )
1046+ return fmt .Errorf ("%w: next pivot number %d != requested %d" , errInvalidChain , have , want )
1047+ }
1048+ if have , want := headers [1 ].Number .Uint64 (), pivot + 2 * uint64 (fsMinFullBlocks )- 8 ; have != want {
1049+ log .Warn ("Peer sent invalid pivot confirmer" , "have" , have , "want" , want )
1050+ return fmt .Errorf ("%w: next pivot confirmer number %d != requested %d" , errInvalidChain , have , want )
1051+ }
1052+ log .Warn ("Pivot seemingly stale, moving" , "old" , pivot , "new" , headers [0 ].Number )
1053+ pivot = headers [0 ].Number .Uint64 ()
1054+
1055+ d .pivotLock .Lock ()
1056+ d .pivotHeader = headers [0 ]
1057+ d .pivotLock .Unlock ()
1058+
1059+ // Write out the pivot into the database so a rollback beyond
1060+ // it will reenable fast sync and update the state root that
1061+ // the state syncer will be downloading.
1062+ rawdb .WriteLastPivotNumber (d .stateDB , pivot )
1063+ }
1064+ pivoting = false
1065+ getHeaders (from )
1066+ continue
1067+ }
9851068 // If the skeleton's finished, pull any remaining head headers directly from the origin
986- if packet .Items () == 0 && skeleton {
1069+ if skeleton && packet .Items () == 0 {
9871070 skeleton = false
9881071 getHeaders (from )
9891072 continue
@@ -1061,7 +1144,14 @@ func (d *Downloader) fetchHeaders(p *peerConnection, from uint64, pivot uint64)
10611144 return errCanceled
10621145 }
10631146 from += uint64 (len (headers ))
1064- getHeaders (from )
1147+
1148+ // If we're still skeleton filling fast sync, check pivot staleness
1149+ // before continuing to the next skeleton filling
1150+ if skeleton && pivot > 0 {
1151+ getNextPivot ()
1152+ } else {
1153+ getHeaders (from )
1154+ }
10651155 } else {
10661156 // No headers delivered, or all of them being delayed, sleep a bit and retry
10671157 p .log .Trace ("All headers delayed, waiting" )
@@ -1390,7 +1480,7 @@ func (d *Downloader) fetchParts(deliveryCh chan dataPack, deliver func(dataPack)
13901480// processHeaders takes batches of retrieved headers from an input channel and
13911481// keeps processing and scheduling them into the header chain and downloader's
13921482// queue until the stream ends or a failure occurs.
1393- func (d * Downloader ) processHeaders (origin uint64 , pivot uint64 , td * big.Int ) error {
1483+ func (d * Downloader ) processHeaders (origin uint64 , td * big.Int ) error {
13941484 // Keep a count of uncertain headers to roll back
13951485 var (
13961486 rollback uint64 // Zero means no rollback (fine as you can't unroll the genesis)
@@ -1493,6 +1583,14 @@ func (d *Downloader) processHeaders(origin uint64, pivot uint64, td *big.Int) er
14931583 // In case of header only syncing, validate the chunk immediately
14941584 if mode == FastSync || mode == LightSync {
14951585 // If we're importing pure headers, verify based on their recentness
1586+ var pivot uint64
1587+
1588+ d .pivotLock .RLock ()
1589+ if d .pivotHeader != nil {
1590+ pivot = d .pivotHeader .Number .Uint64 ()
1591+ }
1592+ d .pivotLock .RUnlock ()
1593+
14961594 frequency := fsHeaderCheckFrequency
14971595 if chunk [len (chunk )- 1 ].Number .Uint64 ()+ uint64 (fsHeaderForceVerify ) > pivot {
14981596 frequency = 1
@@ -1609,10 +1707,13 @@ func (d *Downloader) importBlockResults(results []*fetchResult) error {
16091707
16101708// processFastSyncContent takes fetch results from the queue and writes them to the
16111709// database. It also controls the synchronisation of state nodes of the pivot block.
1612- func (d * Downloader ) processFastSyncContent (latest * types. Header ) error {
1710+ func (d * Downloader ) processFastSyncContent () error {
16131711 // Start syncing state of the reported head block. This should get us most of
16141712 // the state of the pivot block.
1615- sync := d .syncState (latest .Root )
1713+ d .pivotLock .RLock ()
1714+ sync := d .syncState (d .pivotHeader .Root )
1715+ d .pivotLock .RUnlock ()
1716+
16161717 defer func () {
16171718 // The `sync` object is replaced every time the pivot moves. We need to
16181719 // defer close the very last active one, hence the lazy evaluation vs.
@@ -1627,12 +1728,6 @@ func (d *Downloader) processFastSyncContent(latest *types.Header) error {
16271728 }
16281729 go closeOnErr (sync )
16291730
1630- // Figure out the ideal pivot block. Note, that this goalpost may move if the
1631- // sync takes long enough for the chain head to move significantly.
1632- pivot := uint64 (0 )
1633- if height := latest .Number .Uint64 (); height > uint64 (fsMinFullBlocks ) {
1634- pivot = height - uint64 (fsMinFullBlocks )
1635- }
16361731 // To cater for moving pivot points, track the pivot block and subsequently
16371732 // accumulated download results separately.
16381733 var (
@@ -1659,22 +1754,46 @@ func (d *Downloader) processFastSyncContent(latest *types.Header) error {
16591754 if d .chainInsertHook != nil {
16601755 d .chainInsertHook (results )
16611756 }
1662- if oldPivot != nil {
1757+ // If we haven't downloaded the pivot block yet, check pivot staleness
1758+ // notifications from the header downloader
1759+ d .pivotLock .RLock ()
1760+ pivot := d .pivotHeader
1761+ d .pivotLock .RUnlock ()
1762+
1763+ if oldPivot == nil {
1764+ if pivot .Root != sync .root {
1765+ sync .Cancel ()
1766+ sync = d .syncState (pivot .Root )
1767+
1768+ go closeOnErr (sync )
1769+ }
1770+ } else {
16631771 results = append (append ([]* fetchResult {oldPivot }, oldTail ... ), results ... )
16641772 }
16651773 // Split around the pivot block and process the two sides via fast/full sync
16661774 if atomic .LoadInt32 (& d .committed ) == 0 {
1667- latest = results [len (results )- 1 ].Header
1668- if height := latest .Number .Uint64 (); height > pivot + 2 * uint64 (fsMinFullBlocks ) {
1669- log .Warn ("Pivot became stale, moving" , "old" , pivot , "new" , height - uint64 (fsMinFullBlocks ))
1670- pivot = height - uint64 (fsMinFullBlocks )
1775+ latest := results [len (results )- 1 ].Header
1776+ // If the height is above the pivot block by 2 sets, it means the pivot
1777+ // become stale in the network and it was garbage collected, move to a
1778+ // new pivot.
1779+ //
1780+ // Note, we have `reorgProtHeaderDelay` number of blocks withheld, Those
1781+ // need to be taken into account, otherwise we're detecting the pivot move
1782+ // late and will drop peers due to unavailable state!!!
1783+ if height := latest .Number .Uint64 (); height >= pivot .Number .Uint64 ()+ 2 * uint64 (fsMinFullBlocks )- uint64 (reorgProtHeaderDelay ) {
1784+ log .Warn ("Pivot became stale, moving" , "old" , pivot .Number .Uint64 (), "new" , height - uint64 (fsMinFullBlocks )+ uint64 (reorgProtHeaderDelay ))
1785+ pivot = results [len (results )- 1 - fsMinFullBlocks + reorgProtHeaderDelay ].Header // must exist as lower old pivot is uncommitted
1786+
1787+ d .pivotLock .Lock ()
1788+ d .pivotHeader = pivot
1789+ d .pivotLock .Unlock ()
16711790
16721791 // Write out the pivot into the database so a rollback beyond it will
16731792 // reenable fast sync
1674- rawdb .WriteLastPivotNumber (d .stateDB , pivot )
1793+ rawdb .WriteLastPivotNumber (d .stateDB , pivot . Number . Uint64 () )
16751794 }
16761795 }
1677- P , beforeP , afterP := splitAroundPivot (pivot , results )
1796+ P , beforeP , afterP := splitAroundPivot (pivot . Number . Uint64 () , results )
16781797 if err := d .commitFastSyncData (beforeP , sync ); err != nil {
16791798 return err
16801799 }
0 commit comments