github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/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  	"math"
    22  	"math/big"
    23  	mrand "math/rand"
    24  	"runtime"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"github.com/ethereumproject/go-ethereum/common"
    30  	"github.com/ethereumproject/go-ethereum/core/types"
    31  	"github.com/ethereumproject/go-ethereum/ethdb"
    32  	"github.com/ethereumproject/go-ethereum/event"
    33  	"github.com/ethereumproject/go-ethereum/logger"
    34  	"github.com/ethereumproject/go-ethereum/logger/glog"
    35  	"github.com/ethereumproject/go-ethereum/pow"
    36  	"github.com/hashicorp/golang-lru"
    37  )
    38  
    39  // HeaderChain implements the basic block header chain logic that is shared by
    40  // core.BlockChain and light.LightChain. It is not usable in itself, only as
    41  // a part of either structure.
    42  // It is not thread safe either, the encapsulating chain structures should do
    43  // the necessary mutex locking/unlocking.
    44  type HeaderChain struct {
    45  	config *ChainConfig
    46  
    47  	chainDb       ethdb.Database
    48  	genesisHeader *types.Header
    49  
    50  	currentHeader     *types.Header // Current head of the header chain (may be above the block chain!)
    51  	currentHeaderHash common.Hash   // Hash of the current head of the header chain (prevent recomputing all the time)
    52  
    53  	headerCache *lru.Cache // Cache for the most recent block headers
    54  	tdCache     *lru.Cache // Cache for the most recent block total difficulties
    55  
    56  	procInterrupt func() bool
    57  
    58  	rand         *mrand.Rand
    59  	getValidator getHeaderValidatorFn
    60  	eventMux     *event.TypeMux
    61  }
    62  
    63  // getHeaderValidatorFn returns a HeaderValidator interface
    64  type getHeaderValidatorFn func() HeaderValidator
    65  
    66  // NewHeaderChain creates a new HeaderChain structure.
    67  //  getValidator should return the parent's validator
    68  //  procInterrupt points to the parent's interrupt semaphore
    69  //  wg points to the parent's shutdown wait group
    70  func NewHeaderChain(chainDb ethdb.Database, config *ChainConfig, mux *event.TypeMux, getValidator getHeaderValidatorFn, procInterrupt func() bool) (*HeaderChain, error) {
    71  	headerCache, _ := lru.New(headerCacheLimit)
    72  	tdCache, _ := lru.New(tdCacheLimit)
    73  
    74  	// Seed a fast but crypto originating random generator
    75  	seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
    76  	if err != nil {
    77  		return nil, err
    78  	}
    79  
    80  	hc := &HeaderChain{
    81  		config:        config,
    82  		eventMux:      mux,
    83  		chainDb:       chainDb,
    84  		headerCache:   headerCache,
    85  		tdCache:       tdCache,
    86  		procInterrupt: procInterrupt,
    87  		rand:          mrand.New(mrand.NewSource(seed.Int64())),
    88  		getValidator:  getValidator,
    89  	}
    90  
    91  	gen := DefaultConfigMainnet.Genesis
    92  	genname := "mainnet"
    93  	// Check if ChainConfig is mainnet or testnet and write genesis accordingly.
    94  	// If it's neither (custom), write default (this will be overwritten or avoided,
    95  	// but maintains consistent implementation.
    96  	if config == DefaultConfigMorden.ChainConfig {
    97  		gen = DefaultConfigMorden.Genesis
    98  		genname = "morden testnet"
    99  	}
   100  
   101  	hc.genesisHeader = hc.GetHeaderByNumber(0)
   102  	if hc.genesisHeader == nil {
   103  		genesisBlock, err := WriteGenesisBlock(chainDb, gen)
   104  		if err != nil {
   105  			return nil, err
   106  		}
   107  		glog.V(logger.Info).Infof("Wrote default ethereum %v genesis block", genname)
   108  		glog.D(logger.Info).Infof("Wrote default ethereum %v genesis block", logger.ColorGreen(genname))
   109  		hc.genesisHeader = genesisBlock.Header()
   110  	}
   111  
   112  	hc.currentHeader = hc.genesisHeader
   113  	if head := GetHeadBlockHash(chainDb); head != (common.Hash{}) {
   114  		if chead := hc.GetHeader(head); chead != nil {
   115  			hc.currentHeader = chead
   116  		}
   117  	}
   118  	hc.currentHeaderHash = hc.currentHeader.Hash()
   119  
   120  	return hc, nil
   121  }
   122  
   123  // WriteHeader writes a header into the local chain, given that its parent is
   124  // already known. If the total difficulty of the newly inserted header becomes
   125  // greater than the current known TD, the canonical chain is re-routed.
   126  //
   127  // Note: This method is not concurrent-safe with inserting blocks simultaneously
   128  // into the chain, as side effects caused by reorganisations cannot be emulated
   129  // without the real blocks. Hence, writing headers directly should only be done
   130  // in two scenarios: pure-header mode of operation (light clients), or properly
   131  // separated header/block phases (non-archive clients).
   132  func (hc *HeaderChain) WriteHeader(header *types.Header) (status WriteStatus, err error) {
   133  	// Cache some values to prevent constant recalculation
   134  	var (
   135  		hash   = header.Hash()
   136  		number = header.Number.Uint64()
   137  	)
   138  
   139  	if logger.MlogEnabled() {
   140  		defer func() {
   141  			mlogWriteStatus := "UNKNOWN"
   142  			switch status {
   143  			case NonStatTy:
   144  				mlogWriteStatus = "NONE"
   145  			case CanonStatTy:
   146  				mlogWriteStatus = "CANON"
   147  			case SideStatTy:
   148  				mlogWriteStatus = "SIDE"
   149  			}
   150  			parent := hc.GetHeader(header.ParentHash)
   151  			parentTimeDiff := new(big.Int)
   152  			if parent != nil {
   153  				parentTimeDiff = new(big.Int).Sub(header.Time, parent.Time)
   154  			}
   155  			mlogHeaderchainWriteHeader.AssignDetails(
   156  				mlogWriteStatus,
   157  				err,
   158  				header.Number,
   159  				header.Hash().Hex(),
   160  				header.GasUsed,
   161  				header.Coinbase.Hex(),
   162  				header.Time,
   163  				header.Difficulty,
   164  				parentTimeDiff,
   165  			).Send(mlogHeaderchain)
   166  		}()
   167  	}
   168  
   169  	// Calculate the total difficulty of the header
   170  	ptd := hc.GetTd(header.ParentHash)
   171  	if ptd == nil {
   172  		return NonStatTy, ParentError(header.ParentHash)
   173  	}
   174  	localTd := hc.GetTd(hc.currentHeaderHash)
   175  	externTd := new(big.Int).Add(header.Difficulty, ptd)
   176  
   177  	// Irrelevant of the canonical status, write the td and header to the database
   178  	if err := hc.WriteTd(hash, externTd); err != nil {
   179  		glog.Fatalf("failed to write header total difficulty: %v", err)
   180  	}
   181  	if err := WriteHeader(hc.chainDb, header); err != nil {
   182  		glog.Fatalf("failed to write header contents: %v", err)
   183  	}
   184  
   185  	// If the total difficulty is higher than our known, add it to the canonical chain
   186  	// Second clause in the if statement reduces the vulnerability to selfish mining.
   187  	// Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
   188  	if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
   189  		// Delete any canonical number assignments above the new head
   190  		for i := number + 1; GetCanonicalHash(hc.chainDb, i) != (common.Hash{}); i++ {
   191  			DeleteCanonicalHash(hc.chainDb, i)
   192  		}
   193  		// Overwrite any stale canonical number assignments
   194  		var (
   195  			headHash   = header.ParentHash
   196  			headHeader = hc.GetHeader(headHash)
   197  			headNumber = headHeader.Number.Uint64()
   198  		)
   199  		for GetCanonicalHash(hc.chainDb, headNumber) != headHash {
   200  			if err := WriteCanonicalHash(hc.chainDb, headHash, headNumber); err != nil {
   201  				glog.Fatalf("failed to insert header number: %v", err)
   202  			}
   203  
   204  			headHash = headHeader.ParentHash
   205  			headHeader = hc.GetHeader(headHash)
   206  			headNumber = headHeader.Number.Uint64()
   207  		}
   208  
   209  		// Extend the canonical chain with the new header
   210  		if err := WriteCanonicalHash(hc.chainDb, hash, number); err != nil {
   211  			glog.Fatalf("failed to insert header number: %v", err)
   212  		}
   213  		if err := WriteHeadHeaderHash(hc.chainDb, hash); err != nil {
   214  			glog.Fatalf("failed to insert head header hash: %v", err)
   215  		}
   216  
   217  		hc.currentHeaderHash, hc.currentHeader = hash, types.CopyHeader(header)
   218  
   219  		status = CanonStatTy
   220  	} else {
   221  		status = SideStatTy
   222  	}
   223  	hc.headerCache.Add(hash, header)
   224  
   225  	return
   226  }
   227  
   228  // WhCallback is a callback function for inserting individual headers.
   229  // A callback is used for two reasons: first, in a LightChain, status should be
   230  // processed and light chain events sent, while in a BlockChain this is not
   231  // necessary since chain events are sent after inserting blocks. Second, the
   232  // header writes should be protected by the parent chain mutex individually.
   233  type WhCallback func(*types.Header) error
   234  
   235  // InsertHeaderChain attempts to insert the given header chain in to the local
   236  // chain, possibly creating a reorg. If an error is returned, it will return the
   237  // index number of the failing header as well an error describing what went wrong.
   238  //
   239  // The verify parameter can be used to fine tune whether nonce verification
   240  // should be done or not. The reason behind the optional check is because some
   241  // of the header retrieval mechanisms already need to verfy nonces, as well as
   242  // because nonces can be verified sparsely, not needing to check each.
   243  func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, checkFreq int, writeHeader WhCallback) (res *HeaderChainInsertResult) {
   244  	res = &HeaderChainInsertResult{}
   245  
   246  	// Collect some import statistics to report on
   247  	var events []interface{}
   248  	stats := struct{ processed, ignored int }{}
   249  	start := time.Now()
   250  
   251  	// Generate the list of headers that should be POW verified
   252  	verify := make([]bool, len(chain))
   253  	for i := 0; i < len(verify)/checkFreq; i++ {
   254  		index := i*checkFreq + hc.rand.Intn(checkFreq)
   255  		if index >= len(verify) {
   256  			index = len(verify) - 1
   257  		}
   258  		verify[index] = true
   259  	}
   260  	verify[len(verify)-1] = true // Last should always be verified to avoid junk
   261  
   262  	// Create the header verification task queue and worker functions
   263  	tasks := make(chan int, len(chain))
   264  	for i := 0; i < len(chain); i++ {
   265  		tasks <- i
   266  	}
   267  	close(tasks)
   268  
   269  	errs, failed := make([]error, len(tasks)), int32(0)
   270  	process := func(worker int) {
   271  		for index := range tasks {
   272  			header, hash := chain[index], chain[index].Hash()
   273  
   274  			// Short circuit insertion if shutting down or processing failed
   275  			if hc.procInterrupt() {
   276  				return
   277  			}
   278  			if atomic.LoadInt32(&failed) > 0 {
   279  				return
   280  			}
   281  
   282  			// Short circuit if the header is bad or already known
   283  			if err := hc.config.HeaderCheck(header); err != nil {
   284  				errs[index] = err
   285  				atomic.AddInt32(&failed, 1)
   286  				return
   287  			}
   288  			if hc.HasHeader(hash) {
   289  				continue
   290  			}
   291  			// Verify that the header honors the chain parameters
   292  			checkPow := verify[index]
   293  
   294  			var err error
   295  			if index == 0 {
   296  				err = hc.getValidator().ValidateHeader(header, hc.GetHeader(header.ParentHash), checkPow)
   297  			} else {
   298  				err = hc.getValidator().ValidateHeader(header, chain[index-1], checkPow)
   299  			}
   300  			if err != nil {
   301  				errs[index] = err
   302  				atomic.AddInt32(&failed, 1)
   303  				return
   304  			}
   305  		}
   306  	}
   307  
   308  	// Start as many worker threads as goroutines allowed
   309  	pending := new(sync.WaitGroup)
   310  	for i := 0; i < runtime.GOMAXPROCS(0); i++ {
   311  		pending.Add(1)
   312  		go func(id int) {
   313  			defer pending.Done()
   314  			process(id)
   315  		}(i)
   316  	}
   317  	pending.Wait()
   318  
   319  	// If anything failed, report
   320  	if failed > 0 {
   321  		for i, err := range errs {
   322  			if err != nil {
   323  				res.Index = i
   324  				res.Error = err
   325  				return
   326  			}
   327  		}
   328  	}
   329  	// All headers passed verification, import them into the database
   330  	for i, header := range chain {
   331  		// Short circuit insertion if shutting down
   332  		if hc.procInterrupt() {
   333  			glog.V(logger.Debug).Infoln("premature abort during header chain processing")
   334  			break
   335  		}
   336  		hash := header.Hash()
   337  
   338  		// If the header's already known, skip it, otherwise store
   339  		if hc.HasHeader(hash) {
   340  			stats.ignored++
   341  			continue
   342  		}
   343  		if err := writeHeader(header); err != nil {
   344  			res.Index = i
   345  			res.Error = err
   346  			return
   347  		}
   348  		stats.processed++
   349  	}
   350  	// Report some public statistics so the user has a clue what's going on
   351  	first, last := chain[0], chain[len(chain)-1]
   352  	elapsed := time.Since(start)
   353  
   354  	hv := HeaderChainInsertEvent{
   355  		Processed:  stats.processed,
   356  		Ignored:    stats.ignored,
   357  		LastNumber: last.Number.Uint64(),
   358  		LastHash:   last.Hash(),
   359  		Elasped:    elapsed,
   360  	}
   361  	res.HeaderChainInsertEvent = hv
   362  
   363  	glog.V(logger.Info).Infof("imported %d header(s) (%d ignored) in %v. #%v [%x… / %x…]", res.Processed, res.Ignored,
   364  		res.Elasped, res.LastNumber, first.Hash().Bytes()[:4], res.LastHash.Bytes()[:4])
   365  
   366  	if logger.MlogEnabled() {
   367  		mlogHeaderchainInsertHeaders.AssignDetails(
   368  			stats.processed,
   369  			stats.ignored,
   370  			last.Number,
   371  			first.Hash().Hex(),
   372  			last.Hash().Hex(),
   373  			elapsed,
   374  		).Send(mlogHeaderchain)
   375  	}
   376  	events = append(events, hv)
   377  	go hc.postChainEvents(events)
   378  
   379  	return res
   380  }
   381  
   382  // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
   383  // hash, fetching towards the genesis block.
   384  func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
   385  	// Get the origin header from which to fetch
   386  	header := hc.GetHeader(hash)
   387  	if header == nil {
   388  		return nil
   389  	}
   390  	// Iterate the headers until enough is collected or the genesis reached
   391  	chain := make([]common.Hash, 0, max)
   392  	for i := uint64(0); i < max; i++ {
   393  		next := header.ParentHash
   394  		if header = hc.GetHeader(next); header == nil {
   395  			break
   396  		}
   397  		chain = append(chain, next)
   398  		if header.Number.Sign() == 0 {
   399  			break
   400  		}
   401  	}
   402  	return chain
   403  }
   404  
   405  // GetTd retrieves a block's total difficulty in the canonical chain from the
   406  // database by hash, caching it if found.
   407  func (hc *HeaderChain) GetTd(hash common.Hash) *big.Int {
   408  	// Short circuit if the td's already in the cache, retrieve otherwise
   409  	if cached, ok := hc.tdCache.Get(hash); ok {
   410  		return cached.(*big.Int)
   411  	}
   412  	td := GetTd(hc.chainDb, hash)
   413  	if td == nil {
   414  		return nil
   415  	}
   416  	// Cache the found body for next time and return
   417  	hc.tdCache.Add(hash, td)
   418  	return td
   419  }
   420  
   421  // WriteTd stores a block's total difficulty into the database, also caching it
   422  // along the way.
   423  func (hc *HeaderChain) WriteTd(hash common.Hash, td *big.Int) error {
   424  	if err := WriteTd(hc.chainDb, hash, td); err != nil {
   425  		return err
   426  	}
   427  	hc.tdCache.Add(hash, new(big.Int).Set(td))
   428  	return nil
   429  }
   430  
   431  // GetHeader retrieves a block header from the database by hash, caching it if
   432  // found.
   433  func (hc *HeaderChain) GetHeader(hash common.Hash) *types.Header {
   434  	// Short circuit if the header's already in the cache, retrieve otherwise
   435  	if header, ok := hc.headerCache.Get(hash); ok {
   436  		return header.(*types.Header)
   437  	}
   438  	header := GetHeader(hc.chainDb, hash)
   439  	if header == nil {
   440  		return nil
   441  	}
   442  	// Cache the found header for next time and return
   443  	hc.headerCache.Add(hash, header)
   444  	return header
   445  }
   446  
   447  // HasHeader checks if a block header is present in the database or not, caching
   448  // it if present.
   449  func (hc *HeaderChain) HasHeader(hash common.Hash) bool {
   450  	return hc.GetHeader(hash) != nil
   451  }
   452  
   453  // GetHeaderByNumber retrieves a block header from the database by number,
   454  // caching it (associated with its hash) if found.
   455  func (hc *HeaderChain) GetHeaderByNumber(number uint64) *types.Header {
   456  	hash := GetCanonicalHash(hc.chainDb, number)
   457  	if hash == (common.Hash{}) {
   458  		return nil
   459  	}
   460  	return hc.GetHeader(hash)
   461  }
   462  
   463  // CurrentHeader retrieves the current head header of the canonical chain. The
   464  // header is retrieved from the HeaderChain's internal cache.
   465  func (hc *HeaderChain) CurrentHeader() *types.Header {
   466  	return hc.currentHeader
   467  }
   468  
   469  // SetCurrentHeader sets the current head header of the canonical chain.
   470  func (hc *HeaderChain) SetCurrentHeader(head *types.Header) {
   471  	if err := WriteHeadHeaderHash(hc.chainDb, head.Hash()); err != nil {
   472  		glog.Fatalf("failed to insert head header hash: %v", err)
   473  	}
   474  	hc.currentHeader = head
   475  	hc.currentHeaderHash = head.Hash()
   476  }
   477  
   478  // DeleteCallback is a callback function that is called by SetHead before
   479  // each header is deleted.
   480  type DeleteCallback func(common.Hash)
   481  
   482  // PurgeAbove remove blockchain data above given head 'n'.
   483  // Similar to hc.SetHead, but uses hardcoded 2048 scan range to check
   484  // for existing blockchain above last found existing head.
   485  // TODO: possibly replace with kv database iterator
   486  func (hc *HeaderChain) PurgeAbove(n uint64, delFn DeleteCallback) {
   487  
   488  	glog.V(logger.Warn).Infof("Purging block data above #%d", n)
   489  
   490  	// Set up logging for block purge progress.
   491  	ticker := time.NewTicker(time.Second * 5)
   492  	defer ticker.Stop()
   493  	go func() {
   494  		for range ticker.C {
   495  			glog.V(logger.Warn).Infof("Removed data through #%d", n)
   496  		}
   497  	}()
   498  
   499  	lastFoundHeaderN := n
   500  	var head *types.Header = nil
   501  	for ; head != nil || n < lastFoundHeaderN+2048; n++ {
   502  		head = hc.GetHeaderByNumber(n)
   503  		if head != nil {
   504  			lastFoundHeaderN = n
   505  
   506  			glog.V(logger.Detail).Infof("    delete header/hash/td headn=%d", head.Number.Uint64())
   507  			hash := head.Hash()
   508  			if delFn != nil {
   509  				delFn(hash)
   510  			}
   511  			DeleteHeader(hc.chainDb, hash)
   512  			DeleteTd(hc.chainDb, hash)
   513  		}
   514  		DeleteCanonicalHash(hc.chainDb, n)
   515  	}
   516  }
   517  
   518  // SetHead rewinds the local chain to a new head. Everything above the new head
   519  // will be deleted and the new one set.
   520  func (hc *HeaderChain) SetHead(head uint64, delFn DeleteCallback) {
   521  	height := uint64(0)
   522  	if hc.currentHeader != nil {
   523  		height = hc.currentHeader.Number.Uint64()
   524  	}
   525  
   526  	for hc.currentHeader != nil && hc.currentHeader.Number.Uint64() > head {
   527  		hash := hc.currentHeader.Hash()
   528  		if delFn != nil {
   529  			delFn(hash)
   530  		}
   531  		DeleteHeader(hc.chainDb, hash)
   532  		DeleteTd(hc.chainDb, hash)
   533  		hc.currentHeader = hc.GetHeader(hc.currentHeader.ParentHash)
   534  	}
   535  	// Roll back the canonical chain numbering
   536  	for i := height; i > head; i-- {
   537  		DeleteCanonicalHash(hc.chainDb, i)
   538  	}
   539  	// Clear out any stale content from the caches
   540  	hc.headerCache.Purge()
   541  	hc.tdCache.Purge()
   542  
   543  	if hc.currentHeader == nil {
   544  		hc.currentHeader = hc.genesisHeader
   545  	}
   546  	hc.currentHeaderHash = hc.currentHeader.Hash()
   547  
   548  	if err := WriteHeadHeaderHash(hc.chainDb, hc.currentHeaderHash); err != nil {
   549  		glog.Fatalf("failed to reset head header hash: %v", err)
   550  	}
   551  }
   552  
   553  // SetGenesis sets a new genesis block header for the chain
   554  func (hc *HeaderChain) SetGenesis(head *types.Header) {
   555  	hc.genesisHeader = head
   556  }
   557  
   558  // postChainEvents iterates over the events generated by a chain insertion and
   559  // posts them into the event mux.
   560  func (hc *HeaderChain) postChainEvents(events []interface{}) {
   561  	// post event logs for further processing
   562  	for _, event := range events {
   563  		// Fire the insertion events individually
   564  		hc.eventMux.Post(event)
   565  	}
   566  }
   567  
   568  // headerValidator is responsible for validating block headers
   569  //
   570  // headerValidator implements HeaderValidator.
   571  type headerValidator struct {
   572  	config *ChainConfig
   573  	hc     *HeaderChain // Canonical header chain
   574  	Pow    pow.PoW      // Proof of work used for validating
   575  }
   576  
   577  // ValidateHeader validates the given header and, depending on the pow arg,
   578  // checks the proof of work of the given header. Returns an error if the
   579  // validation failed.
   580  func (v *headerValidator) ValidateHeader(header, parent *types.Header, checkPow bool) error {
   581  	// Short circuit if the parent is missing.
   582  	if parent == nil {
   583  		return ParentError(header.ParentHash)
   584  	}
   585  	// Short circuit if the header's already known or its parent missing
   586  	if v.hc.HasHeader(header.Hash()) {
   587  		return nil
   588  	}
   589  	return ValidateHeader(v.config, v.Pow, header, parent, checkPow, false)
   590  }