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