github.com/calmw/ethereum@v0.1.1/eth/downloader/skeleton.go (about)

     1  // Copyright 2022 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package downloader
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  	"fmt"
    23  	"math/rand"
    24  	"sort"
    25  	"time"
    26  
    27  	"github.com/calmw/ethereum/common"
    28  	"github.com/calmw/ethereum/core/rawdb"
    29  	"github.com/calmw/ethereum/core/types"
    30  	"github.com/calmw/ethereum/eth/protocols/eth"
    31  	"github.com/calmw/ethereum/ethdb"
    32  	"github.com/calmw/ethereum/log"
    33  )
    34  
    35  // scratchHeaders is the number of headers to store in a scratch space to allow
    36  // concurrent downloads. A header is about 0.5KB in size, so there is no worry
    37  // about using too much memory. The only catch is that we can only validate gaps
    38  // after they're linked to the head, so the bigger the scratch space, the larger
    39  // potential for invalid headers.
    40  //
    41  // The current scratch space of 131072 headers is expected to use 64MB RAM.
    42  const scratchHeaders = 131072
    43  
    44  // requestHeaders is the number of header to request from a remote peer in a single
    45  // network packet. Although the skeleton downloader takes into consideration peer
    46  // capacities when picking idlers, the packet size was decided to remain constant
    47  // since headers are relatively small and it's easier to work with fixed batches
    48  // vs. dynamic interval fillings.
    49  const requestHeaders = 512
    50  
    51  // errSyncLinked is an internal helper error to signal that the current sync
    52  // cycle linked up to the genesis block, this the skeleton syncer should ping
    53  // the backfiller to resume. Since we already have that logic on sync start,
    54  // piggy-back on that instead of 2 entrypoints.
    55  var errSyncLinked = errors.New("sync linked")
    56  
    57  // errSyncMerged is an internal helper error to signal that the current sync
    58  // cycle merged with a previously aborted subchain, thus the skeleton syncer
    59  // should abort and restart with the new state.
    60  var errSyncMerged = errors.New("sync merged")
    61  
    62  // errSyncReorged is an internal helper error to signal that the head chain of
    63  // the current sync cycle was (partially) reorged, thus the skeleton syncer
    64  // should abort and restart with the new state.
    65  var errSyncReorged = errors.New("sync reorged")
    66  
    67  // errTerminated is returned if the sync mechanism was terminated for this run of
    68  // the process. This is usually the case when Geth is shutting down and some events
    69  // might still be propagating.
    70  var errTerminated = errors.New("terminated")
    71  
    72  // errReorgDenied is returned if an attempt is made to extend the beacon chain
    73  // with a new header, but it does not link up to the existing sync.
    74  var errReorgDenied = errors.New("non-forced head reorg denied")
    75  
    76  func init() {
    77  	// Tuning parameters is nice, but the scratch space must be assignable in
    78  	// full to peers. It's a useless cornercase to support a dangling half-group.
    79  	if scratchHeaders%requestHeaders != 0 {
    80  		panic("Please make scratchHeaders divisible by requestHeaders")
    81  	}
    82  }
    83  
    84  // subchain is a contiguous header chain segment that is backed by the database,
    85  // but may not be linked to the live chain. The skeleton downloader may produce
    86  // a new one of these every time it is restarted until the subchain grows large
    87  // enough to connect with a previous subchain.
    88  //
    89  // The subchains use the exact same database namespace and are not disjoint from
    90  // each other. As such, extending one to overlap the other entails reducing the
    91  // second one first. This combined buffer model is used to avoid having to move
    92  // data on disk when two subchains are joined together.
    93  type subchain struct {
    94  	Head uint64      // Block number of the newest header in the subchain
    95  	Tail uint64      // Block number of the oldest header in the subchain
    96  	Next common.Hash // Block hash of the next oldest header in the subchain
    97  }
    98  
    99  // skeletonProgress is a database entry to allow suspending and resuming a chain
   100  // sync. As the skeleton header chain is downloaded backwards, restarts can and
   101  // will produce temporarily disjoint subchains. There is no way to restart a
   102  // suspended skeleton sync without prior knowledge of all prior suspension points.
   103  type skeletonProgress struct {
   104  	Subchains []*subchain // Disjoint subchains downloaded until now
   105  	Finalized *uint64     // Last known finalized block number
   106  }
   107  
   108  // headUpdate is a notification that the beacon sync should switch to a new target.
   109  // The update might request whether to forcefully change the target, or only try to
   110  // extend it and fail if it's not possible.
   111  type headUpdate struct {
   112  	header *types.Header // Header to update the sync target to
   113  	final  *types.Header // Finalized header to use as thresholds
   114  	force  bool          // Whether to force the update or only extend if possible
   115  	errc   chan error    // Channel to signal acceptance of the new head
   116  }
   117  
   118  // headerRequest tracks a pending header request to ensure responses are to
   119  // actual requests and to validate any security constraints.
   120  //
   121  // Concurrency note: header requests and responses are handled concurrently from
   122  // the main runloop to allow Keccak256 hash verifications on the peer's thread and
   123  // to drop on invalid response. The request struct must contain all the data to
   124  // construct the response without accessing runloop internals (i.e. subchains).
   125  // That is only included to allow the runloop to match a response to the task being
   126  // synced without having yet another set of maps.
   127  type headerRequest struct {
   128  	peer string // Peer to which this request is assigned
   129  	id   uint64 // Request ID of this request
   130  
   131  	deliver chan *headerResponse // Channel to deliver successful response on
   132  	revert  chan *headerRequest  // Channel to deliver request failure on
   133  	cancel  chan struct{}        // Channel to track sync cancellation
   134  	stale   chan struct{}        // Channel to signal the request was dropped
   135  
   136  	head uint64 // Head number of the requested batch of headers
   137  }
   138  
   139  // headerResponse is an already verified remote response to a header request.
   140  type headerResponse struct {
   141  	peer    *peerConnection // Peer from which this response originates
   142  	reqid   uint64          // Request ID that this response fulfils
   143  	headers []*types.Header // Chain of headers
   144  }
   145  
   146  // backfiller is a callback interface through which the skeleton sync can tell
   147  // the downloader that it should suspend or resume backfilling on specific head
   148  // events (e.g. suspend on forks or gaps, resume on successful linkups).
   149  type backfiller interface {
   150  	// suspend requests the backfiller to abort any running full or snap sync
   151  	// based on the skeleton chain as it might be invalid. The backfiller should
   152  	// gracefully handle multiple consecutive suspends without a resume, even
   153  	// on initial startup.
   154  	//
   155  	// The method should return the last block header that has been successfully
   156  	// backfilled, or nil if the backfiller was not resumed.
   157  	suspend() *types.Header
   158  
   159  	// resume requests the backfiller to start running fill or snap sync based on
   160  	// the skeleton chain as it has successfully been linked. Appending new heads
   161  	// to the end of the chain will not result in suspend/resume cycles.
   162  	// leaking too much sync logic out to the filler.
   163  	resume()
   164  }
   165  
   166  // skeleton represents a header chain synchronized after the merge where blocks
   167  // aren't validated any more via PoW in a forward fashion, rather are dictated
   168  // and extended at the head via the beacon chain and backfilled on the original
   169  // Ethereum block sync protocol.
   170  //
   171  // Since the skeleton is grown backwards from head to genesis, it is handled as
   172  // a separate entity, not mixed in with the logical sequential transition of the
   173  // blocks. Once the skeleton is connected to an existing, validated chain, the
   174  // headers will be moved into the main downloader for filling and execution.
   175  //
   176  // Opposed to the original Ethereum block synchronization which is trustless (and
   177  // uses a master peer to minimize the attack surface), post-merge block sync starts
   178  // from a trusted head. As such, there is no need for a master peer any more and
   179  // headers can be requested fully concurrently (though some batches might be
   180  // discarded if they don't link up correctly).
   181  //
   182  // Although a skeleton is part of a sync cycle, it is not recreated, rather stays
   183  // alive throughout the lifetime of the downloader. This allows it to be extended
   184  // concurrently with the sync cycle, since extensions arrive from an API surface,
   185  // not from within (vs. legacy Ethereum sync).
   186  //
   187  // Since the skeleton tracks the entire header chain until it is consumed by the
   188  // forward block filling, it needs 0.5KB/block storage. At current mainnet sizes
   189  // this is only possible with a disk backend. Since the skeleton is separate from
   190  // the node's header chain, storing the headers ephemerally until sync finishes
   191  // is wasted disk IO, but it's a price we're going to pay to keep things simple
   192  // for now.
   193  type skeleton struct {
   194  	db     ethdb.Database // Database backing the skeleton
   195  	filler backfiller     // Chain syncer suspended/resumed by head events
   196  
   197  	peers *peerSet                   // Set of peers we can sync from
   198  	idles map[string]*peerConnection // Set of idle peers in the current sync cycle
   199  	drop  peerDropFn                 // Drops a peer for misbehaving
   200  
   201  	progress *skeletonProgress // Sync progress tracker for resumption and metrics
   202  	started  time.Time         // Timestamp when the skeleton syncer was created
   203  	logged   time.Time         // Timestamp when progress was last logged to the user
   204  	pulled   uint64            // Number of headers downloaded in this run
   205  
   206  	scratchSpace  []*types.Header // Scratch space to accumulate headers in (first = recent)
   207  	scratchOwners []string        // Peer IDs owning chunks of the scratch space (pend or delivered)
   208  	scratchHead   uint64          // Block number of the first item in the scratch space
   209  
   210  	requests map[uint64]*headerRequest // Header requests currently running
   211  
   212  	headEvents chan *headUpdate // Notification channel for new heads
   213  	terminate  chan chan error  // Termination channel to abort sync
   214  	terminated chan struct{}    // Channel to signal that the syncer is dead
   215  
   216  	// Callback hooks used during testing
   217  	syncStarting func() // callback triggered after a sync cycle is inited but before started
   218  }
   219  
   220  // newSkeleton creates a new sync skeleton that tracks a potentially dangling
   221  // header chain until it's linked into an existing set of blocks.
   222  func newSkeleton(db ethdb.Database, peers *peerSet, drop peerDropFn, filler backfiller) *skeleton {
   223  	sk := &skeleton{
   224  		db:         db,
   225  		filler:     filler,
   226  		peers:      peers,
   227  		drop:       drop,
   228  		requests:   make(map[uint64]*headerRequest),
   229  		headEvents: make(chan *headUpdate),
   230  		terminate:  make(chan chan error),
   231  		terminated: make(chan struct{}),
   232  	}
   233  	go sk.startup()
   234  	return sk
   235  }
   236  
   237  // startup is an initial background loop which waits for an event to start or
   238  // tear the syncer down. This is required to make the skeleton sync loop once
   239  // per process but at the same time not start before the beacon chain announces
   240  // a new (existing) head.
   241  func (s *skeleton) startup() {
   242  	// Close a notification channel so anyone sending us events will know if the
   243  	// sync loop was torn down for good.
   244  	defer close(s.terminated)
   245  
   246  	// Wait for startup or teardown. This wait might loop a few times if a beacon
   247  	// client requests sync head extensions, but not forced reorgs (i.e. they are
   248  	// giving us new payloads without setting a starting head initially).
   249  	for {
   250  		select {
   251  		case errc := <-s.terminate:
   252  			// No head was announced but Geth is shutting down
   253  			errc <- nil
   254  			return
   255  
   256  		case event := <-s.headEvents:
   257  			// New head announced, start syncing to it, looping every time a current
   258  			// cycle is terminated due to a chain event (head reorg, old chain merge).
   259  			if !event.force {
   260  				event.errc <- errors.New("forced head needed for startup")
   261  				continue
   262  			}
   263  			event.errc <- nil // forced head accepted for startup
   264  			head := event.header
   265  			s.started = time.Now()
   266  
   267  			for {
   268  				// If the sync cycle terminated or was terminated, propagate up when
   269  				// higher layers request termination. There's no fancy explicit error
   270  				// signalling as the sync loop should never terminate (TM).
   271  				newhead, err := s.sync(head)
   272  				switch {
   273  				case err == errSyncLinked:
   274  					// Sync cycle linked up to the genesis block. Tear down the loop
   275  					// and restart it so, it can properly notify the backfiller. Don't
   276  					// account a new head.
   277  					head = nil
   278  
   279  				case err == errSyncMerged:
   280  					// Subchains were merged, we just need to reinit the internal
   281  					// start to continue on the tail of the merged chain. Don't
   282  					// announce a new head,
   283  					head = nil
   284  
   285  				case err == errSyncReorged:
   286  					// The subchain being synced got modified at the head in a
   287  					// way that requires resyncing it. Restart sync with the new
   288  					// head to force a cleanup.
   289  					head = newhead
   290  
   291  				case err == errTerminated:
   292  					// Sync was requested to be terminated from within, stop and
   293  					// return (no need to pass a message, was already done internally)
   294  					return
   295  
   296  				default:
   297  					// Sync either successfully terminated or failed with an unhandled
   298  					// error. Abort and wait until Geth requests a termination.
   299  					errc := <-s.terminate
   300  					errc <- err
   301  					return
   302  				}
   303  			}
   304  		}
   305  	}
   306  }
   307  
   308  // Terminate tears down the syncer indefinitely.
   309  func (s *skeleton) Terminate() error {
   310  	// Request termination and fetch any errors
   311  	errc := make(chan error)
   312  	s.terminate <- errc
   313  	err := <-errc
   314  
   315  	// Wait for full shutdown (not necessary, but cleaner)
   316  	<-s.terminated
   317  	return err
   318  }
   319  
   320  // Sync starts or resumes a previous sync cycle to download and maintain a reverse
   321  // header chain starting at the head and leading towards genesis to an available
   322  // ancestor.
   323  //
   324  // This method does not block, rather it just waits until the syncer receives the
   325  // fed header. What the syncer does with it is the syncer's problem.
   326  func (s *skeleton) Sync(head *types.Header, final *types.Header, force bool) error {
   327  	log.Trace("New skeleton head announced", "number", head.Number, "hash", head.Hash(), "force", force)
   328  	errc := make(chan error)
   329  
   330  	select {
   331  	case s.headEvents <- &headUpdate{header: head, final: final, force: force, errc: errc}:
   332  		return <-errc
   333  	case <-s.terminated:
   334  		return errTerminated
   335  	}
   336  }
   337  
   338  // sync is the internal version of Sync that executes a single sync cycle, either
   339  // until some termination condition is reached, or until the current cycle merges
   340  // with a previously aborted run.
   341  func (s *skeleton) sync(head *types.Header) (*types.Header, error) {
   342  	// If we're continuing a previous merge interrupt, just access the existing
   343  	// old state without initing from disk.
   344  	if head == nil {
   345  		head = rawdb.ReadSkeletonHeader(s.db, s.progress.Subchains[0].Head)
   346  	} else {
   347  		// Otherwise, initialize the sync, trimming and previous leftovers until
   348  		// we're consistent with the newly requested chain head
   349  		s.initSync(head)
   350  	}
   351  	// Create the scratch space to fill with concurrently downloaded headers
   352  	s.scratchSpace = make([]*types.Header, scratchHeaders)
   353  	defer func() { s.scratchSpace = nil }() // don't hold on to references after sync
   354  
   355  	s.scratchOwners = make([]string, scratchHeaders/requestHeaders)
   356  	defer func() { s.scratchOwners = nil }() // don't hold on to references after sync
   357  
   358  	s.scratchHead = s.progress.Subchains[0].Tail - 1 // tail must not be 0!
   359  
   360  	// If the sync is already done, resume the backfiller. When the loop stops,
   361  	// terminate the backfiller too.
   362  	linked := len(s.progress.Subchains) == 1 &&
   363  		rawdb.HasHeader(s.db, s.progress.Subchains[0].Next, s.scratchHead) &&
   364  		rawdb.HasBody(s.db, s.progress.Subchains[0].Next, s.scratchHead) &&
   365  		rawdb.HasReceipts(s.db, s.progress.Subchains[0].Next, s.scratchHead)
   366  	if linked {
   367  		s.filler.resume()
   368  	}
   369  	defer func() {
   370  		if filled := s.filler.suspend(); filled != nil {
   371  			// If something was filled, try to delete stale sync helpers. If
   372  			// unsuccessful, warn the user, but not much else we can do (it's
   373  			// a programming error, just let users report an issue and don't
   374  			// choke in the meantime).
   375  			if err := s.cleanStales(filled); err != nil {
   376  				log.Error("Failed to clean stale beacon headers", "err", err)
   377  			}
   378  		}
   379  	}()
   380  	// Create a set of unique channels for this sync cycle. We need these to be
   381  	// ephemeral so a data race doesn't accidentally deliver something stale on
   382  	// a persistent channel across syncs (yup, this happened)
   383  	var (
   384  		requestFails = make(chan *headerRequest)
   385  		responses    = make(chan *headerResponse)
   386  	)
   387  	cancel := make(chan struct{})
   388  	defer close(cancel)
   389  
   390  	log.Debug("Starting reverse header sync cycle", "head", head.Number, "hash", head.Hash(), "cont", s.scratchHead)
   391  
   392  	// Whether sync completed or not, disregard any future packets
   393  	defer func() {
   394  		log.Debug("Terminating reverse header sync cycle", "head", head.Number, "hash", head.Hash(), "cont", s.scratchHead)
   395  		s.requests = make(map[uint64]*headerRequest)
   396  	}()
   397  
   398  	// Start tracking idle peers for task assignments
   399  	peering := make(chan *peeringEvent, 64) // arbitrary buffer, just some burst protection
   400  
   401  	peeringSub := s.peers.SubscribeEvents(peering)
   402  	defer peeringSub.Unsubscribe()
   403  
   404  	s.idles = make(map[string]*peerConnection)
   405  	for _, peer := range s.peers.AllPeers() {
   406  		s.idles[peer.id] = peer
   407  	}
   408  	// Nofity any tester listening for startup events
   409  	if s.syncStarting != nil {
   410  		s.syncStarting()
   411  	}
   412  	for {
   413  		// Something happened, try to assign new tasks to any idle peers
   414  		if !linked {
   415  			s.assignTasks(responses, requestFails, cancel)
   416  		}
   417  		// Wait for something to happen
   418  		select {
   419  		case event := <-peering:
   420  			// A peer joined or left, the tasks queue and allocations need to be
   421  			// checked for potential assignment or reassignment
   422  			peerid := event.peer.id
   423  			if event.join {
   424  				log.Debug("Joining skeleton peer", "id", peerid)
   425  				s.idles[peerid] = event.peer
   426  			} else {
   427  				log.Debug("Leaving skeleton peer", "id", peerid)
   428  				s.revertRequests(peerid)
   429  				delete(s.idles, peerid)
   430  			}
   431  
   432  		case errc := <-s.terminate:
   433  			errc <- nil
   434  			return nil, errTerminated
   435  
   436  		case event := <-s.headEvents:
   437  			// New head was announced, try to integrate it. If successful, nothing
   438  			// needs to be done as the head simply extended the last range. For now
   439  			// we don't seamlessly integrate reorgs to keep things simple. If the
   440  			// network starts doing many mini reorgs, it might be worthwhile handling
   441  			// a limited depth without an error.
   442  			if reorged := s.processNewHead(event.header, event.final, event.force); reorged {
   443  				// If a reorg is needed, and we're forcing the new head, signal
   444  				// the syncer to tear down and start over. Otherwise, drop the
   445  				// non-force reorg.
   446  				if event.force {
   447  					event.errc <- nil // forced head reorg accepted
   448  					return event.header, errSyncReorged
   449  				}
   450  				event.errc <- errReorgDenied
   451  				continue
   452  			}
   453  			event.errc <- nil // head extension accepted
   454  
   455  			// New head was integrated into the skeleton chain. If the backfiller
   456  			// is still running, it will pick it up. If it already terminated,
   457  			// a new cycle needs to be spun up.
   458  			if linked {
   459  				s.filler.resume()
   460  			}
   461  
   462  		case req := <-requestFails:
   463  			s.revertRequest(req)
   464  
   465  		case res := <-responses:
   466  			// Process the batch of headers. If though processing we managed to
   467  			// link the current subchain to a previously downloaded one, abort the
   468  			// sync and restart with the merged subchains.
   469  			//
   470  			// If we managed to link to the existing local chain or genesis block,
   471  			// abort sync altogether.
   472  			linked, merged := s.processResponse(res)
   473  			if linked {
   474  				log.Debug("Beacon sync linked to local chain")
   475  				return nil, errSyncLinked
   476  			}
   477  			if merged {
   478  				log.Debug("Beacon sync merged subchains")
   479  				return nil, errSyncMerged
   480  			}
   481  			// We still have work to do, loop and repeat
   482  		}
   483  	}
   484  }
   485  
   486  // initSync attempts to get the skeleton sync into a consistent state wrt any
   487  // past state on disk and the newly requested head to sync to. If the new head
   488  // is nil, the method will return and continue from the previous head.
   489  func (s *skeleton) initSync(head *types.Header) {
   490  	// Extract the head number, we'll need it all over
   491  	number := head.Number.Uint64()
   492  
   493  	// Retrieve the previously saved sync progress
   494  	if status := rawdb.ReadSkeletonSyncStatus(s.db); len(status) > 0 {
   495  		s.progress = new(skeletonProgress)
   496  		if err := json.Unmarshal(status, s.progress); err != nil {
   497  			log.Error("Failed to decode skeleton sync status", "err", err)
   498  		} else {
   499  			// Previous sync was available, print some continuation logs
   500  			for _, subchain := range s.progress.Subchains {
   501  				log.Debug("Restarting skeleton subchain", "head", subchain.Head, "tail", subchain.Tail)
   502  			}
   503  			// Create a new subchain for the head (unless the last can be extended),
   504  			// trimming anything it would overwrite
   505  			headchain := &subchain{
   506  				Head: number,
   507  				Tail: number,
   508  				Next: head.ParentHash,
   509  			}
   510  			for len(s.progress.Subchains) > 0 {
   511  				// If the last chain is above the new head, delete altogether
   512  				lastchain := s.progress.Subchains[0]
   513  				if lastchain.Tail >= headchain.Tail {
   514  					log.Debug("Dropping skeleton subchain", "head", lastchain.Head, "tail", lastchain.Tail)
   515  					s.progress.Subchains = s.progress.Subchains[1:]
   516  					continue
   517  				}
   518  				// Otherwise truncate the last chain if needed and abort trimming
   519  				if lastchain.Head >= headchain.Tail {
   520  					log.Debug("Trimming skeleton subchain", "oldhead", lastchain.Head, "newhead", headchain.Tail-1, "tail", lastchain.Tail)
   521  					lastchain.Head = headchain.Tail - 1
   522  				}
   523  				break
   524  			}
   525  			// If the last subchain can be extended, we're lucky. Otherwise, create
   526  			// a new subchain sync task.
   527  			var extended bool
   528  			if n := len(s.progress.Subchains); n > 0 {
   529  				lastchain := s.progress.Subchains[0]
   530  				if lastchain.Head == headchain.Tail-1 {
   531  					lasthead := rawdb.ReadSkeletonHeader(s.db, lastchain.Head)
   532  					if lasthead.Hash() == head.ParentHash {
   533  						log.Debug("Extended skeleton subchain with new head", "head", headchain.Tail, "tail", lastchain.Tail)
   534  						lastchain.Head = headchain.Tail
   535  						extended = true
   536  					}
   537  				}
   538  			}
   539  			if !extended {
   540  				log.Debug("Created new skeleton subchain", "head", number, "tail", number)
   541  				s.progress.Subchains = append([]*subchain{headchain}, s.progress.Subchains...)
   542  			}
   543  			// Update the database with the new sync stats and insert the new
   544  			// head header. We won't delete any trimmed skeleton headers since
   545  			// those will be outside the index space of the many subchains and
   546  			// the database space will be reclaimed eventually when processing
   547  			// blocks above the current head (TODO(karalabe): don't forget).
   548  			batch := s.db.NewBatch()
   549  
   550  			rawdb.WriteSkeletonHeader(batch, head)
   551  			s.saveSyncStatus(batch)
   552  
   553  			if err := batch.Write(); err != nil {
   554  				log.Crit("Failed to write skeleton sync status", "err", err)
   555  			}
   556  			return
   557  		}
   558  	}
   559  	// Either we've failed to decode the previous state, or there was none. Start
   560  	// a fresh sync with a single subchain represented by the currently sent
   561  	// chain head.
   562  	s.progress = &skeletonProgress{
   563  		Subchains: []*subchain{
   564  			{
   565  				Head: number,
   566  				Tail: number,
   567  				Next: head.ParentHash,
   568  			},
   569  		},
   570  	}
   571  	batch := s.db.NewBatch()
   572  
   573  	rawdb.WriteSkeletonHeader(batch, head)
   574  	s.saveSyncStatus(batch)
   575  
   576  	if err := batch.Write(); err != nil {
   577  		log.Crit("Failed to write initial skeleton sync status", "err", err)
   578  	}
   579  	log.Debug("Created initial skeleton subchain", "head", number, "tail", number)
   580  }
   581  
   582  // saveSyncStatus marshals the remaining sync tasks into leveldb.
   583  func (s *skeleton) saveSyncStatus(db ethdb.KeyValueWriter) {
   584  	status, err := json.Marshal(s.progress)
   585  	if err != nil {
   586  		panic(err) // This can only fail during implementation
   587  	}
   588  	rawdb.WriteSkeletonSyncStatus(db, status)
   589  }
   590  
   591  // processNewHead does the internal shuffling for a new head marker and either
   592  // accepts and integrates it into the skeleton or requests a reorg. Upon reorg,
   593  // the syncer will tear itself down and restart with a fresh head. It is simpler
   594  // to reconstruct the sync state than to mutate it and hope for the best.
   595  func (s *skeleton) processNewHead(head *types.Header, final *types.Header, force bool) bool {
   596  	// If a new finalized block was announced, update the sync process independent
   597  	// of what happens with the sync head below
   598  	if final != nil {
   599  		if number := final.Number.Uint64(); s.progress.Finalized == nil || *s.progress.Finalized != number {
   600  			s.progress.Finalized = new(uint64)
   601  			*s.progress.Finalized = final.Number.Uint64()
   602  
   603  			s.saveSyncStatus(s.db)
   604  		}
   605  	}
   606  	// If the header cannot be inserted without interruption, return an error for
   607  	// the outer loop to tear down the skeleton sync and restart it
   608  	number := head.Number.Uint64()
   609  
   610  	lastchain := s.progress.Subchains[0]
   611  	if lastchain.Tail >= number {
   612  		// If the chain is down to a single beacon header, and it is re-announced
   613  		// once more, ignore it instead of tearing down sync for a noop.
   614  		if lastchain.Head == lastchain.Tail {
   615  			if current := rawdb.ReadSkeletonHeader(s.db, number); current.Hash() == head.Hash() {
   616  				return false
   617  			}
   618  		}
   619  		// Not a noop / double head announce, abort with a reorg
   620  		if force {
   621  			log.Warn("Beacon chain reorged", "tail", lastchain.Tail, "head", lastchain.Head, "newHead", number)
   622  		}
   623  		return true
   624  	}
   625  	if lastchain.Head+1 < number {
   626  		if force {
   627  			log.Warn("Beacon chain gapped", "head", lastchain.Head, "newHead", number)
   628  		}
   629  		return true
   630  	}
   631  	if parent := rawdb.ReadSkeletonHeader(s.db, number-1); parent.Hash() != head.ParentHash {
   632  		if force {
   633  			log.Warn("Beacon chain forked", "ancestor", parent.Number, "hash", parent.Hash(), "want", head.ParentHash)
   634  		}
   635  		return true
   636  	}
   637  	// New header seems to be in the last subchain range. Unwind any extra headers
   638  	// from the chain tip and insert the new head. We won't delete any trimmed
   639  	// skeleton headers since those will be outside the index space of the many
   640  	// subchains and the database space will be reclaimed eventually when processing
   641  	// blocks above the current head (TODO(karalabe): don't forget).
   642  	batch := s.db.NewBatch()
   643  
   644  	rawdb.WriteSkeletonHeader(batch, head)
   645  	lastchain.Head = number
   646  	s.saveSyncStatus(batch)
   647  
   648  	if err := batch.Write(); err != nil {
   649  		log.Crit("Failed to write skeleton sync status", "err", err)
   650  	}
   651  	return false
   652  }
   653  
   654  // assignTasks attempts to match idle peers to pending header retrievals.
   655  func (s *skeleton) assignTasks(success chan *headerResponse, fail chan *headerRequest, cancel chan struct{}) {
   656  	// Sort the peers by download capacity to use faster ones if many available
   657  	idlers := &peerCapacitySort{
   658  		peers: make([]*peerConnection, 0, len(s.idles)),
   659  		caps:  make([]int, 0, len(s.idles)),
   660  	}
   661  	targetTTL := s.peers.rates.TargetTimeout()
   662  	for _, peer := range s.idles {
   663  		idlers.peers = append(idlers.peers, peer)
   664  		idlers.caps = append(idlers.caps, s.peers.rates.Capacity(peer.id, eth.BlockHeadersMsg, targetTTL))
   665  	}
   666  	if len(idlers.peers) == 0 {
   667  		return
   668  	}
   669  	sort.Sort(idlers)
   670  
   671  	// Find header regions not yet downloading and fill them
   672  	for task, owner := range s.scratchOwners {
   673  		// If we're out of idle peers, stop assigning tasks
   674  		if len(idlers.peers) == 0 {
   675  			return
   676  		}
   677  		// Skip any tasks already filling
   678  		if owner != "" {
   679  			continue
   680  		}
   681  		// If we've reached the genesis, stop assigning tasks
   682  		if uint64(task*requestHeaders) >= s.scratchHead {
   683  			return
   684  		}
   685  		// Found a task and have peers available, assign it
   686  		idle := idlers.peers[0]
   687  
   688  		idlers.peers = idlers.peers[1:]
   689  		idlers.caps = idlers.caps[1:]
   690  
   691  		// Matched a pending task to an idle peer, allocate a unique request id
   692  		var reqid uint64
   693  		for {
   694  			reqid = uint64(rand.Int63())
   695  			if reqid == 0 {
   696  				continue
   697  			}
   698  			if _, ok := s.requests[reqid]; ok {
   699  				continue
   700  			}
   701  			break
   702  		}
   703  		// Generate the network query and send it to the peer
   704  		req := &headerRequest{
   705  			peer:    idle.id,
   706  			id:      reqid,
   707  			deliver: success,
   708  			revert:  fail,
   709  			cancel:  cancel,
   710  			stale:   make(chan struct{}),
   711  			head:    s.scratchHead - uint64(task*requestHeaders),
   712  		}
   713  		s.requests[reqid] = req
   714  		delete(s.idles, idle.id)
   715  
   716  		// Generate the network query and send it to the peer
   717  		go s.executeTask(idle, req)
   718  
   719  		// Inject the request into the task to block further assignments
   720  		s.scratchOwners[task] = idle.id
   721  	}
   722  }
   723  
   724  // executeTask executes a single fetch request, blocking until either a result
   725  // arrives or a timeouts / cancellation is triggered. The method should be run
   726  // on its own goroutine and will deliver on the requested channels.
   727  func (s *skeleton) executeTask(peer *peerConnection, req *headerRequest) {
   728  	start := time.Now()
   729  	resCh := make(chan *eth.Response)
   730  
   731  	// Figure out how many headers to fetch. Usually this will be a full batch,
   732  	// but for the very tail of the chain, trim the request to the number left.
   733  	// Since nodes may or may not return the genesis header for a batch request,
   734  	// don't even request it. The parent hash of block #1 is enough to link.
   735  	requestCount := requestHeaders
   736  	if req.head < requestHeaders {
   737  		requestCount = int(req.head)
   738  	}
   739  	peer.log.Trace("Fetching skeleton headers", "from", req.head, "count", requestCount)
   740  	netreq, err := peer.peer.RequestHeadersByNumber(req.head, requestCount, 0, true, resCh)
   741  	if err != nil {
   742  		peer.log.Trace("Failed to request headers", "err", err)
   743  		s.scheduleRevertRequest(req)
   744  		return
   745  	}
   746  	defer netreq.Close()
   747  
   748  	// Wait until the response arrives, the request is cancelled or times out
   749  	ttl := s.peers.rates.TargetTimeout()
   750  
   751  	timeoutTimer := time.NewTimer(ttl)
   752  	defer timeoutTimer.Stop()
   753  
   754  	select {
   755  	case <-req.cancel:
   756  		peer.log.Debug("Header request cancelled")
   757  		s.scheduleRevertRequest(req)
   758  
   759  	case <-timeoutTimer.C:
   760  		// Header retrieval timed out, update the metrics
   761  		peer.log.Warn("Header request timed out, dropping peer", "elapsed", ttl)
   762  		headerTimeoutMeter.Mark(1)
   763  		s.peers.rates.Update(peer.id, eth.BlockHeadersMsg, 0, 0)
   764  		s.scheduleRevertRequest(req)
   765  
   766  		// At this point we either need to drop the offending peer, or we need a
   767  		// mechanism to allow waiting for the response and not cancel it. For now
   768  		// lets go with dropping since the header sizes are deterministic and the
   769  		// beacon sync runs exclusive (downloader is idle) so there should be no
   770  		// other load to make timeouts probable. If we notice that timeouts happen
   771  		// more often than we'd like, we can introduce a tracker for the requests
   772  		// gone stale and monitor them. However, in that case too, we need a way
   773  		// to protect against malicious peers never responding, so it would need
   774  		// a second, hard-timeout mechanism.
   775  		s.drop(peer.id)
   776  
   777  	case res := <-resCh:
   778  		// Headers successfully retrieved, update the metrics
   779  		headers := *res.Res.(*eth.BlockHeadersPacket)
   780  
   781  		headerReqTimer.Update(time.Since(start))
   782  		s.peers.rates.Update(peer.id, eth.BlockHeadersMsg, res.Time, len(headers))
   783  
   784  		// Cross validate the headers with the requests
   785  		switch {
   786  		case len(headers) == 0:
   787  			// No headers were delivered, reject the response and reschedule
   788  			peer.log.Debug("No headers delivered")
   789  			res.Done <- errors.New("no headers delivered")
   790  			s.scheduleRevertRequest(req)
   791  
   792  		case headers[0].Number.Uint64() != req.head:
   793  			// Header batch anchored at non-requested number
   794  			peer.log.Debug("Invalid header response head", "have", headers[0].Number, "want", req.head)
   795  			res.Done <- errors.New("invalid header batch anchor")
   796  			s.scheduleRevertRequest(req)
   797  
   798  		case req.head >= requestHeaders && len(headers) != requestHeaders:
   799  			// Invalid number of non-genesis headers delivered, reject the response and reschedule
   800  			peer.log.Debug("Invalid non-genesis header count", "have", len(headers), "want", requestHeaders)
   801  			res.Done <- errors.New("not enough non-genesis headers delivered")
   802  			s.scheduleRevertRequest(req)
   803  
   804  		case req.head < requestHeaders && uint64(len(headers)) != req.head:
   805  			// Invalid number of genesis headers delivered, reject the response and reschedule
   806  			peer.log.Debug("Invalid genesis header count", "have", len(headers), "want", headers[0].Number.Uint64())
   807  			res.Done <- errors.New("not enough genesis headers delivered")
   808  			s.scheduleRevertRequest(req)
   809  
   810  		default:
   811  			// Packet seems structurally valid, check hash progression and if it
   812  			// is correct too, deliver for storage
   813  			for i := 0; i < len(headers)-1; i++ {
   814  				if headers[i].ParentHash != headers[i+1].Hash() {
   815  					peer.log.Debug("Invalid hash progression", "index", i, "wantparenthash", headers[i].ParentHash, "haveparenthash", headers[i+1].Hash())
   816  					res.Done <- errors.New("invalid hash progression")
   817  					s.scheduleRevertRequest(req)
   818  					return
   819  				}
   820  			}
   821  			// Hash chain is valid. The delivery might still be junk as we're
   822  			// downloading batches concurrently (so no way to link the headers
   823  			// until gaps are filled); in that case, we'll nuke the peer when
   824  			// we detect the fault.
   825  			res.Done <- nil
   826  
   827  			select {
   828  			case req.deliver <- &headerResponse{
   829  				peer:    peer,
   830  				reqid:   req.id,
   831  				headers: headers,
   832  			}:
   833  			case <-req.cancel:
   834  			}
   835  		}
   836  	}
   837  }
   838  
   839  // revertRequests locates all the currently pending requests from a particular
   840  // peer and reverts them, rescheduling for others to fulfill.
   841  func (s *skeleton) revertRequests(peer string) {
   842  	// Gather the requests first, revertals need the lock too
   843  	var requests []*headerRequest
   844  	for _, req := range s.requests {
   845  		if req.peer == peer {
   846  			requests = append(requests, req)
   847  		}
   848  	}
   849  	// Revert all the requests matching the peer
   850  	for _, req := range requests {
   851  		s.revertRequest(req)
   852  	}
   853  }
   854  
   855  // scheduleRevertRequest asks the event loop to clean up a request and return
   856  // all failed retrieval tasks to the scheduler for reassignment.
   857  func (s *skeleton) scheduleRevertRequest(req *headerRequest) {
   858  	select {
   859  	case req.revert <- req:
   860  		// Sync event loop notified
   861  	case <-req.cancel:
   862  		// Sync cycle got cancelled
   863  	case <-req.stale:
   864  		// Request already reverted
   865  	}
   866  }
   867  
   868  // revertRequest cleans up a request and returns all failed retrieval tasks to
   869  // the scheduler for reassignment.
   870  //
   871  // Note, this needs to run on the event runloop thread to reschedule to idle peers.
   872  // On peer threads, use scheduleRevertRequest.
   873  func (s *skeleton) revertRequest(req *headerRequest) {
   874  	log.Trace("Reverting header request", "peer", req.peer, "reqid", req.id)
   875  	select {
   876  	case <-req.stale:
   877  		log.Trace("Header request already reverted", "peer", req.peer, "reqid", req.id)
   878  		return
   879  	default:
   880  	}
   881  	close(req.stale)
   882  
   883  	// Remove the request from the tracked set
   884  	delete(s.requests, req.id)
   885  
   886  	// Remove the request from the tracked set and mark the task as not-pending,
   887  	// ready for rescheduling
   888  	s.scratchOwners[(s.scratchHead-req.head)/requestHeaders] = ""
   889  }
   890  
   891  func (s *skeleton) processResponse(res *headerResponse) (linked bool, merged bool) {
   892  	res.peer.log.Trace("Processing header response", "head", res.headers[0].Number, "hash", res.headers[0].Hash(), "count", len(res.headers))
   893  
   894  	// Whether the response is valid, we can mark the peer as idle and notify
   895  	// the scheduler to assign a new task. If the response is invalid, we'll
   896  	// drop the peer in a bit.
   897  	s.idles[res.peer.id] = res.peer
   898  
   899  	// Ensure the response is for a valid request
   900  	if _, ok := s.requests[res.reqid]; !ok {
   901  		// Some internal accounting is broken. A request either times out or it
   902  		// gets fulfilled successfully. It should not be possible to deliver a
   903  		// response to a non-existing request.
   904  		res.peer.log.Error("Unexpected header packet")
   905  		return false, false
   906  	}
   907  	delete(s.requests, res.reqid)
   908  
   909  	// Insert the delivered headers into the scratch space independent of the
   910  	// content or continuation; those will be validated in a moment
   911  	head := res.headers[0].Number.Uint64()
   912  	copy(s.scratchSpace[s.scratchHead-head:], res.headers)
   913  
   914  	// If there's still a gap in the head of the scratch space, abort
   915  	if s.scratchSpace[0] == nil {
   916  		return false, false
   917  	}
   918  	// Try to consume any head headers, validating the boundary conditions
   919  	batch := s.db.NewBatch()
   920  	for s.scratchSpace[0] != nil {
   921  		// Next batch of headers available, cross-reference with the subchain
   922  		// we are extending and either accept or discard
   923  		if s.progress.Subchains[0].Next != s.scratchSpace[0].Hash() {
   924  			// Print a log messages to track what's going on
   925  			tail := s.progress.Subchains[0].Tail
   926  			want := s.progress.Subchains[0].Next
   927  			have := s.scratchSpace[0].Hash()
   928  
   929  			log.Warn("Invalid skeleton headers", "peer", s.scratchOwners[0], "number", tail-1, "want", want, "have", have)
   930  
   931  			// The peer delivered junk, or at least not the subchain we are
   932  			// syncing to. Free up the scratch space and assignment, reassign
   933  			// and drop the original peer.
   934  			for i := 0; i < requestHeaders; i++ {
   935  				s.scratchSpace[i] = nil
   936  			}
   937  			s.drop(s.scratchOwners[0])
   938  			s.scratchOwners[0] = ""
   939  			break
   940  		}
   941  		// Scratch delivery matches required subchain, deliver the batch of
   942  		// headers and push the subchain forward
   943  		var consumed int
   944  		for _, header := range s.scratchSpace[:requestHeaders] {
   945  			if header != nil { // nil when the genesis is reached
   946  				consumed++
   947  
   948  				rawdb.WriteSkeletonHeader(batch, header)
   949  				s.pulled++
   950  
   951  				s.progress.Subchains[0].Tail--
   952  				s.progress.Subchains[0].Next = header.ParentHash
   953  
   954  				// If we've reached an existing block in the chain, stop retrieving
   955  				// headers. Note, if we want to support light clients with the same
   956  				// code we'd need to switch here based on the downloader mode. That
   957  				// said, there's no such functionality for now, so don't complicate.
   958  				//
   959  				// In the case of full sync it would be enough to check for the body,
   960  				// but even a full syncing node will generate a receipt once block
   961  				// processing is done, so it's just one more "needless" check.
   962  				//
   963  				// The weird cascading checks are done to minimize the database reads.
   964  				linked = rawdb.HasHeader(s.db, header.ParentHash, header.Number.Uint64()-1) &&
   965  					rawdb.HasBody(s.db, header.ParentHash, header.Number.Uint64()-1) &&
   966  					rawdb.HasReceipts(s.db, header.ParentHash, header.Number.Uint64()-1)
   967  				if linked {
   968  					break
   969  				}
   970  			}
   971  		}
   972  		head := s.progress.Subchains[0].Head
   973  		tail := s.progress.Subchains[0].Tail
   974  		next := s.progress.Subchains[0].Next
   975  
   976  		log.Trace("Primary subchain extended", "head", head, "tail", tail, "next", next)
   977  
   978  		// If the beacon chain was linked to the local chain, completely swap out
   979  		// all internal progress and abort header synchronization.
   980  		if linked {
   981  			// Linking into the local chain should also mean that there are no
   982  			// leftover subchains, but in the case of importing the blocks via
   983  			// the engine API, we will not push the subchains forward. This will
   984  			// lead to a gap between an old sync cycle and a future one.
   985  			if subchains := len(s.progress.Subchains); subchains > 1 {
   986  				switch {
   987  				// If there are only 2 subchains - the current one and an older
   988  				// one - and the old one consists of a single block, then it's
   989  				// the expected new sync cycle after some propagated blocks. Log
   990  				// it for debugging purposes, explicitly clean and don't escalate.
   991  				case subchains == 2 && s.progress.Subchains[1].Head == s.progress.Subchains[1].Tail:
   992  					// Remove the leftover skeleton header associated with old
   993  					// skeleton chain only if it's not covered by the current
   994  					// skeleton range.
   995  					if s.progress.Subchains[1].Head < s.progress.Subchains[0].Tail {
   996  						log.Debug("Cleaning previous beacon sync state", "head", s.progress.Subchains[1].Head)
   997  						rawdb.DeleteSkeletonHeader(batch, s.progress.Subchains[1].Head)
   998  					}
   999  					// Drop the leftover skeleton chain since it's stale.
  1000  					s.progress.Subchains = s.progress.Subchains[:1]
  1001  
  1002  				// If we have more than one header or more than one leftover chain,
  1003  				// the syncer's internal state is corrupted. Do try to fix it, but
  1004  				// be very vocal about the fault.
  1005  				default:
  1006  					var context []interface{}
  1007  
  1008  					for i := range s.progress.Subchains[1:] {
  1009  						context = append(context, fmt.Sprintf("stale_head_%d", i+1))
  1010  						context = append(context, s.progress.Subchains[i+1].Head)
  1011  						context = append(context, fmt.Sprintf("stale_tail_%d", i+1))
  1012  						context = append(context, s.progress.Subchains[i+1].Tail)
  1013  						context = append(context, fmt.Sprintf("stale_next_%d", i+1))
  1014  						context = append(context, s.progress.Subchains[i+1].Next)
  1015  					}
  1016  					log.Error("Cleaning spurious beacon sync leftovers", context...)
  1017  					s.progress.Subchains = s.progress.Subchains[:1]
  1018  
  1019  					// Note, here we didn't actually delete the headers at all,
  1020  					// just the metadata. We could implement a cleanup mechanism,
  1021  					// but further modifying corrupted state is kind of asking
  1022  					// for it. Unless there's a good enough reason to risk it,
  1023  					// better to live with the small database junk.
  1024  				}
  1025  			}
  1026  			break
  1027  		}
  1028  		// Batch of headers consumed, shift the download window forward
  1029  		copy(s.scratchSpace, s.scratchSpace[requestHeaders:])
  1030  		for i := 0; i < requestHeaders; i++ {
  1031  			s.scratchSpace[scratchHeaders-i-1] = nil
  1032  		}
  1033  		copy(s.scratchOwners, s.scratchOwners[1:])
  1034  		s.scratchOwners[scratchHeaders/requestHeaders-1] = ""
  1035  
  1036  		s.scratchHead -= uint64(consumed)
  1037  
  1038  		// If the subchain extended into the next subchain, we need to handle
  1039  		// the overlap. Since there could be many overlaps (come on), do this
  1040  		// in a loop.
  1041  		for len(s.progress.Subchains) > 1 && s.progress.Subchains[1].Head >= s.progress.Subchains[0].Tail {
  1042  			// Extract some stats from the second subchain
  1043  			head := s.progress.Subchains[1].Head
  1044  			tail := s.progress.Subchains[1].Tail
  1045  			next := s.progress.Subchains[1].Next
  1046  
  1047  			// Since we just overwrote part of the next subchain, we need to trim
  1048  			// its head independent of matching or mismatching content
  1049  			if s.progress.Subchains[1].Tail >= s.progress.Subchains[0].Tail {
  1050  				// Fully overwritten, get rid of the subchain as a whole
  1051  				log.Debug("Previous subchain fully overwritten", "head", head, "tail", tail, "next", next)
  1052  				s.progress.Subchains = append(s.progress.Subchains[:1], s.progress.Subchains[2:]...)
  1053  				continue
  1054  			} else {
  1055  				// Partially overwritten, trim the head to the overwritten size
  1056  				log.Debug("Previous subchain partially overwritten", "head", head, "tail", tail, "next", next)
  1057  				s.progress.Subchains[1].Head = s.progress.Subchains[0].Tail - 1
  1058  			}
  1059  			// If the old subchain is an extension of the new one, merge the two
  1060  			// and let the skeleton syncer restart (to clean internal state)
  1061  			if rawdb.ReadSkeletonHeader(s.db, s.progress.Subchains[1].Head).Hash() == s.progress.Subchains[0].Next {
  1062  				log.Debug("Previous subchain merged", "head", head, "tail", tail, "next", next)
  1063  				s.progress.Subchains[0].Tail = s.progress.Subchains[1].Tail
  1064  				s.progress.Subchains[0].Next = s.progress.Subchains[1].Next
  1065  
  1066  				s.progress.Subchains = append(s.progress.Subchains[:1], s.progress.Subchains[2:]...)
  1067  				merged = true
  1068  			}
  1069  		}
  1070  		// If subchains were merged, all further available headers in the scratch
  1071  		// space are invalid since we skipped ahead. Stop processing the scratch
  1072  		// space to avoid dropping peers thinking they delivered invalid data.
  1073  		if merged {
  1074  			break
  1075  		}
  1076  	}
  1077  	s.saveSyncStatus(batch)
  1078  	if err := batch.Write(); err != nil {
  1079  		log.Crit("Failed to write skeleton headers and progress", "err", err)
  1080  	}
  1081  	// Print a progress report making the UX a bit nicer
  1082  	left := s.progress.Subchains[0].Tail - 1
  1083  	if linked {
  1084  		left = 0
  1085  	}
  1086  	if time.Since(s.logged) > 8*time.Second || left == 0 {
  1087  		s.logged = time.Now()
  1088  
  1089  		if s.pulled == 0 {
  1090  			log.Info("Beacon sync starting", "left", left)
  1091  		} else {
  1092  			eta := float64(time.Since(s.started)) / float64(s.pulled) * float64(left)
  1093  			log.Info("Syncing beacon headers", "downloaded", s.pulled, "left", left, "eta", common.PrettyDuration(eta))
  1094  		}
  1095  	}
  1096  	return linked, merged
  1097  }
  1098  
  1099  // cleanStales removes previously synced beacon headers that have become stale
  1100  // due to the downloader backfilling past the tracked tail.
  1101  func (s *skeleton) cleanStales(filled *types.Header) error {
  1102  	number := filled.Number.Uint64()
  1103  	log.Trace("Cleaning stale beacon headers", "filled", number, "hash", filled.Hash())
  1104  
  1105  	// If the filled header is below the linked subchain, something's
  1106  	// corrupted internally. Report and error and refuse to do anything.
  1107  	if number < s.progress.Subchains[0].Tail {
  1108  		return fmt.Errorf("filled header below beacon header tail: %d < %d", number, s.progress.Subchains[0].Tail)
  1109  	}
  1110  	// Subchain seems trimmable, push the tail forward up to the last
  1111  	// filled header and delete everything before it - if available. In
  1112  	// case we filled past the head, recreate the subchain with a new
  1113  	// head to keep it consistent with the data on disk.
  1114  	var (
  1115  		start = s.progress.Subchains[0].Tail // start deleting from the first known header
  1116  		end   = number                       // delete until the requested threshold
  1117  		batch = s.db.NewBatch()
  1118  	)
  1119  	s.progress.Subchains[0].Tail = number
  1120  	s.progress.Subchains[0].Next = filled.ParentHash
  1121  
  1122  	if s.progress.Subchains[0].Head < number {
  1123  		// If more headers were filled than available, push the entire
  1124  		// subchain forward to keep tracking the node's block imports
  1125  		end = s.progress.Subchains[0].Head + 1 // delete the entire original range, including the head
  1126  		s.progress.Subchains[0].Head = number  // assign a new head (tail is already assigned to this)
  1127  
  1128  		// The entire original skeleton chain was deleted and a new one
  1129  		// defined. Make sure the new single-header chain gets pushed to
  1130  		// disk to keep internal state consistent.
  1131  		rawdb.WriteSkeletonHeader(batch, filled)
  1132  	}
  1133  	// Execute the trimming and the potential rewiring of the progress
  1134  	s.saveSyncStatus(batch)
  1135  	for n := start; n < end; n++ {
  1136  		// If the batch grew too big, flush it and continue with a new batch.
  1137  		// The catch is that the sync metadata needs to reflect the actually
  1138  		// flushed state, so temporarily change the subchain progress and
  1139  		// revert after the flush.
  1140  		if batch.ValueSize() >= ethdb.IdealBatchSize {
  1141  			tmpTail := s.progress.Subchains[0].Tail
  1142  			tmpNext := s.progress.Subchains[0].Next
  1143  
  1144  			s.progress.Subchains[0].Tail = n
  1145  			s.progress.Subchains[0].Next = rawdb.ReadSkeletonHeader(s.db, n).ParentHash
  1146  			s.saveSyncStatus(batch)
  1147  
  1148  			if err := batch.Write(); err != nil {
  1149  				log.Crit("Failed to write beacon trim data", "err", err)
  1150  			}
  1151  			batch.Reset()
  1152  
  1153  			s.progress.Subchains[0].Tail = tmpTail
  1154  			s.progress.Subchains[0].Next = tmpNext
  1155  			s.saveSyncStatus(batch)
  1156  		}
  1157  		rawdb.DeleteSkeletonHeader(batch, n)
  1158  	}
  1159  	if err := batch.Write(); err != nil {
  1160  		log.Crit("Failed to write beacon trim data", "err", err)
  1161  	}
  1162  	return nil
  1163  }
  1164  
  1165  // Bounds retrieves the current head and tail tracked by the skeleton syncer
  1166  // and optionally the last known finalized header if any was announced and if
  1167  // it is still in the sync range. This method is used by the backfiller, whose
  1168  // life cycle is controlled by the skeleton syncer.
  1169  //
  1170  // Note, the method will not use the internal state of the skeleton, but will
  1171  // rather blindly pull stuff from the database. This is fine, because the back-
  1172  // filler will only run when the skeleton chain is fully downloaded and stable.
  1173  // There might be new heads appended, but those are atomic from the perspective
  1174  // of this method. Any head reorg will first tear down the backfiller and only
  1175  // then make the modification.
  1176  func (s *skeleton) Bounds() (head *types.Header, tail *types.Header, final *types.Header, err error) {
  1177  	// Read the current sync progress from disk and figure out the current head.
  1178  	// Although there's a lot of error handling here, these are mostly as sanity
  1179  	// checks to avoid crashing if a programming error happens. These should not
  1180  	// happen in live code.
  1181  	status := rawdb.ReadSkeletonSyncStatus(s.db)
  1182  	if len(status) == 0 {
  1183  		return nil, nil, nil, errors.New("beacon sync not yet started")
  1184  	}
  1185  	progress := new(skeletonProgress)
  1186  	if err := json.Unmarshal(status, progress); err != nil {
  1187  		return nil, nil, nil, err
  1188  	}
  1189  	head = rawdb.ReadSkeletonHeader(s.db, progress.Subchains[0].Head)
  1190  	if head == nil {
  1191  		return nil, nil, nil, fmt.Errorf("head skeleton header %d is missing", progress.Subchains[0].Head)
  1192  	}
  1193  	tail = rawdb.ReadSkeletonHeader(s.db, progress.Subchains[0].Tail)
  1194  	if tail == nil {
  1195  		return nil, nil, nil, fmt.Errorf("tail skeleton header %d is missing", progress.Subchains[0].Tail)
  1196  	}
  1197  	if progress.Finalized != nil && tail.Number.Uint64() <= *progress.Finalized && *progress.Finalized <= head.Number.Uint64() {
  1198  		final = rawdb.ReadSkeletonHeader(s.db, *progress.Finalized)
  1199  		if final == nil {
  1200  			return nil, nil, nil, fmt.Errorf("finalized skeleton header %d is missing", *progress.Finalized)
  1201  		}
  1202  	}
  1203  	return head, tail, final, nil
  1204  }
  1205  
  1206  // Header retrieves a specific header tracked by the skeleton syncer. This method
  1207  // is meant to be used by the backfiller, whose life cycle is controlled by the
  1208  // skeleton syncer.
  1209  //
  1210  // Note, outside the permitted runtimes, this method might return nil results and
  1211  // subsequent calls might return headers from different chains.
  1212  func (s *skeleton) Header(number uint64) *types.Header {
  1213  	return rawdb.ReadSkeletonHeader(s.db, number)
  1214  }