github.com/skoak/go-ethereum@v1.9.7/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/ethereum/go-ethereum/common"
    30  	"github.com/ethereum/go-ethereum/consensus"
    31  	"github.com/ethereum/go-ethereum/core/rawdb"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/ethdb"
    34  	"github.com/ethereum/go-ethereum/log"
    35  	"github.com/ethereum/go-ethereum/params"
    36  	lru "github.com/hashicorp/golang-lru"
    37  )
    38  
    39  const (
    40  	headerCacheLimit = 512
    41  	tdCacheLimit     = 1024
    42  	numberCacheLimit = 2048
    43  )
    44  
    45  // HeaderChain implements the basic block header chain logic that is shared by
    46  // core.BlockChain and light.LightChain. It is not usable in itself, only as
    47  // a part of either structure.
    48  // It is not thread safe either, the encapsulating chain structures should do
    49  // the necessary mutex locking/unlocking.
    50  type HeaderChain struct {
    51  	config *params.ChainConfig
    52  
    53  	chainDb       ethdb.Database
    54  	genesisHeader *types.Header
    55  
    56  	currentHeader     atomic.Value // Current head of the header chain (may be above the block chain!)
    57  	currentHeaderHash common.Hash  // Hash of the current head of the header chain (prevent recomputing all the time)
    58  
    59  	headerCache *lru.Cache // Cache for the most recent block headers
    60  	tdCache     *lru.Cache // Cache for the most recent block total difficulties
    61  	numberCache *lru.Cache // Cache for the most recent block numbers
    62  
    63  	procInterrupt func() bool
    64  
    65  	rand   *mrand.Rand
    66  	engine consensus.Engine
    67  }
    68  
    69  // NewHeaderChain creates a new HeaderChain structure.
    70  //  getValidator should return the parent's validator
    71  //  procInterrupt points to the parent's interrupt semaphore
    72  //  wg points to the parent's shutdown wait group
    73  func NewHeaderChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, procInterrupt func() bool) (*HeaderChain, error) {
    74  	headerCache, _ := lru.New(headerCacheLimit)
    75  	tdCache, _ := lru.New(tdCacheLimit)
    76  	numberCache, _ := lru.New(numberCacheLimit)
    77  
    78  	// Seed a fast but crypto originating random generator
    79  	seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
    80  	if err != nil {
    81  		return nil, err
    82  	}
    83  
    84  	hc := &HeaderChain{
    85  		config:        config,
    86  		chainDb:       chainDb,
    87  		headerCache:   headerCache,
    88  		tdCache:       tdCache,
    89  		numberCache:   numberCache,
    90  		procInterrupt: procInterrupt,
    91  		rand:          mrand.New(mrand.NewSource(seed.Int64())),
    92  		engine:        engine,
    93  	}
    94  
    95  	hc.genesisHeader = hc.GetHeaderByNumber(0)
    96  	if hc.genesisHeader == nil {
    97  		return nil, ErrNoGenesis
    98  	}
    99  
   100  	hc.currentHeader.Store(hc.genesisHeader)
   101  	if head := rawdb.ReadHeadBlockHash(chainDb); head != (common.Hash{}) {
   102  		if chead := hc.GetHeaderByHash(head); chead != nil {
   103  			hc.currentHeader.Store(chead)
   104  		}
   105  	}
   106  	hc.currentHeaderHash = hc.CurrentHeader().Hash()
   107  	headHeaderGauge.Update(hc.CurrentHeader().Number.Int64())
   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  		headHeaderGauge.Update(header.Number.Int64())
   190  
   191  		status = CanonStatTy
   192  	} else {
   193  		status = SideStatTy
   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  	for i := 1; i < len(chain); i++ {
   211  		if chain[i].Number.Uint64() != chain[i-1].Number.Uint64()+1 || chain[i].ParentHash != chain[i-1].Hash() {
   212  			// Chain broke ancestry, log a message (programming error) and skip insertion
   213  			log.Error("Non contiguous header insert", "number", chain[i].Number, "hash", chain[i].Hash(),
   214  				"parent", chain[i].ParentHash, "prevnumber", chain[i-1].Number, "prevhash", chain[i-1].Hash())
   215  
   216  			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,
   217  				chain[i-1].Hash().Bytes()[:4], i, chain[i].Number, chain[i].Hash().Bytes()[:4], chain[i].ParentHash[:4])
   218  		}
   219  	}
   220  
   221  	// Generate the list of seal verification requests, and start the parallel verifier
   222  	seals := make([]bool, len(chain))
   223  	if checkFreq != 0 {
   224  		// In case of checkFreq == 0 all seals are left false.
   225  		for i := 0; i < len(seals)/checkFreq; i++ {
   226  			index := i*checkFreq + hc.rand.Intn(checkFreq)
   227  			if index >= len(seals) {
   228  				index = len(seals) - 1
   229  			}
   230  			seals[index] = true
   231  		}
   232  		// Last should always be verified to avoid junk.
   233  		seals[len(seals)-1] = true
   234  	}
   235  
   236  	abort, results := hc.engine.VerifyHeaders(hc, chain, seals)
   237  	defer close(abort)
   238  
   239  	// Iterate over the headers and ensure they all check out
   240  	for i, header := range chain {
   241  		// If the chain is terminating, stop processing blocks
   242  		if hc.procInterrupt() {
   243  			log.Debug("Premature abort during headers verification")
   244  			return 0, errors.New("aborted")
   245  		}
   246  		// If the header is a banned one, straight out abort
   247  		if BadHashes[header.Hash()] {
   248  			return i, ErrBlacklistedHash
   249  		}
   250  		// Otherwise wait for headers checks and ensure they pass
   251  		if err := <-results; err != nil {
   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  		hash := header.Hash()
   279  		if hc.HasHeader(hash, header.Number.Uint64()) {
   280  			externTd := hc.GetTd(hash, header.Number.Uint64())
   281  			localTd := hc.GetTd(hc.currentHeaderHash, hc.CurrentHeader().Number.Uint64())
   282  			if externTd == nil || externTd.Cmp(localTd) <= 0 {
   283  				stats.ignored++
   284  				continue
   285  			}
   286  		}
   287  		if err := writeHeader(header); err != nil {
   288  			return i, err
   289  		}
   290  		stats.processed++
   291  	}
   292  	// Report some public statistics so the user has a clue what's going on
   293  	last := chain[len(chain)-1]
   294  
   295  	context := []interface{}{
   296  		"count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
   297  		"number", last.Number, "hash", last.Hash(),
   298  	}
   299  	if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute {
   300  		context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...)
   301  	}
   302  	if stats.ignored > 0 {
   303  		context = append(context, []interface{}{"ignored", stats.ignored}...)
   304  	}
   305  	log.Info("Imported new block headers", context...)
   306  
   307  	return 0, nil
   308  }
   309  
   310  // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
   311  // hash, fetching towards the genesis block.
   312  func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
   313  	// Get the origin header from which to fetch
   314  	header := hc.GetHeaderByHash(hash)
   315  	if header == nil {
   316  		return nil
   317  	}
   318  	// Iterate the headers until enough is collected or the genesis reached
   319  	chain := make([]common.Hash, 0, max)
   320  	for i := uint64(0); i < max; i++ {
   321  		next := header.ParentHash
   322  		if header = hc.GetHeader(next, header.Number.Uint64()-1); header == nil {
   323  			break
   324  		}
   325  		chain = append(chain, next)
   326  		if header.Number.Sign() == 0 {
   327  			break
   328  		}
   329  	}
   330  	return chain
   331  }
   332  
   333  // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
   334  // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
   335  // number of blocks to be individually checked before we reach the canonical chain.
   336  //
   337  // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
   338  func (hc *HeaderChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
   339  	if ancestor > number {
   340  		return common.Hash{}, 0
   341  	}
   342  	if ancestor == 1 {
   343  		// in this case it is cheaper to just read the header
   344  		if header := hc.GetHeader(hash, number); header != nil {
   345  			return header.ParentHash, number - 1
   346  		} else {
   347  			return common.Hash{}, 0
   348  		}
   349  	}
   350  	for ancestor != 0 {
   351  		if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
   352  			ancestorHash := rawdb.ReadCanonicalHash(hc.chainDb, number-ancestor)
   353  			if rawdb.ReadCanonicalHash(hc.chainDb, number) == hash {
   354  				number -= ancestor
   355  				return ancestorHash, number
   356  			}
   357  		}
   358  		if *maxNonCanonical == 0 {
   359  			return common.Hash{}, 0
   360  		}
   361  		*maxNonCanonical--
   362  		ancestor--
   363  		header := hc.GetHeader(hash, number)
   364  		if header == nil {
   365  			return common.Hash{}, 0
   366  		}
   367  		hash = header.ParentHash
   368  		number--
   369  	}
   370  	return hash, number
   371  }
   372  
   373  // GetTd retrieves a block's total difficulty in the canonical chain from the
   374  // database by hash and number, caching it if found.
   375  func (hc *HeaderChain) GetTd(hash common.Hash, number uint64) *big.Int {
   376  	// Short circuit if the td's already in the cache, retrieve otherwise
   377  	if cached, ok := hc.tdCache.Get(hash); ok {
   378  		return cached.(*big.Int)
   379  	}
   380  	td := rawdb.ReadTd(hc.chainDb, hash, number)
   381  	if td == nil {
   382  		return nil
   383  	}
   384  	// Cache the found body for next time and return
   385  	hc.tdCache.Add(hash, td)
   386  	return td
   387  }
   388  
   389  // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
   390  // database by hash, caching it if found.
   391  func (hc *HeaderChain) GetTdByHash(hash common.Hash) *big.Int {
   392  	number := hc.GetBlockNumber(hash)
   393  	if number == nil {
   394  		return nil
   395  	}
   396  	return hc.GetTd(hash, *number)
   397  }
   398  
   399  // WriteTd stores a block's total difficulty into the database, also caching it
   400  // along the way.
   401  func (hc *HeaderChain) WriteTd(hash common.Hash, number uint64, td *big.Int) error {
   402  	rawdb.WriteTd(hc.chainDb, hash, number, td)
   403  	hc.tdCache.Add(hash, new(big.Int).Set(td))
   404  	return nil
   405  }
   406  
   407  // GetHeader retrieves a block header from the database by hash and number,
   408  // caching it if found.
   409  func (hc *HeaderChain) GetHeader(hash common.Hash, number uint64) *types.Header {
   410  	// Short circuit if the header's already in the cache, retrieve otherwise
   411  	if header, ok := hc.headerCache.Get(hash); ok {
   412  		return header.(*types.Header)
   413  	}
   414  	header := rawdb.ReadHeader(hc.chainDb, hash, number)
   415  	if header == nil {
   416  		return nil
   417  	}
   418  	// Cache the found header for next time and return
   419  	hc.headerCache.Add(hash, header)
   420  	return header
   421  }
   422  
   423  // GetHeaderByHash retrieves a block header from the database by hash, caching it if
   424  // found.
   425  func (hc *HeaderChain) GetHeaderByHash(hash common.Hash) *types.Header {
   426  	number := hc.GetBlockNumber(hash)
   427  	if number == nil {
   428  		return nil
   429  	}
   430  	return hc.GetHeader(hash, *number)
   431  }
   432  
   433  // HasHeader checks if a block header is present in the database or not.
   434  func (hc *HeaderChain) HasHeader(hash common.Hash, number uint64) bool {
   435  	if hc.numberCache.Contains(hash) || hc.headerCache.Contains(hash) {
   436  		return true
   437  	}
   438  	return rawdb.HasHeader(hc.chainDb, hash, number)
   439  }
   440  
   441  // GetHeaderByNumber retrieves a block header from the database by number,
   442  // caching it (associated with its hash) if found.
   443  func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
   444  	hash := rawdb.ReadCanonicalHash(hc.chainDb, number)
   445  	if hash == (common.Hash{}) {
   446  		return nil
   447  	}
   448  	return hc.GetHeader(hash, number)
   449  }
   450  
   451  func (hc *HeaderChain) GetCanonicalHash(number uint64) common.Hash {
   452  	return rawdb.ReadCanonicalHash(hc.chainDb, number)
   453  }
   454  
   455  // CurrentHeader retrieves the current head header of the canonical chain. The
   456  // header is retrieved from the HeaderChain's internal cache.
   457  func (hc *HeaderChain) CurrentHeader() *types.Header {
   458  	return hc.currentHeader.Load().(*types.Header)
   459  }
   460  
   461  // SetCurrentHeader sets the current head header of the canonical chain.
   462  func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
   463  	rawdb.WriteHeadHeaderHash(hc.chainDb, head.Hash())
   464  
   465  	hc.currentHeader.Store(head)
   466  	hc.currentHeaderHash = head.Hash()
   467  	headHeaderGauge.Update(head.Number.Int64())
   468  }
   469  
   470  type (
   471  	// UpdateHeadBlocksCallback is a callback function that is called by SetHead
   472  	// before head header is updated.
   473  	UpdateHeadBlocksCallback func(ethdb.KeyValueWriter, *types.Header)
   474  
   475  	// DeleteBlockContentCallback is a callback function that is called by SetHead
   476  	// before each header is deleted.
   477  	DeleteBlockContentCallback func(ethdb.KeyValueWriter, common.Hash, uint64)
   478  )
   479  
   480  // SetHead rewinds the local chain to a new head. Everything above the new head
   481  // will be deleted and the new one set.
   482  func (hc *HeaderChain) SetHead(head uint64, updateFn UpdateHeadBlocksCallback, delFn DeleteBlockContentCallback) {
   483  	var (
   484  		parentHash common.Hash
   485  		batch      = hc.chainDb.NewBatch()
   486  	)
   487  	for hdr := hc.CurrentHeader(); hdr != nil && hdr.Number.Uint64() > head; hdr = hc.CurrentHeader() {
   488  		hash, num := hdr.Hash(), hdr.Number.Uint64()
   489  
   490  		// Rewind block chain to new head.
   491  		parent := hc.GetHeader(hdr.ParentHash, num-1)
   492  		if parent == nil {
   493  			parent = hc.genesisHeader
   494  		}
   495  		parentHash = hdr.ParentHash
   496  		// Notably, since geth has the possibility for setting the head to a low
   497  		// height which is even lower than ancient head.
   498  		// In order to ensure that the head is always no higher than the data in
   499  		// the database(ancient store or active store), we need to update head
   500  		// first then remove the relative data from the database.
   501  		//
   502  		// Update head first(head fast block, head full block) before deleting the data.
   503  		if updateFn != nil {
   504  			updateFn(hc.chainDb, parent)
   505  		}
   506  		// Update head header then.
   507  		rawdb.WriteHeadHeaderHash(hc.chainDb, parentHash)
   508  
   509  		// Remove the relative data from the database.
   510  		if delFn != nil {
   511  			delFn(batch, hash, num)
   512  		}
   513  		// Rewind header chain to new head.
   514  		rawdb.DeleteHeader(batch, hash, num)
   515  		rawdb.DeleteTd(batch, hash, num)
   516  		rawdb.DeleteCanonicalHash(batch, num)
   517  
   518  		hc.currentHeader.Store(parent)
   519  		hc.currentHeaderHash = parentHash
   520  		headHeaderGauge.Update(parent.Number.Int64())
   521  	}
   522  	batch.Write()
   523  
   524  	// Clear out any stale content from the caches
   525  	hc.headerCache.Purge()
   526  	hc.tdCache.Purge()
   527  	hc.numberCache.Purge()
   528  }
   529  
   530  // SetGenesis sets a new genesis block header for the chain
   531  func (hc *HeaderChain) SetGenesis(head *types.Header) {
   532  	hc.genesisHeader = head
   533  }
   534  
   535  // Config retrieves the header chain's chain configuration.
   536  func (hc *HeaderChain) Config() *params.ChainConfig { return hc.config }
   537  
   538  // Engine retrieves the header chain's consensus engine.
   539  func (hc *HeaderChain) Engine() consensus.Engine { return hc.engine }
   540  
   541  // GetBlock implements consensus.ChainReader, and returns nil for every input as
   542  // a header chain does not have blocks available for retrieval.
   543  func (hc *HeaderChain) GetBlock(hash common.Hash, number uint64) *types.Block {
   544  	return nil
   545  }