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