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