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