github.com/aquanetwork/aquachain@v1.7.8/core/headerchain.go (about)

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