github.com/theQRL/go-zond@v0.2.1/core/headerchain.go (about)

     1  // Copyright 2015 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 core
    18  
    19  import (
    20  	crand "crypto/rand"
    21  	"errors"
    22  	"fmt"
    23  	"math"
    24  	"math/big"
    25  	mrand "math/rand"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/theQRL/go-zond/common"
    30  	"github.com/theQRL/go-zond/common/lru"
    31  	"github.com/theQRL/go-zond/consensus"
    32  	"github.com/theQRL/go-zond/core/rawdb"
    33  	"github.com/theQRL/go-zond/core/types"
    34  	"github.com/theQRL/go-zond/log"
    35  	"github.com/theQRL/go-zond/params"
    36  	"github.com/theQRL/go-zond/rlp"
    37  	"github.com/theQRL/go-zond/zonddb"
    38  )
    39  
    40  const (
    41  	headerCacheLimit = 512
    42  	numberCacheLimit = 2048
    43  )
    44  
    45  // HeaderChain implements the basic block header chain logic. It is not usable in itself, only as
    46  // a part of either structure.
    47  //
    48  // HeaderChain is responsible for maintaining the header chain including the
    49  // header query and updating.
    50  //
    51  // The components maintained by headerchain includes: (1) total difficulty
    52  // (2) header (3) block hash -> number mapping (4) canonical number -> hash mapping
    53  // and (5) head header flag.
    54  //
    55  // It is not thread safe either, the encapsulating chain structures should do
    56  // the necessary mutex locking/unlocking.
    57  type HeaderChain struct {
    58  	config        *params.ChainConfig
    59  	chainDb       zonddb.Database
    60  	genesisHeader *types.Header
    61  
    62  	currentHeader     atomic.Value // Current head of the header chain (may be above the block chain!)
    63  	currentHeaderHash common.Hash  // Hash of the current head of the header chain (prevent recomputing all the time)
    64  
    65  	headerCache *lru.Cache[common.Hash, *types.Header]
    66  	numberCache *lru.Cache[common.Hash, uint64] // most recent block numbers
    67  
    68  	procInterrupt func() bool
    69  
    70  	rand   *mrand.Rand
    71  	engine consensus.Engine
    72  }
    73  
    74  // NewHeaderChain creates a new HeaderChain structure. ProcInterrupt points
    75  // to the parent's interrupt semaphore.
    76  func NewHeaderChain(chainDb zonddb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) {
    77  	// Seed a fast but crypto originating random generator
    78  	seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
    79  	if err != nil {
    80  		return nil, err
    81  	}
    82  	hc := &HeaderChain{
    83  		config:        config,
    84  		chainDb:       chainDb,
    85  		headerCache:   lru.NewCache[common.Hash, *types.Header](headerCacheLimit),
    86  		numberCache:   lru.NewCache[common.Hash, uint64](numberCacheLimit),
    87  		procInterrupt: procInterrupt,
    88  		rand:          mrand.New(mrand.NewSource(seed.Int64())),
    89  		engine:        engine,
    90  	}
    91  	hc.genesisHeader = hc.GetHeaderByNumber(0)
    92  	if hc.genesisHeader == nil {
    93  		return nil, ErrNoGenesis
    94  	}
    95  	hc.currentHeader.Store(hc.genesisHeader)
    96  	if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) {
    97  		if chead := hc.GetHeaderByHash(head); chead != nil {
    98  			hc.currentHeader.Store(chead)
    99  		}
   100  	}
   101  	hc.currentHeaderHash = hc.CurrentHeader().Hash()
   102  	headHeaderGauge.Update(hc.CurrentHeader().Number.Int64())
   103  	return hc, nil
   104  }
   105  
   106  // GetBlockNumber retrieves the block number belonging to the given hash
   107  // from the cache or database
   108  func (hc *HeaderChain) GetBlockNumber(hash common.Hash) *uint64 {
   109  	if cached, ok := hc.numberCache.Get(hash); ok {
   110  		return &cached
   111  	}
   112  	number := rawdb.ReadHeaderNumber(hc.chainDb, hash)
   113  	if number != nil {
   114  		hc.numberCache.Add(hash, *number)
   115  	}
   116  	return number
   117  }
   118  
   119  type headerWriteResult struct {
   120  	status     WriteStatus
   121  	ignored    int
   122  	imported   int
   123  	lastHash   common.Hash
   124  	lastHeader *types.Header
   125  }
   126  
   127  // Reorg reorgs the local canonical chain into the specified chain. The reorg
   128  // can be classified into two cases: (a) extend the local chain (b) switch the
   129  // head to the given header.
   130  func (hc *HeaderChain) Reorg(headers []*types.Header) error {
   131  	// Short circuit if nothing to reorg.
   132  	if len(headers) == 0 {
   133  		return nil
   134  	}
   135  	// If the parent of the (first) block is already the canon header,
   136  	// we don't have to go backwards to delete canon blocks, but simply
   137  	// pile them onto the existing chain. Otherwise, do the necessary
   138  	// reorgs.
   139  	var (
   140  		first = headers[0]
   141  		last  = headers[len(headers)-1]
   142  		batch = hc.chainDb.NewBatch()
   143  	)
   144  	if first.ParentHash != hc.currentHeaderHash {
   145  		// Delete any canonical number assignments above the new head
   146  		for i := last.Number.Uint64() + 1; ; i++ {
   147  			hash := rawdb.ReadCanonicalHash(hc.chainDb, i)
   148  			if hash == (common.Hash{}) {
   149  				break
   150  			}
   151  			rawdb.DeleteCanonicalHash(batch, i)
   152  		}
   153  		// Overwrite any stale canonical number assignments, going
   154  		// backwards from the first header in this import until the
   155  		// cross link between two chains.
   156  		var (
   157  			header     = first
   158  			headNumber = header.Number.Uint64()
   159  			headHash   = header.Hash()
   160  		)
   161  		for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash {
   162  			rawdb.WriteCanonicalHash(batch, headHash, headNumber)
   163  			if headNumber == 0 {
   164  				break // It shouldn't be reached
   165  			}
   166  			headHash, headNumber = header.ParentHash, header.Number.Uint64()-1
   167  			header = hc.GetHeader(headHash, headNumber)
   168  			if header == nil {
   169  				return fmt.Errorf("missing parent %d %x", headNumber, headHash)
   170  			}
   171  		}
   172  	}
   173  	// Extend the canonical chain with the new headers
   174  	for i := 0; i < len(headers)-1; i++ {
   175  		hash := headers[i+1].ParentHash // Save some extra hashing
   176  		num := headers[i].Number.Uint64()
   177  		rawdb.WriteCanonicalHash(batch, hash, num)
   178  		rawdb.WriteHeadHeaderHash(batch, hash)
   179  	}
   180  	// Write the last header
   181  	hash := headers[len(headers)-1].Hash()
   182  	num := headers[len(headers)-1].Number.Uint64()
   183  	rawdb.WriteCanonicalHash(batch, hash, num)
   184  	rawdb.WriteHeadHeaderHash(batch, hash)
   185  
   186  	if err := batch.Write(); err != nil {
   187  		return err
   188  	}
   189  	// Last step update all in-memory head header markers
   190  	hc.currentHeaderHash = last.Hash()
   191  	hc.currentHeader.Store(types.CopyHeader(last))
   192  	headHeaderGauge.Update(last.Number.Int64())
   193  	return nil
   194  }
   195  
   196  // WriteHeaders writes a chain of headers into the local chain, given that the
   197  // parents are already known. The chain head header won't be updated in this
   198  // function, the additional SetCanonical is expected in order to finish the entire
   199  // procedure.
   200  func (hc *HeaderChain) WriteHeaders(headers []*types.Header) (int, error) {
   201  	if len(headers) == 0 {
   202  		return 0, nil
   203  	}
   204  	var (
   205  		inserted    []rawdb.NumberHash // Ephemeral lookup of number/hash for the chain
   206  		parentKnown = true             // Set to true to force hc.HasHeader check the first iteration
   207  		batch       = hc.chainDb.NewBatch()
   208  	)
   209  	for i, header := range headers {
   210  		var hash common.Hash
   211  		// The headers have already been validated at this point, so we already
   212  		// know that it's a contiguous chain, where
   213  		// headers[i].Hash() == headers[i+1].ParentHash
   214  		if i < len(headers)-1 {
   215  			hash = headers[i+1].ParentHash
   216  		} else {
   217  			hash = header.Hash()
   218  		}
   219  		number := header.Number.Uint64()
   220  
   221  		// If the parent was not present, store it
   222  		// If the header is already known, skip it, otherwise store
   223  		alreadyKnown := parentKnown && hc.HasHeader(hash, number)
   224  		if !alreadyKnown {
   225  			rawdb.WriteHeader(batch, header)
   226  			inserted = append(inserted, rawdb.NumberHash{Number: number, Hash: hash})
   227  			hc.headerCache.Add(hash, header)
   228  			hc.numberCache.Add(hash, number)
   229  		}
   230  		parentKnown = alreadyKnown
   231  	}
   232  	// Skip the slow disk write of all headers if interrupted.
   233  	if hc.procInterrupt() {
   234  		log.Debug("Premature abort during headers import")
   235  		return 0, errors.New("aborted")
   236  	}
   237  	// Commit to disk!
   238  	if err := batch.Write(); err != nil {
   239  		log.Crit("Failed to write headers", "error", err)
   240  	}
   241  	return len(inserted), nil
   242  }
   243  
   244  // writeHeadersAndSetHead writes a batch of block headers and applies the last
   245  // header as the chain head if the fork choicer says it's ok to update the chain.
   246  // Note: This method is not concurrent-safe with inserting blocks simultaneously
   247  // into the chain, as side effects caused by reorganisations cannot be emulated
   248  // without the real blocks. Hence, writing headers directly should only be done
   249  // in two scenarios: pure-header mode of operation (light clients), or properly
   250  // separated header/block phases (non-archive clients).
   251  func (hc *HeaderChain) writeHeadersAndSetHead(headers []*types.Header) (*headerWriteResult, error) {
   252  	inserted, err := hc.WriteHeaders(headers)
   253  	if err != nil {
   254  		return nil, err
   255  	}
   256  	var (
   257  		lastHeader = headers[len(headers)-1]
   258  		lastHash   = headers[len(headers)-1].Hash()
   259  		result     = &headerWriteResult{
   260  			status:     NonStatTy,
   261  			ignored:    len(headers) - inserted,
   262  			imported:   inserted,
   263  			lastHash:   lastHash,
   264  			lastHeader: lastHeader,
   265  		}
   266  	)
   267  
   268  	// Special case, all the inserted headers are already on the canonical
   269  	// header chain, skip the reorg operation.
   270  	if hc.GetCanonicalHash(lastHeader.Number.Uint64()) == lastHash && lastHeader.Number.Uint64() <= hc.CurrentHeader().Number.Uint64() {
   271  		return result, nil
   272  	}
   273  	// Apply the reorg operation
   274  	if err := hc.Reorg(headers); err != nil {
   275  		return nil, err
   276  	}
   277  	result.status = CanonStatTy
   278  	return result, nil
   279  }
   280  
   281  func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header) (int, error) {
   282  	// Do a sanity check that the provided chain is actually ordered and linked
   283  	for i := 1; i < len(chain); i++ {
   284  		if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 {
   285  			hash := chain[i].Hash()
   286  			parentHash := chain[i-1].Hash()
   287  			// Chain broke ancestry, log a message (programming error) and skip insertion
   288  			log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", hash,
   289  				"parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", parentHash)
   290  
   291  			return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x..], item %d is #%d [%x..] (parent [%x..])", i-1, chain[i-1].Number,
   292  				parentHash.Bytes()[:4], i, chain[i].Number, hash.Bytes()[:4], chain[i].ParentHash[:4])
   293  		}
   294  	}
   295  	// Start the parallel verifier
   296  	abort, results := hc.engine.VerifyHeaders(hc, chain)
   297  	defer close(abort)
   298  
   299  	// Iterate over the headers and ensure they all check out
   300  	for i := range chain {
   301  		// If the chain is terminating, stop processing blocks
   302  		if hc.procInterrupt() {
   303  			log.Debug("Premature abort during headers verification")
   304  			return 0, errors.New("aborted")
   305  		}
   306  		// Otherwise wait for headers checks and ensure they pass
   307  		if err := <-results; err != nil {
   308  			return i, err
   309  		}
   310  	}
   311  
   312  	return 0, nil
   313  }
   314  
   315  // InsertHeaderChain inserts the given headers and does the reorganisations.
   316  //
   317  // The validity of the headers is NOT CHECKED by this method, i.e. they need to be
   318  // validated by ValidateHeaderChain before calling InsertHeaderChain.
   319  //
   320  // This insert is all-or-nothing. If this returns an error, no headers were written,
   321  // otherwise they were all processed successfully.
   322  //
   323  // The returned 'write status' says if the inserted headers are part of the canonical chain
   324  // or a side chain.
   325  func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, start time.Time) (WriteStatus, error) {
   326  	if hc.procInterrupt() {
   327  		return 0, errors.New("aborted")
   328  	}
   329  	res, err := hc.writeHeadersAndSetHead(chain)
   330  	if err != nil {
   331  		return 0, err
   332  	}
   333  	// Report some public statistics so the user has a clue what's going on
   334  	context := []interface{}{
   335  		"count", res.imported,
   336  		"elapsed", common.PrettyDuration(time.Since(start)),
   337  	}
   338  	if last := res.lastHeader; last != nil {
   339  		context = append(context, "number", last.Number, "hash", res.lastHash)
   340  		if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute {
   341  			context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...)
   342  		}
   343  	}
   344  	if res.ignored > 0 {
   345  		context = append(context, []interface{}{"ignored", res.ignored}...)
   346  	}
   347  	log.Debug("Imported new block headers", context...)
   348  	return res.status, err
   349  }
   350  
   351  // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
   352  // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
   353  // number of blocks to be individually checked before we reach the canonical chain.
   354  //
   355  // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
   356  func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
   357  	if ancestor > number {
   358  		return common.Hash{}, 0
   359  	}
   360  	if ancestor == 1 {
   361  		// in this case it is cheaper to just read the header
   362  		if header := hc.GetHeader(hash, number); header != nil {
   363  			return header.ParentHash, number - 1
   364  		}
   365  		return common.Hash{}, 0
   366  	}
   367  	for ancestor != 0 {
   368  		if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
   369  			ancestorHash := rawdb.ReadCanonicalHash(hc.chainDb, number-ancestor)
   370  			if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
   371  				number -= ancestor
   372  				return ancestorHash, number
   373  			}
   374  		}
   375  		if *maxNonCanonical == 0 {
   376  			return common.Hash{}, 0
   377  		}
   378  		*maxNonCanonical--
   379  		ancestor--
   380  		header := hc.GetHeader(hash, number)
   381  		if header == nil {
   382  			return common.Hash{}, 0
   383  		}
   384  		hash = header.ParentHash
   385  		number--
   386  	}
   387  	return hash, number
   388  }
   389  
   390  // GetHeader retrieves a block header from the database by hash and number,
   391  // caching it if found.
   392  func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
   393  	// Short circuit if the header's already in the cache, retrieve otherwise
   394  	if header, ok := hc.headerCache.Get(hash); ok {
   395  		return header
   396  	}
   397  	header := rawdb.ReadHeader(hc.chainDb, hash, number)
   398  	if header == nil {
   399  		return nil
   400  	}
   401  	// Cache the found header for next time and return
   402  	hc.headerCache.Add(hash, header)
   403  	return header
   404  }
   405  
   406  // GetHeaderByHash retrieves a block header from the database by hash, caching it if
   407  // found.
   408  func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
   409  	number := hc.GetBlockNumber(hash)
   410  	if number == nil {
   411  		return nil
   412  	}
   413  	return hc.GetHeader(hash, *number)
   414  }
   415  
   416  // HasHeader checks if a block header is present in the database or not.
   417  // In theory, if header is present in the database, all relative components
   418  // like td and hash->number should be present too.
   419  func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
   420  	if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
   421  		return true
   422  	}
   423  	return rawdb.HasHeader(hc.chainDb, hash, number)
   424  }
   425  
   426  // GetHeaderByNumber retrieves a block header from the database by number,
   427  // caching it (associated with its hash) if found.
   428  func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
   429  	hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
   430  	if hash == (common.Hash{}) {
   431  		return nil
   432  	}
   433  	return hc.GetHeader(hash, number)
   434  }
   435  
   436  // GetHeadersFrom returns a contiguous segment of headers, in rlp-form, going
   437  // backwards from the given number.
   438  // If the 'number' is higher than the highest local header, this method will
   439  // return a best-effort response, containing the headers that we do have.
   440  func (hc *HeaderChain) GetHeadersFrom(number, count uint64) []rlp.RawValue {
   441  	// If the request is for future headers, we still return the portion of
   442  	// headers that we are able to serve
   443  	if current := hc.CurrentHeader().Number.Uint64(); current < number {
   444  		if count > number-current {
   445  			count -= number - current
   446  			number = current
   447  		} else {
   448  			return nil
   449  		}
   450  	}
   451  	var headers []rlp.RawValue
   452  	// If we have some of the headers in cache already, use that before going to db.
   453  	hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
   454  	if hash == (common.Hash{}) {
   455  		return nil
   456  	}
   457  	for count > 0 {
   458  		header, ok := hc.headerCache.Get(hash)
   459  		if !ok {
   460  			break
   461  		}
   462  		rlpData, _ := rlp.EncodeToBytes(header)
   463  		headers = append(headers, rlpData)
   464  		hash = header.ParentHash
   465  		count--
   466  		number--
   467  	}
   468  	// Read remaining from db
   469  	if count > 0 {
   470  		headers = append(headers, rawdb.ReadHeaderRange(hc.chainDb, number, count)...)
   471  	}
   472  	return headers
   473  }
   474  
   475  func (hc *HeaderChain) GetCanonicalHash(number uint64) common.Hash {
   476  	return rawdb.ReadCanonicalHash(hc.chainDb, number)
   477  }
   478  
   479  // CurrentHeader retrieves the current head header of the canonical chain. The
   480  // header is retrieved from the HeaderChain's internal cache.
   481  func (hc *HeaderChain) CurrentHeader() *types.Header {
   482  	return hc.currentHeader.Load().(*types.Header)
   483  }
   484  
   485  // SetCurrentHeader sets the in-memory head header marker of the canonical chan
   486  // as the given header.
   487  func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
   488  	hc.currentHeader.Store(head)
   489  	hc.currentHeaderHash = head.Hash()
   490  	headHeaderGauge.Update(head.Number.Int64())
   491  }
   492  
   493  type (
   494  	// UpdateHeadBlocksCallback is a callback function that is called by SetHead
   495  	// before head header is updated. The method will return the actual block it
   496  	// updated the head to (missing state) and a flag if setHead should continue
   497  	// rewinding till that forcefully (exceeded ancient limits)
   498  	UpdateHeadBlocksCallback func(zonddb.KeyValueWriter, *types.Header) (*types.Header, bool)
   499  
   500  	// DeleteBlockContentCallback is a callback function that is called by SetHead
   501  	// before each header is deleted.
   502  	DeleteBlockContentCallback func(zonddb.KeyValueWriter, common.Hash, uint64)
   503  )
   504  
   505  // SetHead rewinds the local chain to a new head. Everything above the new head
   506  // will be deleted and the new one set.
   507  func (hc *HeaderChain) SetHead(head uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) {
   508  	hc.setHead(head, 0, updateFn, delFn)
   509  }
   510  
   511  // SetHeadWithTimestamp rewinds the local chain to a new head timestamp. Everything
   512  // above the new head will be deleted and the new one set.
   513  func (hc *HeaderChain) SetHeadWithTimestamp(time uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) {
   514  	hc.setHead(0, time, updateFn, delFn)
   515  }
   516  
   517  // setHead rewinds the local chain to a new head block or a head timestamp.
   518  // Everything above the new head will be deleted and the new one set.
   519  func (hc *HeaderChain) setHead(headBlock uint64, headTime uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) {
   520  	// Sanity check that there's no attempt to undo the genesis block. This is
   521  	// a fairly synthetic case where someone enables a timestamp based fork
   522  	// below the genesis timestamp. It's nice to not allow that instead of the
   523  	// entire chain getting deleted.
   524  	if headTime > 0 && hc.genesisHeader.Time > headTime {
   525  		// Note, a critical error is quite brutal, but we should really not reach
   526  		// this point. Since pre-timestamp based forks it was impossible to have
   527  		// a fork before block 0, the setHead would always work. With timestamp
   528  		// forks it becomes possible to specify below the genesis. That said, the
   529  		// only time we setHead via timestamp is with chain config changes on the
   530  		// startup, so failing hard there is ok.
   531  		log.Crit("Rejecting genesis rewind via timestamp", "target", headTime, "genesis", hc.genesisHeader.Time)
   532  	}
   533  	var (
   534  		parentHash common.Hash
   535  		batch      = hc.chainDb.NewBatch()
   536  		origin     = true
   537  	)
   538  	done := func(header *types.Header) bool {
   539  		if headTime > 0 {
   540  			return header.Time <= headTime
   541  		}
   542  		return header.Number.Uint64() <= headBlock
   543  	}
   544  	for hdr := hc.CurrentHeader(); hdr != nil && !done(hdr); hdr = hc.CurrentHeader() {
   545  		num := hdr.Number.Uint64()
   546  
   547  		// Rewind chain to new head
   548  		parent := hc.GetHeader(hdr.ParentHash, num-1)
   549  		if parent == nil {
   550  			parent = hc.genesisHeader
   551  		}
   552  		parentHash = parent.Hash()
   553  
   554  		// Notably, since gzond has the possibility for setting the head to a low
   555  		// height which is even lower than ancient head.
   556  		// In order to ensure that the head is always no higher than the data in
   557  		// the database (ancient store or active store), we need to update head
   558  		// first then remove the relative data from the database.
   559  		//
   560  		// Update head first(head fast block, head full block) before deleting the data.
   561  		markerBatch := hc.chainDb.NewBatch()
   562  		if updateFn != nil {
   563  			newHead, force := updateFn(markerBatch, parent)
   564  			if force && ((headTime > 0 && newHead.Time < headTime) || (headTime == 0 && newHead.Number.Uint64() < headBlock)) {
   565  				log.Warn("Force rewinding till ancient limit", "head", newHead.Number.Uint64())
   566  				headBlock, headTime = newHead.Number.Uint64(), 0 // Target timestamp passed, continue rewind in block mode (cleaner)
   567  			}
   568  		}
   569  		// Update head header then.
   570  		rawdb.WriteHeadHeaderHash(markerBatch, parentHash)
   571  		if err := markerBatch.Write(); err != nil {
   572  			log.Crit("Failed to update chain markers", "error", err)
   573  		}
   574  		hc.currentHeader.Store(parent)
   575  		hc.currentHeaderHash = parentHash
   576  		headHeaderGauge.Update(parent.Number.Int64())
   577  
   578  		// If this is the first iteration, wipe any leftover data upwards too so
   579  		// we don't end up with dangling daps in the database
   580  		var nums []uint64
   581  		if origin {
   582  			for n := num + 1; len(rawdb.ReadAllHashes(hc.chainDb, n)) > 0; n++ {
   583  				nums = append([]uint64{n}, nums...) // suboptimal, but we don't really expect this path
   584  			}
   585  			origin = false
   586  		}
   587  		nums = append(nums, num)
   588  
   589  		// Remove the related data from the database on all sidechains
   590  		for _, num := range nums {
   591  			// Gather all the side fork hashes
   592  			hashes := rawdb.ReadAllHashes(hc.chainDb, num)
   593  			if len(hashes) == 0 {
   594  				// No hashes in the database whatsoever, probably frozen already
   595  				hashes = append(hashes, hdr.Hash())
   596  			}
   597  			for _, hash := range hashes {
   598  				if delFn != nil {
   599  					delFn(batch, hash, num)
   600  				}
   601  				rawdb.DeleteHeader(batch, hash, num)
   602  			}
   603  			rawdb.DeleteCanonicalHash(batch, num)
   604  		}
   605  	}
   606  	// Flush all accumulated deletions.
   607  	if err := batch.Write(); err != nil {
   608  		log.Crit("Failed to rewind block", "error", err)
   609  	}
   610  	// Clear out any stale content from the caches
   611  	hc.headerCache.Purge()
   612  	hc.numberCache.Purge()
   613  }
   614  
   615  // SetGenesis sets a new genesis block header for the chain
   616  func (hc *HeaderChain) SetGenesis(head *types.Header) {
   617  	hc.genesisHeader = head
   618  }
   619  
   620  // Config retrieves the header chain's chain configuration.
   621  func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }
   622  
   623  // Engine retrieves the header chain's consensus engine.
   624  func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }
   625  
   626  // GetBlock implements consensus.ChainReader, and returns nil for every input as
   627  // a header chain does not have blocks available for retrieval.
   628  func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
   629  	return nil
   630  }