github.com/intfoundation/intchain@v0.0.0-20220727031208-4316ad31ca73/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  	"github.com/intfoundation/intchain/core/rawdb"
    24  	"github.com/intfoundation/intchain/core/state"
    25  	"math"
    26  	"math/big"
    27  	mrand "math/rand"
    28  	"time"
    29  
    30  	"github.com/hashicorp/golang-lru"
    31  	"github.com/intfoundation/intchain/common"
    32  	"github.com/intfoundation/intchain/consensus"
    33  	"github.com/intfoundation/intchain/core/types"
    34  	"github.com/intfoundation/intchain/intdb"
    35  	"github.com/intfoundation/intchain/log"
    36  	"github.com/intfoundation/intchain/params"
    37  	"sync/atomic"
    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  // It is not thread safe either, the encapsulating chain structures should do
    50  // the necessary mutex locking/unlocking.
    51  type HeaderChain struct {
    52  	config *params.ChainConfig
    53  
    54  	chainDb       intdb.Database
    55  	genesisHeader *types.Header
    56  
    57  	currentHeader     atomic.Value // Current head of the header chain (may be above the block chain!)
    58  	currentHeaderHash common.Hash  // Hash of the current head of the header chain (prevent recomputing all the time)
    59  
    60  	headerCache *lru.Cache // Cache for the most recent block headers
    61  	tdCache     *lru.Cache // Cache for the most recent block total difficulties
    62  	numberCache *lru.Cache // Cache for the most recent block numbers
    63  
    64  	procInterrupt func() bool
    65  
    66  	rand   *mrand.Rand
    67  	engine consensus.Engine
    68  }
    69  
    70  // NewHeaderChain creates a new HeaderChain structure.
    71  //  getValidator should return the parent's validator
    72  //  procInterrupt points to the parent's interrupt semaphore
    73  //  wg points to the parent's shutdown wait group
    74  func NewHeaderChain(chainDb intdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) {
    75  	headerCache, _ := lru.New(headerCacheLimit)
    76  	tdCache, _ := lru.New(tdCacheLimit)
    77  	numberCache, _ := lru.New(numberCacheLimit)
    78  
    79  	// Seed a fast but crypto originating random generator
    80  	seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
    81  	if err != nil {
    82  		return nil, err
    83  	}
    84  
    85  	hc := &HeaderChain{
    86  		config:        config,
    87  		chainDb:       chainDb,
    88  		headerCache:   headerCache,
    89  		tdCache:       tdCache,
    90  		numberCache:   numberCache,
    91  		procInterrupt: procInterrupt,
    92  		rand:          mrand.New(mrand.NewSource(seed.Int64())),
    93  		engine:        engine,
    94  	}
    95  
    96  	hc.genesisHeader = hc.GetHeaderByNumber(0)
    97  	if hc.genesisHeader == nil {
    98  		return nil, ErrNoGenesis
    99  	}
   100  
   101  	hc.currentHeader.Store(hc.genesisHeader)
   102  	if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) {
   103  		if chead := hc.GetHeaderByHash(head); chead != nil {
   104  			hc.currentHeader.Store(chead)
   105  		}
   106  	}
   107  	hc.currentHeaderHash = hc.CurrentHeader().Hash()
   108  
   109  	return hc, nil
   110  }
   111  
   112  // GetBlockNumber retrieves the block number belonging to the given hash
   113  // from the cache or database
   114  func (hc *HeaderChain) GetBlockNumber(hash common.Hash) *uint64 {
   115  	if cached, ok := hc.numberCache.Get(hash); ok {
   116  		number := cached.(uint64)
   117  		return &number
   118  	}
   119  	number := rawdb.ReadHeaderNumber(hc.chainDb, hash)
   120  	if number != nil {
   121  		hc.numberCache.Add(hash, *number)
   122  	}
   123  	return number
   124  }
   125  
   126  // WriteHeader writes a header into the local chain, given that its parent is
   127  // already known. If the total difficulty of the newly inserted header becomes
   128  // greater than the current known TD, the canonical chain is re-routed.
   129  //
   130  // Note: This method is not concurrent-safe with inserting blocks simultaneously
   131  // into the chain, as side effects caused by reorganisations cannot be emulated
   132  // without the real blocks. Hence, writing headers directly should only be done
   133  // in two scenarios: pure-header mode of operation (light clients), or properly
   134  // separated header/block phases (non-archive clients).
   135  func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) {
   136  	// Cache some values to prevent constant recalculation
   137  	var (
   138  		hash   = header.Hash()
   139  		number = header.Number.Uint64()
   140  	)
   141  	// Calculate the total difficulty of the header
   142  	ptd := hc.GetTd(header.ParentHash, number-1)
   143  	if ptd == nil {
   144  		return NonStatTy, consensus.ErrUnknownAncestor
   145  	}
   146  	localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64())
   147  	externTd := new(big.Int).Add(header.Difficulty, ptd)
   148  
   149  	// Irrelevant of the canonical status, write the td and header to the database
   150  	if err := hc.WriteTd(hash, number, externTd); err != nil {
   151  		log.Crit("Failed to write header total difficulty", "err", err)
   152  	}
   153  	rawdb.WriteHeader(hc.chainDb, header)
   154  
   155  	// If the total difficulty is higher than our known, add it to the canonical chain
   156  	// Second clause in the if statement reduces the vulnerability to selfish mining.
   157  	// Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
   158  	if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
   159  		// Delete any canonical number assignments above the new head
   160  		batch := hc.chainDb.NewBatch()
   161  		for i := number + 1; ; i++ {
   162  			hash := rawdb.ReadCanonicalHash(hc.chainDb, i)
   163  			if hash == (common.Hash{}) {
   164  				break
   165  			}
   166  			rawdb.DeleteCanonicalHash(batch, i)
   167  		}
   168  		batch.Write()
   169  
   170  		// Overwrite any stale canonical number assignments
   171  		var (
   172  			headHash   = header.ParentHash
   173  			headNumber = header.Number.Uint64() - 1
   174  			headHeader = hc.GetHeader(headHash, headNumber)
   175  		)
   176  		for rawdb.ReadCanonicalHash(hc.chainDb, headNumber) != headHash {
   177  			rawdb.WriteCanonicalHash(hc.chainDb, headHash, headNumber)
   178  
   179  			headHash = headHeader.ParentHash
   180  			headNumber = headHeader.Number.Uint64() - 1
   181  			headHeader = hc.GetHeader(headHash, headNumber)
   182  		}
   183  		// Extend the canonical chain with the new header
   184  		rawdb.WriteCanonicalHash(hc.chainDb, hash, number)
   185  		rawdb.WriteHeadHeaderHash(hc.chainDb, hash)
   186  
   187  		hc.currentHeaderHash = hash
   188  		hc.currentHeader.Store(types.CopyHeader(header))
   189  
   190  		status = CanonStatTy
   191  	} else {
   192  		status = SideStatTy
   193  	}
   194  
   195  	hc.headerCache.Add(hash, header)
   196  	hc.numberCache.Add(hash, number)
   197  
   198  	return
   199  }
   200  
   201  // WhCallback is a callback function for inserting individual headers.
   202  // A callback is used for two reasons: first, in a LightChain, status should be
   203  // processed and light chain events sent, while in a BlockChain this is not
   204  // necessary since chain events are sent after inserting blocks. Second, the
   205  // header writes should be protected by the parent chain mutex individually.
   206  type WhCallback func(*types.Header) error
   207  
   208  func (hc *HeaderChain) ValidateHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
   209  	// Do a sanity check that the provided chain is actually ordered and linked
   210  	log.Info("(hc *HeaderChain) ValidateHeaderChain 0")
   211  	for i := 1; i < len(chain); i++ {
   212  		if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
   213  			// Chain broke ancestry, log a messge (programming error) and skip insertion
   214  			log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(),
   215  				"parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash())
   216  
   217  			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,
   218  				chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
   219  		}
   220  	}
   221  
   222  	// Generate the list of seal verification requests, and start the parallel verifier
   223  	seals := make([]bool, len(chain))
   224  	for i := 0; i < len(seals)/checkFreq; i++ {
   225  		index := i*checkFreq + hc.rand.Intn(checkFreq)
   226  		if index >= len(seals) {
   227  			index = len(seals) - 1
   228  		}
   229  		seals[index] = true
   230  	}
   231  	seals[len(seals)-1] = true // Last should always be verified to avoid junk
   232  
   233  	abort, results := hc.engine.VerifyHeaders(hc, chain, seals)
   234  	defer close(abort)
   235  
   236  	// Iterate over the headers and ensure they all check out
   237  	for i, header := range chain {
   238  		// If the chain is terminating, stop processing blocks
   239  		if hc.procInterrupt() {
   240  			log.Debug("Premature abort during headers verification")
   241  			log.Info("(hc *HeaderChain) ValidateHeaderChain 1")
   242  			return 0, errors.New("aborted")
   243  		}
   244  		// If the header is a banned one, straight out abort
   245  		if BadHashes[header.Hash()] {
   246  			log.Info("(hc *HeaderChain) ValidateHeaderChain 2")
   247  			return i, ErrBlacklistedHash
   248  		}
   249  		// Otherwise wait for headers checks and ensure they pass
   250  		if err := <-results; err != nil {
   251  			log.Info("(hc *HeaderChain) ValidateHeaderChain 3")
   252  			return i, err
   253  		}
   254  	}
   255  
   256  	return 0, nil
   257  }
   258  
   259  // InsertHeaderChain attempts to insert the given header chain in to the local
   260  // chain, possibly creating a reorg. If an error is returned, it will return the
   261  // index number of the failing header as well an error describing what went wrong.
   262  //
   263  // The verify parameter can be used to fine tune whether nonce verification
   264  // should be done or not. The reason behind the optional check is because some
   265  // of the header retrieval mechanisms already need to verfy nonces, as well as
   266  // because nonces can be verified sparsely, not needing to check each.
   267  func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCallback, start time.Time) (int, error) {
   268  	// Collect some import statistics to report on
   269  	stats := struct{ processed, ignored int }{}
   270  	// All headers passed verification, import them into the database
   271  	for i, header := range chain {
   272  		// Short circuit insertion if shutting down
   273  		if hc.procInterrupt() {
   274  			log.Debug("Premature abort during headers import")
   275  			return i, errors.New("aborted")
   276  		}
   277  		// If the header's already known, skip it, otherwise store
   278  		if hc.HasHeader(header.Hash(), header.Number.Uint64()) {
   279  			stats.ignored++
   280  			continue
   281  		}
   282  		if err := writeHeader(header); err != nil {
   283  			return i, err
   284  		}
   285  		stats.processed++
   286  	}
   287  	// Report some public statistics so the user has a clue what's going on
   288  	last := chain[len(chain)-1]
   289  	log.Info("Imported new block headers", "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
   290  		"number", last.Number, "hash", last.Hash(), "ignored", stats.ignored)
   291  
   292  	return 0, nil
   293  }
   294  
   295  // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
   296  // hash, fetching towards the genesis block.
   297  func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
   298  	// Get the origin header from which to fetch
   299  	header := hc.GetHeaderByHash(hash)
   300  	if header == nil {
   301  		return nil
   302  	}
   303  	// Iterate the headers until enough is collected or the genesis reached
   304  	chain := make([]common.Hash, 0, max)
   305  	for i := uint64(0); i < max; i++ {
   306  		next := header.ParentHash
   307  		if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
   308  			break
   309  		}
   310  		chain = append(chain, next)
   311  		if header.Number.Sign() == 0 {
   312  			break
   313  		}
   314  	}
   315  	return chain
   316  }
   317  
   318  // GetTd retrieves a block's total difficulty in the canonical chain from the
   319  // database by hash and number, caching it if found.
   320  func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
   321  	// Short circuit if the td's already in the cache, retrieve otherwise
   322  	if cached, ok := hc.tdCache.Get(hash); ok {
   323  		return cached.(*big.Int)
   324  	}
   325  	td := rawdb.ReadTd(hc.chainDb, hash, number)
   326  	if td == nil {
   327  		return nil
   328  	}
   329  	// Cache the found body for next time and return
   330  	hc.tdCache.Add(hash, td)
   331  	return td
   332  }
   333  
   334  // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
   335  // database by hash, caching it if found.
   336  func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
   337  	number := hc.GetBlockNumber(hash)
   338  	if number == nil {
   339  		return nil
   340  	}
   341  	return hc.GetTd(hash, *number)
   342  }
   343  
   344  // WriteTd stores a block's total difficulty into the database, also caching it
   345  // along the way.
   346  func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error {
   347  	rawdb.WriteTd(hc.chainDb, hash, number, td)
   348  	hc.tdCache.Add(hash, new(big.Int).Set(td))
   349  	return nil
   350  }
   351  
   352  // GetHeader retrieves a block header from the database by hash and number,
   353  // caching it if found.
   354  func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
   355  	// Short circuit if the header's already in the cache, retrieve otherwise
   356  	if header, ok := hc.headerCache.Get(hash); ok {
   357  		return header.(*types.Header)
   358  	}
   359  	header := rawdb.ReadHeader(hc.chainDb, hash, number)
   360  	if header == nil {
   361  		return nil
   362  	}
   363  	// Cache the found header for next time and return
   364  	hc.headerCache.Add(hash, header)
   365  	return header
   366  }
   367  
   368  // GetHeaderByHash retrieves a block header from the database by hash, caching it if
   369  // found.
   370  func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
   371  	number := hc.GetBlockNumber(hash)
   372  	if number == nil {
   373  		return nil
   374  	}
   375  	return hc.GetHeader(hash, *number)
   376  }
   377  
   378  // HasHeader checks if a block header is present in the database or not.
   379  func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
   380  	if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
   381  		return true
   382  	}
   383  	return rawdb.HasHeader(hc.chainDb, hash, number)
   384  }
   385  
   386  // GetHeaderByNumber retrieves a block header from the database by number,
   387  // caching it (associated with its hash) if found.
   388  func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
   389  	hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
   390  	if hash == (common.Hash{}) {
   391  		return nil
   392  	}
   393  	return hc.GetHeader(hash, number)
   394  }
   395  
   396  // CurrentHeader retrieves the current head header of the canonical chain. The
   397  // header is retrieved from the HeaderChain's internal cache.
   398  func (hc *HeaderChain) CurrentHeader() *types.Header {
   399  	return hc.currentHeader.Load().(*types.Header)
   400  }
   401  
   402  // SetCurrentHeader sets the current head header of the canonical chain.
   403  func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
   404  	rawdb.WriteHeadHeaderHash(hc.chainDb, head.Hash())
   405  
   406  	hc.currentHeader.Store(head)
   407  	hc.currentHeaderHash = head.Hash()
   408  }
   409  
   410  // DeleteCallback is a callback function that is called by SetHead before
   411  // each header is deleted.
   412  type DeleteCallback func(intdb.Writer, common.Hash, uint64)
   413  
   414  // SetHead rewinds the local chain to a new head. Everything above the new head
   415  // will be deleted and the new one set.
   416  func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) {
   417  	height := uint64(0)
   418  
   419  	if hdr := hc.CurrentHeader(); hdr != nil {
   420  		height = hdr.Number.Uint64()
   421  	}
   422  	batch := hc.chainDb.NewBatch()
   423  	for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() {
   424  		hash := hdr.Hash()
   425  		num := hdr.Number.Uint64()
   426  		if delFn != nil {
   427  			delFn(batch, hash, num)
   428  		}
   429  		rawdb.DeleteHeader(batch, hash, num)
   430  		rawdb.DeleteTd(batch, hash, num)
   431  
   432  		hc.currentHeader.Store(hc.GetHeader(hdr.ParentHash, hdr.Number.Uint64()-1))
   433  	}
   434  	// Roll back the canonical chain numbering
   435  	for i := height; i > head; i-- {
   436  		rawdb.DeleteCanonicalHash(batch, i)
   437  	}
   438  	batch.Write()
   439  
   440  	// Clear out any stale content from the caches
   441  	hc.headerCache.Purge()
   442  	hc.tdCache.Purge()
   443  	hc.numberCache.Purge()
   444  
   445  	if hc.CurrentHeader() == nil {
   446  		hc.currentHeader.Store(hc.genesisHeader)
   447  	}
   448  	hc.currentHeaderHash = hc.CurrentHeader().Hash()
   449  
   450  	rawdb.WriteHeadHeaderHash(hc.chainDb, hc.currentHeaderHash)
   451  }
   452  
   453  // SetGenesis sets a new genesis block header for the chain
   454  func (hc *HeaderChain) SetGenesis(head *types.Header) {
   455  	hc.genesisHeader = head
   456  }
   457  
   458  // Config retrieves the header chain's chain configuration.
   459  func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }
   460  
   461  // Engine retrieves the header chain's consensus engine.
   462  func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }
   463  
   464  // GetBlock implements consensus.ChainReader, and returns nil for every input as
   465  // a header chain does not have blocks available for retrieval.
   466  func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
   467  	return nil
   468  }
   469  
   470  // GetBlockByNumber implements consensus.ChainReader, and returns nil for every input as
   471  // a header chain does not have blocks available for retrieval.
   472  func (hc *HeaderChain) GetBlockByNumber(number uint64) *types.Block {
   473  	return nil
   474  }
   475  
   476  // CurrentBlock implements consensus.ChainReader, and returns nil for every input as
   477  ///a header chain does not have blocks available for retrieval.
   478  func (hc *HeaderChain) CurrentBlock() *types.Block {
   479  	return nil
   480  }
   481  
   482  // State implements consensus.ChainReader, and return nil for every input a
   483  func (hc *HeaderChain) State() (*state.StateDB, error) {
   484  	return nil, nil
   485  }