github.com/MaynardMiner/ethereumprogpow@v1.8.23/core/blockchain.go (about)

     1  // Copyright 2014 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 implements the Ethereum consensus protocol.
    18  package core
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"io"
    24  	"math/big"
    25  	mrand "math/rand"
    26  	"sync"
    27  	"sync/atomic"
    28  	"time"
    29  
    30  	"github.com/ethereumprogpow/ethereumprogpow/common"
    31  	"github.com/ethereumprogpow/ethereumprogpow/common/mclock"
    32  	"github.com/ethereumprogpow/ethereumprogpow/common/prque"
    33  	"github.com/ethereumprogpow/ethereumprogpow/consensus"
    34  	"github.com/ethereumprogpow/ethereumprogpow/core/rawdb"
    35  	"github.com/ethereumprogpow/ethereumprogpow/core/state"
    36  	"github.com/ethereumprogpow/ethereumprogpow/core/types"
    37  	"github.com/ethereumprogpow/ethereumprogpow/core/vm"
    38  	"github.com/ethereumprogpow/ethereumprogpow/crypto"
    39  	"github.com/ethereumprogpow/ethereumprogpow/ethdb"
    40  	"github.com/ethereumprogpow/ethereumprogpow/event"
    41  	"github.com/ethereumprogpow/ethereumprogpow/log"
    42  	"github.com/ethereumprogpow/ethereumprogpow/metrics"
    43  	"github.com/ethereumprogpow/ethereumprogpow/params"
    44  	"github.com/ethereumprogpow/ethereumprogpow/rlp"
    45  	"github.com/ethereumprogpow/ethereumprogpow/trie"
    46  	"github.com/hashicorp/golang-lru"
    47  )
    48  
    49  var (
    50  	blockInsertTimer     = metrics.NewRegisteredTimer("chain/inserts", nil)
    51  	blockValidationTimer = metrics.NewRegisteredTimer("chain/validation", nil)
    52  	blockExecutionTimer  = metrics.NewRegisteredTimer("chain/execution", nil)
    53  	blockWriteTimer      = metrics.NewRegisteredTimer("chain/write", nil)
    54  
    55  	ErrNoGenesis = errors.New("Genesis not found in chain")
    56  )
    57  
    58  const (
    59  	bodyCacheLimit      = 256
    60  	blockCacheLimit     = 256
    61  	receiptsCacheLimit  = 32
    62  	maxFutureBlocks     = 256
    63  	maxTimeFutureBlocks = 30
    64  	badBlockLimit       = 10
    65  	triesInMemory       = 128
    66  
    67  	// BlockChainVersion ensures that an incompatible database forces a resync from scratch.
    68  	BlockChainVersion uint64 = 3
    69  )
    70  
    71  // CacheConfig contains the configuration values for the trie caching/pruning
    72  // that's resident in a blockchain.
    73  type CacheConfig struct {
    74  	Disabled       bool          // Whether to disable trie write caching (archive node)
    75  	TrieCleanLimit int           // Memory allowance (MB) to use for caching trie nodes in memory
    76  	TrieDirtyLimit int           // Memory limit (MB) at which to start flushing dirty trie nodes to disk
    77  	TrieTimeLimit  time.Duration // Time limit after which to flush the current in-memory trie to disk
    78  }
    79  
    80  // BlockChain represents the canonical chain given a database with a genesis
    81  // block. The Blockchain manages chain imports, reverts, chain reorganisations.
    82  //
    83  // Importing blocks in to the block chain happens according to the set of rules
    84  // defined by the two stage Validator. Processing of blocks is done using the
    85  // Processor which processes the included transaction. The validation of the state
    86  // is done in the second part of the Validator. Failing results in aborting of
    87  // the import.
    88  //
    89  // The BlockChain also helps in returning blocks from **any** chain included
    90  // in the database as well as blocks that represents the canonical chain. It's
    91  // important to note that GetBlock can return any block and does not need to be
    92  // included in the canonical one where as GetBlockByNumber always represents the
    93  // canonical chain.
    94  type BlockChain struct {
    95  	chainConfig *params.ChainConfig // Chain & network configuration
    96  	cacheConfig *CacheConfig        // Cache configuration for pruning
    97  
    98  	db     ethdb.Database // Low level persistent database to store final content in
    99  	triegc *prque.Prque   // Priority queue mapping block numbers to tries to gc
   100  	gcproc time.Duration  // Accumulates canonical block processing for trie dumping
   101  
   102  	hc            *HeaderChain
   103  	rmLogsFeed    event.Feed
   104  	chainFeed     event.Feed
   105  	chainSideFeed event.Feed
   106  	chainHeadFeed event.Feed
   107  	logsFeed      event.Feed
   108  	scope         event.SubscriptionScope
   109  	genesisBlock  *types.Block
   110  
   111  	mu      sync.RWMutex // global mutex for locking chain operations
   112  	chainmu sync.RWMutex // blockchain insertion lock
   113  	procmu  sync.RWMutex // block processor lock
   114  
   115  	checkpoint       int          // checkpoint counts towards the new checkpoint
   116  	currentBlock     atomic.Value // Current head of the block chain
   117  	currentFastBlock atomic.Value // Current head of the fast-sync chain (may be above the block chain!)
   118  
   119  	stateCache    state.Database // State database to reuse between imports (contains state cache)
   120  	bodyCache     *lru.Cache     // Cache for the most recent block bodies
   121  	bodyRLPCache  *lru.Cache     // Cache for the most recent block bodies in RLP encoded format
   122  	receiptsCache *lru.Cache     // Cache for the most recent receipts per block
   123  	blockCache    *lru.Cache     // Cache for the most recent entire blocks
   124  	futureBlocks  *lru.Cache     // future blocks are blocks added for later processing
   125  
   126  	quit    chan struct{} // blockchain quit channel
   127  	running int32         // running must be called atomically
   128  	// procInterrupt must be atomically called
   129  	procInterrupt int32          // interrupt signaler for block processing
   130  	wg            sync.WaitGroup // chain processing wait group for shutting down
   131  
   132  	engine    consensus.Engine
   133  	processor Processor // block processor interface
   134  	validator Validator // block and state validator interface
   135  	vmConfig  vm.Config
   136  
   137  	badBlocks      *lru.Cache              // Bad block cache
   138  	shouldPreserve func(*types.Block) bool // Function used to determine whether should preserve the given block.
   139  }
   140  
   141  // NewBlockChain returns a fully initialised block chain using information
   142  // available in the database. It initialises the default Ethereum Validator and
   143  // Processor.
   144  func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config, shouldPreserve func(block *types.Block) bool) (*BlockChain, error) {
   145  	if cacheConfig == nil {
   146  		cacheConfig = &CacheConfig{
   147  			TrieCleanLimit: 256,
   148  			TrieDirtyLimit: 256,
   149  			TrieTimeLimit:  5 * time.Minute,
   150  		}
   151  	}
   152  	bodyCache, _ := lru.New(bodyCacheLimit)
   153  	bodyRLPCache, _ := lru.New(bodyCacheLimit)
   154  	receiptsCache, _ := lru.New(receiptsCacheLimit)
   155  	blockCache, _ := lru.New(blockCacheLimit)
   156  	futureBlocks, _ := lru.New(maxFutureBlocks)
   157  	badBlocks, _ := lru.New(badBlockLimit)
   158  
   159  	bc := &BlockChain{
   160  		chainConfig:    chainConfig,
   161  		cacheConfig:    cacheConfig,
   162  		db:             db,
   163  		triegc:         prque.New(nil),
   164  		stateCache:     state.NewDatabaseWithCache(db, cacheConfig.TrieCleanLimit),
   165  		quit:           make(chan struct{}),
   166  		shouldPreserve: shouldPreserve,
   167  		bodyCache:      bodyCache,
   168  		bodyRLPCache:   bodyRLPCache,
   169  		receiptsCache:  receiptsCache,
   170  		blockCache:     blockCache,
   171  		futureBlocks:   futureBlocks,
   172  		engine:         engine,
   173  		vmConfig:       vmConfig,
   174  		badBlocks:      badBlocks,
   175  	}
   176  	bc.SetValidator(NewBlockValidator(chainConfig, bc, engine))
   177  	bc.SetProcessor(NewStateProcessor(chainConfig, bc, engine))
   178  
   179  	var err error
   180  	bc.hc, err = NewHeaderChain(db, chainConfig, engine, bc.getProcInterrupt)
   181  	if err != nil {
   182  		return nil, err
   183  	}
   184  	bc.genesisBlock = bc.GetBlockByNumber(0)
   185  	if bc.genesisBlock == nil {
   186  		return nil, ErrNoGenesis
   187  	}
   188  	if err := bc.loadLastState(); err != nil {
   189  		return nil, err
   190  	}
   191  	// Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
   192  	for hash := range BadHashes {
   193  		if header := bc.GetHeaderByHash(hash); header != nil {
   194  			// get the canonical block corresponding to the offending header's number
   195  			headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
   196  			// make sure the headerByNumber (if present) is in our current canonical chain
   197  			if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
   198  				log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
   199  				bc.SetHead(header.Number.Uint64() - 1)
   200  				log.Error("Chain rewind was successful, resuming normal operation")
   201  			}
   202  		}
   203  	}
   204  	// Take ownership of this particular state
   205  	go bc.update()
   206  	return bc, nil
   207  }
   208  
   209  func (bc *BlockChain) getProcInterrupt() bool {
   210  	return atomic.LoadInt32(&bc.procInterrupt) == 1
   211  }
   212  
   213  // GetVMConfig returns the block chain VM config.
   214  func (bc *BlockChain) GetVMConfig() *vm.Config {
   215  	return &bc.vmConfig
   216  }
   217  
   218  // loadLastState loads the last known chain state from the database. This method
   219  // assumes that the chain manager mutex is held.
   220  func (bc *BlockChain) loadLastState() error {
   221  	// Restore the last known head block
   222  	head := rawdb.ReadHeadBlockHash(bc.db)
   223  	if head == (common.Hash{}) {
   224  		// Corrupt or empty database, init from scratch
   225  		log.Warn("Empty database, resetting chain")
   226  		return bc.Reset()
   227  	}
   228  	// Make sure the entire head block is available
   229  	currentBlock := bc.GetBlockByHash(head)
   230  	if currentBlock == nil {
   231  		// Corrupt or empty database, init from scratch
   232  		log.Warn("Head block missing, resetting chain", "hash", head)
   233  		return bc.Reset()
   234  	}
   235  	// Make sure the state associated with the block is available
   236  	if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
   237  		// Dangling block without a state associated, init from scratch
   238  		log.Warn("Head state missing, repairing chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
   239  		if err := bc.repair(&currentBlock); err != nil {
   240  			return err
   241  		}
   242  	}
   243  	// Everything seems to be fine, set as the head block
   244  	bc.currentBlock.Store(currentBlock)
   245  
   246  	// Restore the last known head header
   247  	currentHeader := currentBlock.Header()
   248  	if head := rawdb.ReadHeadHeaderHash(bc.db); head != (common.Hash{}) {
   249  		if header := bc.GetHeaderByHash(head); header != nil {
   250  			currentHeader = header
   251  		}
   252  	}
   253  	bc.hc.SetCurrentHeader(currentHeader)
   254  
   255  	// Restore the last known head fast block
   256  	bc.currentFastBlock.Store(currentBlock)
   257  	if head := rawdb.ReadHeadFastBlockHash(bc.db); head != (common.Hash{}) {
   258  		if block := bc.GetBlockByHash(head); block != nil {
   259  			bc.currentFastBlock.Store(block)
   260  		}
   261  	}
   262  
   263  	// Issue a status log for the user
   264  	currentFastBlock := bc.CurrentFastBlock()
   265  
   266  	headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
   267  	blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
   268  	fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64())
   269  
   270  	log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(currentHeader.Time.Int64(), 0)))
   271  	log.Info("Loaded most recent local full block", "number", currentBlock.Number(), "hash", currentBlock.Hash(), "td", blockTd, "age", common.PrettyAge(time.Unix(currentBlock.Time().Int64(), 0)))
   272  	log.Info("Loaded most recent local fast block", "number", currentFastBlock.Number(), "hash", currentFastBlock.Hash(), "td", fastTd, "age", common.PrettyAge(time.Unix(currentFastBlock.Time().Int64(), 0)))
   273  
   274  	return nil
   275  }
   276  
   277  // SetHead rewinds the local chain to a new head. In the case of headers, everything
   278  // above the new head will be deleted and the new one set. In the case of blocks
   279  // though, the head may be further rewound if block bodies are missing (non-archive
   280  // nodes after a fast sync).
   281  func (bc *BlockChain) SetHead(head uint64) error {
   282  	log.Warn("Rewinding blockchain", "target", head)
   283  
   284  	bc.mu.Lock()
   285  	defer bc.mu.Unlock()
   286  
   287  	// Rewind the header chain, deleting all block bodies until then
   288  	delFn := func(db rawdb.DatabaseDeleter, hash common.Hash, num uint64) {
   289  		rawdb.DeleteBody(db, hash, num)
   290  	}
   291  	bc.hc.SetHead(head, delFn)
   292  	currentHeader := bc.hc.CurrentHeader()
   293  
   294  	// Clear out any stale content from the caches
   295  	bc.bodyCache.Purge()
   296  	bc.bodyRLPCache.Purge()
   297  	bc.receiptsCache.Purge()
   298  	bc.blockCache.Purge()
   299  	bc.futureBlocks.Purge()
   300  
   301  	// Rewind the block chain, ensuring we don't end up with a stateless head block
   302  	if currentBlock := bc.CurrentBlock(); currentBlock != nil && currentHeader.Number.Uint64() < currentBlock.NumberU64() {
   303  		bc.currentBlock.Store(bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()))
   304  	}
   305  	if currentBlock := bc.CurrentBlock(); currentBlock != nil {
   306  		if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
   307  			// Rewound state missing, rolled back to before pivot, reset to genesis
   308  			bc.currentBlock.Store(bc.genesisBlock)
   309  		}
   310  	}
   311  	// Rewind the fast block in a simpleton way to the target head
   312  	if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock != nil && currentHeader.Number.Uint64() < currentFastBlock.NumberU64() {
   313  		bc.currentFastBlock.Store(bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64()))
   314  	}
   315  	// If either blocks reached nil, reset to the genesis state
   316  	if currentBlock := bc.CurrentBlock(); currentBlock == nil {
   317  		bc.currentBlock.Store(bc.genesisBlock)
   318  	}
   319  	if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock == nil {
   320  		bc.currentFastBlock.Store(bc.genesisBlock)
   321  	}
   322  	currentBlock := bc.CurrentBlock()
   323  	currentFastBlock := bc.CurrentFastBlock()
   324  
   325  	rawdb.WriteHeadBlockHash(bc.db, currentBlock.Hash())
   326  	rawdb.WriteHeadFastBlockHash(bc.db, currentFastBlock.Hash())
   327  
   328  	return bc.loadLastState()
   329  }
   330  
   331  // FastSyncCommitHead sets the current head block to the one defined by the hash
   332  // irrelevant what the chain contents were prior.
   333  func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
   334  	// Make sure that both the block as well at its state trie exists
   335  	block := bc.GetBlockByHash(hash)
   336  	if block == nil {
   337  		return fmt.Errorf("non existent block [%x…]", hash[:4])
   338  	}
   339  	if _, err := trie.NewSecure(block.Root(), bc.stateCache.TrieDB(), 0); err != nil {
   340  		return err
   341  	}
   342  	// If all checks out, manually set the head block
   343  	bc.mu.Lock()
   344  	bc.currentBlock.Store(block)
   345  	bc.mu.Unlock()
   346  
   347  	log.Info("Committed new head block", "number", block.Number(), "hash", hash)
   348  	return nil
   349  }
   350  
   351  // GasLimit returns the gas limit of the current HEAD block.
   352  func (bc *BlockChain) GasLimit() uint64 {
   353  	return bc.CurrentBlock().GasLimit()
   354  }
   355  
   356  // CurrentBlock retrieves the current head block of the canonical chain. The
   357  // block is retrieved from the blockchain's internal cache.
   358  func (bc *BlockChain) CurrentBlock() *types.Block {
   359  	return bc.currentBlock.Load().(*types.Block)
   360  }
   361  
   362  // CurrentFastBlock retrieves the current fast-sync head block of the canonical
   363  // chain. The block is retrieved from the blockchain's internal cache.
   364  func (bc *BlockChain) CurrentFastBlock() *types.Block {
   365  	return bc.currentFastBlock.Load().(*types.Block)
   366  }
   367  
   368  // SetProcessor sets the processor required for making state modifications.
   369  func (bc *BlockChain) SetProcessor(processor Processor) {
   370  	bc.procmu.Lock()
   371  	defer bc.procmu.Unlock()
   372  	bc.processor = processor
   373  }
   374  
   375  // SetValidator sets the validator which is used to validate incoming blocks.
   376  func (bc *BlockChain) SetValidator(validator Validator) {
   377  	bc.procmu.Lock()
   378  	defer bc.procmu.Unlock()
   379  	bc.validator = validator
   380  }
   381  
   382  // Validator returns the current validator.
   383  func (bc *BlockChain) Validator() Validator {
   384  	bc.procmu.RLock()
   385  	defer bc.procmu.RUnlock()
   386  	return bc.validator
   387  }
   388  
   389  // Processor returns the current processor.
   390  func (bc *BlockChain) Processor() Processor {
   391  	bc.procmu.RLock()
   392  	defer bc.procmu.RUnlock()
   393  	return bc.processor
   394  }
   395  
   396  // State returns a new mutable state based on the current HEAD block.
   397  func (bc *BlockChain) State() (*state.StateDB, error) {
   398  	return bc.StateAt(bc.CurrentBlock().Root())
   399  }
   400  
   401  // StateAt returns a new mutable state based on a particular point in time.
   402  func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
   403  	return state.New(root, bc.stateCache)
   404  }
   405  
   406  // StateCache returns the caching database underpinning the blockchain instance.
   407  func (bc *BlockChain) StateCache() state.Database {
   408  	return bc.stateCache
   409  }
   410  
   411  // Reset purges the entire blockchain, restoring it to its genesis state.
   412  func (bc *BlockChain) Reset() error {
   413  	return bc.ResetWithGenesisBlock(bc.genesisBlock)
   414  }
   415  
   416  // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
   417  // specified genesis state.
   418  func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
   419  	// Dump the entire block chain and purge the caches
   420  	if err := bc.SetHead(0); err != nil {
   421  		return err
   422  	}
   423  	bc.mu.Lock()
   424  	defer bc.mu.Unlock()
   425  
   426  	// Prepare the genesis block and reinitialise the chain
   427  	if err := bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
   428  		log.Crit("Failed to write genesis block TD", "err", err)
   429  	}
   430  	rawdb.WriteBlock(bc.db, genesis)
   431  
   432  	bc.genesisBlock = genesis
   433  	bc.insert(bc.genesisBlock)
   434  	bc.currentBlock.Store(bc.genesisBlock)
   435  	bc.hc.SetGenesis(bc.genesisBlock.Header())
   436  	bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
   437  	bc.currentFastBlock.Store(bc.genesisBlock)
   438  
   439  	return nil
   440  }
   441  
   442  // repair tries to repair the current blockchain by rolling back the current block
   443  // until one with associated state is found. This is needed to fix incomplete db
   444  // writes caused either by crashes/power outages, or simply non-committed tries.
   445  //
   446  // This method only rolls back the current block. The current header and current
   447  // fast block are left intact.
   448  func (bc *BlockChain) repair(head **types.Block) error {
   449  	for {
   450  		// Abort if we've rewound to a head block that does have associated state
   451  		if _, err := state.New((*head).Root(), bc.stateCache); err == nil {
   452  			log.Info("Rewound blockchain to past state", "number", (*head).Number(), "hash", (*head).Hash())
   453  			return nil
   454  		}
   455  		// Otherwise rewind one block and recheck state availability there
   456  		block := bc.GetBlock((*head).ParentHash(), (*head).NumberU64()-1)
   457  		if block == nil {
   458  			return fmt.Errorf("missing block %d [%x]", (*head).NumberU64()-1, (*head).ParentHash())
   459  		}
   460  		(*head) = block
   461  	}
   462  }
   463  
   464  // Export writes the active chain to the given writer.
   465  func (bc *BlockChain) Export(w io.Writer) error {
   466  	return bc.ExportN(w, uint64(0), bc.CurrentBlock().NumberU64())
   467  }
   468  
   469  // ExportN writes a subset of the active chain to the given writer.
   470  func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
   471  	bc.mu.RLock()
   472  	defer bc.mu.RUnlock()
   473  
   474  	if first > last {
   475  		return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
   476  	}
   477  	log.Info("Exporting batch of blocks", "count", last-first+1)
   478  
   479  	start, reported := time.Now(), time.Now()
   480  	for nr := first; nr <= last; nr++ {
   481  		block := bc.GetBlockByNumber(nr)
   482  		if block == nil {
   483  			return fmt.Errorf("export failed on #%d: not found", nr)
   484  		}
   485  		if err := block.EncodeRLP(w); err != nil {
   486  			return err
   487  		}
   488  		if time.Since(reported) >= statsReportLimit {
   489  			log.Info("Exporting blocks", "exported", block.NumberU64()-first, "elapsed", common.PrettyDuration(time.Since(start)))
   490  			reported = time.Now()
   491  		}
   492  	}
   493  
   494  	return nil
   495  }
   496  
   497  // insert injects a new head block into the current block chain. This method
   498  // assumes that the block is indeed a true head. It will also reset the head
   499  // header and the head fast sync block to this very same block if they are older
   500  // or if they are on a different side chain.
   501  //
   502  // Note, this function assumes that the `mu` mutex is held!
   503  func (bc *BlockChain) insert(block *types.Block) {
   504  	// If the block is on a side chain or an unknown one, force other heads onto it too
   505  	updateHeads := rawdb.ReadCanonicalHash(bc.db, block.NumberU64()) != block.Hash()
   506  
   507  	// Add the block to the canonical chain number scheme and mark as the head
   508  	rawdb.WriteCanonicalHash(bc.db, block.Hash(), block.NumberU64())
   509  	rawdb.WriteHeadBlockHash(bc.db, block.Hash())
   510  
   511  	bc.currentBlock.Store(block)
   512  
   513  	// If the block is better than our head or is on a different chain, force update heads
   514  	if updateHeads {
   515  		bc.hc.SetCurrentHeader(block.Header())
   516  		rawdb.WriteHeadFastBlockHash(bc.db, block.Hash())
   517  
   518  		bc.currentFastBlock.Store(block)
   519  	}
   520  }
   521  
   522  // Genesis retrieves the chain's genesis block.
   523  func (bc *BlockChain) Genesis() *types.Block {
   524  	return bc.genesisBlock
   525  }
   526  
   527  // GetBody retrieves a block body (transactions and uncles) from the database by
   528  // hash, caching it if found.
   529  func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
   530  	// Short circuit if the body's already in the cache, retrieve otherwise
   531  	if cached, ok := bc.bodyCache.Get(hash); ok {
   532  		body := cached.(*types.Body)
   533  		return body
   534  	}
   535  	number := bc.hc.GetBlockNumber(hash)
   536  	if number == nil {
   537  		return nil
   538  	}
   539  	body := rawdb.ReadBody(bc.db, hash, *number)
   540  	if body == nil {
   541  		return nil
   542  	}
   543  	// Cache the found body for next time and return
   544  	bc.bodyCache.Add(hash, body)
   545  	return body
   546  }
   547  
   548  // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
   549  // caching it if found.
   550  func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
   551  	// Short circuit if the body's already in the cache, retrieve otherwise
   552  	if cached, ok := bc.bodyRLPCache.Get(hash); ok {
   553  		return cached.(rlp.RawValue)
   554  	}
   555  	number := bc.hc.GetBlockNumber(hash)
   556  	if number == nil {
   557  		return nil
   558  	}
   559  	body := rawdb.ReadBodyRLP(bc.db, hash, *number)
   560  	if len(body) == 0 {
   561  		return nil
   562  	}
   563  	// Cache the found body for next time and return
   564  	bc.bodyRLPCache.Add(hash, body)
   565  	return body
   566  }
   567  
   568  // HasBlock checks if a block is fully present in the database or not.
   569  func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
   570  	if bc.blockCache.Contains(hash) {
   571  		return true
   572  	}
   573  	return rawdb.HasBody(bc.db, hash, number)
   574  }
   575  
   576  // HasFastBlock checks if a fast block is fully present in the database or not.
   577  func (bc *BlockChain) HasFastBlock(hash common.Hash, number uint64) bool {
   578  	if !bc.HasBlock(hash, number) {
   579  		return false
   580  	}
   581  	if bc.receiptsCache.Contains(hash) {
   582  		return true
   583  	}
   584  	return rawdb.HasReceipts(bc.db, hash, number)
   585  }
   586  
   587  // HasState checks if state trie is fully present in the database or not.
   588  func (bc *BlockChain) HasState(hash common.Hash) bool {
   589  	_, err := bc.stateCache.OpenTrie(hash)
   590  	return err == nil
   591  }
   592  
   593  // HasBlockAndState checks if a block and associated state trie is fully present
   594  // in the database or not, caching it if present.
   595  func (bc *BlockChain) HasBlockAndState(hash common.Hash, number uint64) bool {
   596  	// Check first that the block itself is known
   597  	block := bc.GetBlock(hash, number)
   598  	if block == nil {
   599  		return false
   600  	}
   601  	return bc.HasState(block.Root())
   602  }
   603  
   604  // GetBlock retrieves a block from the database by hash and number,
   605  // caching it if found.
   606  func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
   607  	// Short circuit if the block's already in the cache, retrieve otherwise
   608  	if block, ok := bc.blockCache.Get(hash); ok {
   609  		return block.(*types.Block)
   610  	}
   611  	block := rawdb.ReadBlock(bc.db, hash, number)
   612  	if block == nil {
   613  		return nil
   614  	}
   615  	// Cache the found block for next time and return
   616  	bc.blockCache.Add(block.Hash(), block)
   617  	return block
   618  }
   619  
   620  // GetBlockByHash retrieves a block from the database by hash, caching it if found.
   621  func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
   622  	number := bc.hc.GetBlockNumber(hash)
   623  	if number == nil {
   624  		return nil
   625  	}
   626  	return bc.GetBlock(hash, *number)
   627  }
   628  
   629  // GetBlockByNumber retrieves a block from the database by number, caching it
   630  // (associated with its hash) if found.
   631  func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
   632  	hash := rawdb.ReadCanonicalHash(bc.db, number)
   633  	if hash == (common.Hash{}) {
   634  		return nil
   635  	}
   636  	return bc.GetBlock(hash, number)
   637  }
   638  
   639  // GetReceiptsByHash retrieves the receipts for all transactions in a given block.
   640  func (bc *BlockChain) GetReceiptsByHash(hash common.Hash) types.Receipts {
   641  	if receipts, ok := bc.receiptsCache.Get(hash); ok {
   642  		return receipts.(types.Receipts)
   643  	}
   644  	number := rawdb.ReadHeaderNumber(bc.db, hash)
   645  	if number == nil {
   646  		return nil
   647  	}
   648  	receipts := rawdb.ReadReceipts(bc.db, hash, *number)
   649  	bc.receiptsCache.Add(hash, receipts)
   650  	return receipts
   651  }
   652  
   653  // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
   654  // [deprecated by eth/62]
   655  func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
   656  	number := bc.hc.GetBlockNumber(hash)
   657  	if number == nil {
   658  		return nil
   659  	}
   660  	for i := 0; i < n; i++ {
   661  		block := bc.GetBlock(hash, *number)
   662  		if block == nil {
   663  			break
   664  		}
   665  		blocks = append(blocks, block)
   666  		hash = block.ParentHash()
   667  		*number--
   668  	}
   669  	return
   670  }
   671  
   672  // GetUnclesInChain retrieves all the uncles from a given block backwards until
   673  // a specific distance is reached.
   674  func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
   675  	uncles := []*types.Header{}
   676  	for i := 0; block != nil && i < length; i++ {
   677  		uncles = append(uncles, block.Uncles()...)
   678  		block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
   679  	}
   680  	return uncles
   681  }
   682  
   683  // TrieNode retrieves a blob of data associated with a trie node (or code hash)
   684  // either from ephemeral in-memory cache, or from persistent storage.
   685  func (bc *BlockChain) TrieNode(hash common.Hash) ([]byte, error) {
   686  	return bc.stateCache.TrieDB().Node(hash)
   687  }
   688  
   689  // Stop stops the blockchain service. If any imports are currently in progress
   690  // it will abort them using the procInterrupt.
   691  func (bc *BlockChain) Stop() {
   692  	if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
   693  		return
   694  	}
   695  	// Unsubscribe all subscriptions registered from blockchain
   696  	bc.scope.Close()
   697  	close(bc.quit)
   698  	atomic.StoreInt32(&bc.procInterrupt, 1)
   699  
   700  	bc.wg.Wait()
   701  
   702  	// Ensure the state of a recent block is also stored to disk before exiting.
   703  	// We're writing three different states to catch different restart scenarios:
   704  	//  - HEAD:     So we don't need to reprocess any blocks in the general case
   705  	//  - HEAD-1:   So we don't do large reorgs if our HEAD becomes an uncle
   706  	//  - HEAD-127: So we have a hard limit on the number of blocks reexecuted
   707  	if !bc.cacheConfig.Disabled {
   708  		triedb := bc.stateCache.TrieDB()
   709  
   710  		for _, offset := range []uint64{0, 1, triesInMemory - 1} {
   711  			if number := bc.CurrentBlock().NumberU64(); number > offset {
   712  				recent := bc.GetBlockByNumber(number - offset)
   713  
   714  				log.Info("Writing cached state to disk", "block", recent.Number(), "hash", recent.Hash(), "root", recent.Root())
   715  				if err := triedb.Commit(recent.Root(), true); err != nil {
   716  					log.Error("Failed to commit recent state trie", "err", err)
   717  				}
   718  			}
   719  		}
   720  		for !bc.triegc.Empty() {
   721  			triedb.Dereference(bc.triegc.PopItem().(common.Hash))
   722  		}
   723  		if size, _ := triedb.Size(); size != 0 {
   724  			log.Error("Dangling trie nodes after full cleanup")
   725  		}
   726  	}
   727  	log.Info("Blockchain manager stopped")
   728  }
   729  
   730  func (bc *BlockChain) procFutureBlocks() {
   731  	blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
   732  	for _, hash := range bc.futureBlocks.Keys() {
   733  		if block, exist := bc.futureBlocks.Peek(hash); exist {
   734  			blocks = append(blocks, block.(*types.Block))
   735  		}
   736  	}
   737  	if len(blocks) > 0 {
   738  		types.BlockBy(types.Number).Sort(blocks)
   739  
   740  		// Insert one by one as chain insertion needs contiguous ancestry between blocks
   741  		for i := range blocks {
   742  			bc.InsertChain(blocks[i : i+1])
   743  		}
   744  	}
   745  }
   746  
   747  // WriteStatus status of write
   748  type WriteStatus byte
   749  
   750  const (
   751  	NonStatTy WriteStatus = iota
   752  	CanonStatTy
   753  	SideStatTy
   754  )
   755  
   756  // Rollback is designed to remove a chain of links from the database that aren't
   757  // certain enough to be valid.
   758  func (bc *BlockChain) Rollback(chain []common.Hash) {
   759  	bc.mu.Lock()
   760  	defer bc.mu.Unlock()
   761  
   762  	for i := len(chain) - 1; i >= 0; i-- {
   763  		hash := chain[i]
   764  
   765  		currentHeader := bc.hc.CurrentHeader()
   766  		if currentHeader.Hash() == hash {
   767  			bc.hc.SetCurrentHeader(bc.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1))
   768  		}
   769  		if currentFastBlock := bc.CurrentFastBlock(); currentFastBlock.Hash() == hash {
   770  			newFastBlock := bc.GetBlock(currentFastBlock.ParentHash(), currentFastBlock.NumberU64()-1)
   771  			bc.currentFastBlock.Store(newFastBlock)
   772  			rawdb.WriteHeadFastBlockHash(bc.db, newFastBlock.Hash())
   773  		}
   774  		if currentBlock := bc.CurrentBlock(); currentBlock.Hash() == hash {
   775  			newBlock := bc.GetBlock(currentBlock.ParentHash(), currentBlock.NumberU64()-1)
   776  			bc.currentBlock.Store(newBlock)
   777  			rawdb.WriteHeadBlockHash(bc.db, newBlock.Hash())
   778  		}
   779  	}
   780  }
   781  
   782  // SetReceiptsData computes all the non-consensus fields of the receipts
   783  func SetReceiptsData(config *params.ChainConfig, block *types.Block, receipts types.Receipts) error {
   784  	signer := types.MakeSigner(config, block.Number())
   785  
   786  	transactions, logIndex := block.Transactions(), uint(0)
   787  	if len(transactions) != len(receipts) {
   788  		return errors.New("transaction and receipt count mismatch")
   789  	}
   790  
   791  	for j := 0; j < len(receipts); j++ {
   792  		// The transaction hash can be retrieved from the transaction itself
   793  		receipts[j].TxHash = transactions[j].Hash()
   794  
   795  		// The contract address can be derived from the transaction itself
   796  		if transactions[j].To() == nil {
   797  			// Deriving the signer is expensive, only do if it's actually needed
   798  			from, _ := types.Sender(signer, transactions[j])
   799  			receipts[j].ContractAddress = crypto.CreateAddress(from, transactions[j].Nonce())
   800  		}
   801  		// The used gas can be calculated based on previous receipts
   802  		if j == 0 {
   803  			receipts[j].GasUsed = receipts[j].CumulativeGasUsed
   804  		} else {
   805  			receipts[j].GasUsed = receipts[j].CumulativeGasUsed - receipts[j-1].CumulativeGasUsed
   806  		}
   807  		// The derived log fields can simply be set from the block and transaction
   808  		for k := 0; k < len(receipts[j].Logs); k++ {
   809  			receipts[j].Logs[k].BlockNumber = block.NumberU64()
   810  			receipts[j].Logs[k].BlockHash = block.Hash()
   811  			receipts[j].Logs[k].TxHash = receipts[j].TxHash
   812  			receipts[j].Logs[k].TxIndex = uint(j)
   813  			receipts[j].Logs[k].Index = logIndex
   814  			logIndex++
   815  		}
   816  	}
   817  	return nil
   818  }
   819  
   820  // InsertReceiptChain attempts to complete an already existing header chain with
   821  // transaction and receipt data.
   822  func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
   823  	bc.wg.Add(1)
   824  	defer bc.wg.Done()
   825  
   826  	// Do a sanity check that the provided chain is actually ordered and linked
   827  	for i := 1; i < len(blockChain); i++ {
   828  		if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
   829  			log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
   830  				"prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
   831  			return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, blockChain[i-1].NumberU64(),
   832  				blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
   833  		}
   834  	}
   835  
   836  	var (
   837  		stats = struct{ processed, ignored int32 }{}
   838  		start = time.Now()
   839  		bytes = 0
   840  		batch = bc.db.NewBatch()
   841  	)
   842  	for i, block := range blockChain {
   843  		receipts := receiptChain[i]
   844  		// Short circuit insertion if shutting down or processing failed
   845  		if atomic.LoadInt32(&bc.procInterrupt) == 1 {
   846  			return 0, nil
   847  		}
   848  		// Short circuit if the owner header is unknown
   849  		if !bc.HasHeader(block.Hash(), block.NumberU64()) {
   850  			return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
   851  		}
   852  		// Skip if the entire data is already known
   853  		if bc.HasBlock(block.Hash(), block.NumberU64()) {
   854  			stats.ignored++
   855  			continue
   856  		}
   857  		// Compute all the non-consensus fields of the receipts
   858  		if err := SetReceiptsData(bc.chainConfig, block, receipts); err != nil {
   859  			return i, fmt.Errorf("failed to set receipts data: %v", err)
   860  		}
   861  		// Write all the data out into the database
   862  		rawdb.WriteBody(batch, block.Hash(), block.NumberU64(), block.Body())
   863  		rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
   864  		rawdb.WriteTxLookupEntries(batch, block)
   865  
   866  		stats.processed++
   867  
   868  		if batch.ValueSize() >= ethdb.IdealBatchSize {
   869  			if err := batch.Write(); err != nil {
   870  				return 0, err
   871  			}
   872  			bytes += batch.ValueSize()
   873  			batch.Reset()
   874  		}
   875  	}
   876  	if batch.ValueSize() > 0 {
   877  		bytes += batch.ValueSize()
   878  		if err := batch.Write(); err != nil {
   879  			return 0, err
   880  		}
   881  	}
   882  
   883  	// Update the head fast sync block if better
   884  	bc.mu.Lock()
   885  	head := blockChain[len(blockChain)-1]
   886  	if td := bc.GetTd(head.Hash(), head.NumberU64()); td != nil { // Rewind may have occurred, skip in that case
   887  		currentFastBlock := bc.CurrentFastBlock()
   888  		if bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()).Cmp(td) < 0 {
   889  			rawdb.WriteHeadFastBlockHash(bc.db, head.Hash())
   890  			bc.currentFastBlock.Store(head)
   891  		}
   892  	}
   893  	bc.mu.Unlock()
   894  
   895  	context := []interface{}{
   896  		"count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)),
   897  		"number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(head.Time().Int64(), 0)),
   898  		"size", common.StorageSize(bytes),
   899  	}
   900  	if stats.ignored > 0 {
   901  		context = append(context, []interface{}{"ignored", stats.ignored}...)
   902  	}
   903  	log.Info("Imported new block receipts", context...)
   904  
   905  	return 0, nil
   906  }
   907  
   908  var lastWrite uint64
   909  
   910  // WriteBlockWithoutState writes only the block and its metadata to the database,
   911  // but does not write any state. This is used to construct competing side forks
   912  // up to the point where they exceed the canonical total difficulty.
   913  func (bc *BlockChain) WriteBlockWithoutState(block *types.Block, td *big.Int) (err error) {
   914  	bc.wg.Add(1)
   915  	defer bc.wg.Done()
   916  
   917  	if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), td); err != nil {
   918  		return err
   919  	}
   920  	rawdb.WriteBlock(bc.db, block)
   921  
   922  	return nil
   923  }
   924  
   925  // WriteBlockWithState writes the block and all associated state to the database.
   926  func (bc *BlockChain) WriteBlockWithState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
   927  	bc.wg.Add(1)
   928  	defer bc.wg.Done()
   929  
   930  	// Calculate the total difficulty of the block
   931  	ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
   932  	if ptd == nil {
   933  		return NonStatTy, consensus.ErrUnknownAncestor
   934  	}
   935  	// Make sure no inconsistent state is leaked during insertion
   936  	bc.mu.Lock()
   937  	defer bc.mu.Unlock()
   938  
   939  	currentBlock := bc.CurrentBlock()
   940  	localTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64())
   941  	externTd := new(big.Int).Add(block.Difficulty(), ptd)
   942  
   943  	// Irrelevant of the canonical status, write the block itself to the database
   944  	if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil {
   945  		return NonStatTy, err
   946  	}
   947  	rawdb.WriteBlock(bc.db, block)
   948  
   949  	root, err := state.Commit(bc.chainConfig.IsEIP158(block.Number()))
   950  	if err != nil {
   951  		return NonStatTy, err
   952  	}
   953  	triedb := bc.stateCache.TrieDB()
   954  
   955  	// If we're running an archive node, always flush
   956  	if bc.cacheConfig.Disabled {
   957  		if err := triedb.Commit(root, false); err != nil {
   958  			return NonStatTy, err
   959  		}
   960  	} else {
   961  		// Full but not archive node, do proper garbage collection
   962  		triedb.Reference(root, common.Hash{}) // metadata reference to keep trie alive
   963  		bc.triegc.Push(root, -int64(block.NumberU64()))
   964  
   965  		if current := block.NumberU64(); current > triesInMemory {
   966  			// If we exceeded our memory allowance, flush matured singleton nodes to disk
   967  			var (
   968  				nodes, imgs = triedb.Size()
   969  				limit       = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * 1024 * 1024
   970  			)
   971  			if nodes > limit || imgs > 4*1024*1024 {
   972  				triedb.Cap(limit - ethdb.IdealBatchSize)
   973  			}
   974  			// Find the next state trie we need to commit
   975  			header := bc.GetHeaderByNumber(current - triesInMemory)
   976  			chosen := header.Number.Uint64()
   977  
   978  			// If we exceeded out time allowance, flush an entire trie to disk
   979  			if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
   980  				// If we're exceeding limits but haven't reached a large enough memory gap,
   981  				// warn the user that the system is becoming unstable.
   982  				if chosen < lastWrite+triesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
   983  					log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/triesInMemory)
   984  				}
   985  				// Flush an entire trie and restart the counters
   986  				triedb.Commit(header.Root, true)
   987  				lastWrite = chosen
   988  				bc.gcproc = 0
   989  			}
   990  			// Garbage collect anything below our required write retention
   991  			for !bc.triegc.Empty() {
   992  				root, number := bc.triegc.Pop()
   993  				if uint64(-number) > chosen {
   994  					bc.triegc.Push(root, number)
   995  					break
   996  				}
   997  				triedb.Dereference(root.(common.Hash))
   998  			}
   999  		}
  1000  	}
  1001  
  1002  	// Write other block data using a batch.
  1003  	batch := bc.db.NewBatch()
  1004  	rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
  1005  
  1006  	// If the total difficulty is higher than our known, add it to the canonical chain
  1007  	// Second clause in the if statement reduces the vulnerability to selfish mining.
  1008  	// Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  1009  	reorg := externTd.Cmp(localTd) > 0
  1010  	currentBlock = bc.CurrentBlock()
  1011  	if !reorg && externTd.Cmp(localTd) == 0 {
  1012  		// Split same-difficulty blocks by number, then preferentially select
  1013  		// the block generated by the local miner as the canonical block.
  1014  		if block.NumberU64() < currentBlock.NumberU64() {
  1015  			reorg = true
  1016  		} else if block.NumberU64() == currentBlock.NumberU64() {
  1017  			var currentPreserve, blockPreserve bool
  1018  			if bc.shouldPreserve != nil {
  1019  				currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  1020  			}
  1021  			reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  1022  		}
  1023  	}
  1024  	if reorg {
  1025  		// Reorganise the chain if the parent is not the head block
  1026  		if block.ParentHash() != currentBlock.Hash() {
  1027  			if err := bc.reorg(currentBlock, block); err != nil {
  1028  				return NonStatTy, err
  1029  			}
  1030  		}
  1031  		// Write the positional metadata for transaction/receipt lookups and preimages
  1032  		rawdb.WriteTxLookupEntries(batch, block)
  1033  		rawdb.WritePreimages(batch, state.Preimages())
  1034  
  1035  		status = CanonStatTy
  1036  	} else {
  1037  		status = SideStatTy
  1038  	}
  1039  	if err := batch.Write(); err != nil {
  1040  		return NonStatTy, err
  1041  	}
  1042  
  1043  	// Set new head.
  1044  	if status == CanonStatTy {
  1045  		bc.insert(block)
  1046  	}
  1047  	bc.futureBlocks.Remove(block.Hash())
  1048  	return status, nil
  1049  }
  1050  
  1051  // addFutureBlock checks if the block is within the max allowed window to get
  1052  // accepted for future processing, and returns an error if the block is too far
  1053  // ahead and was not added.
  1054  func (bc *BlockChain) addFutureBlock(block *types.Block) error {
  1055  	max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
  1056  	if block.Time().Cmp(max) > 0 {
  1057  		return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max)
  1058  	}
  1059  	bc.futureBlocks.Add(block.Hash(), block)
  1060  	return nil
  1061  }
  1062  
  1063  // InsertChain attempts to insert the given batch of blocks in to the canonical
  1064  // chain or, otherwise, create a fork. If an error is returned it will return
  1065  // the index number of the failing block as well an error describing what went
  1066  // wrong.
  1067  //
  1068  // After insertion is done, all accumulated events will be fired.
  1069  func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  1070  	// Sanity check that we have something meaningful to import
  1071  	if len(chain) == 0 {
  1072  		return 0, nil
  1073  	}
  1074  	// Do a sanity check that the provided chain is actually ordered and linked
  1075  	for i := 1; i < len(chain); i++ {
  1076  		if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() {
  1077  			// Chain broke ancestry, log a message (programming error) and skip insertion
  1078  			log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(),
  1079  				"parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash())
  1080  
  1081  			return 0, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].NumberU64(),
  1082  				chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4])
  1083  		}
  1084  	}
  1085  	// Pre-checks passed, start the full block imports
  1086  	bc.wg.Add(1)
  1087  	bc.chainmu.Lock()
  1088  	n, events, logs, err := bc.insertChain(chain, true)
  1089  	bc.chainmu.Unlock()
  1090  	bc.wg.Done()
  1091  
  1092  	bc.PostChainEvents(events, logs)
  1093  	return n, err
  1094  }
  1095  
  1096  // insertChain is the internal implementation of insertChain, which assumes that
  1097  // 1) chains are contiguous, and 2) The chain mutex is held.
  1098  //
  1099  // This method is split out so that import batches that require re-injecting
  1100  // historical blocks can do so without releasing the lock, which could lead to
  1101  // racey behaviour. If a sidechain import is in progress, and the historic state
  1102  // is imported, but then new canon-head is added before the actual sidechain
  1103  // completes, then the historic state could be pruned again
  1104  func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []interface{}, []*types.Log, error) {
  1105  	// If the chain is terminating, don't even bother starting u
  1106  	if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1107  		return 0, nil, nil, nil
  1108  	}
  1109  	// Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  1110  	senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain)
  1111  
  1112  	// A queued approach to delivering events. This is generally
  1113  	// faster than direct delivery and requires much less mutex
  1114  	// acquiring.
  1115  	var (
  1116  		stats         = insertStats{startTime: mclock.Now()}
  1117  		events        = make([]interface{}, 0, len(chain))
  1118  		lastCanon     *types.Block
  1119  		coalescedLogs []*types.Log
  1120  	)
  1121  	// Start the parallel header verifier
  1122  	headers := make([]*types.Header, len(chain))
  1123  	seals := make([]bool, len(chain))
  1124  
  1125  	for i, block := range chain {
  1126  		headers[i] = block.Header()
  1127  		seals[i] = verifySeals
  1128  	}
  1129  	abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  1130  	defer close(abort)
  1131  
  1132  	// Peek the error for the first block to decide the directing import logic
  1133  	it := newInsertIterator(chain, results, bc.Validator())
  1134  
  1135  	block, err := it.next()
  1136  	switch {
  1137  	// First block is pruned, insert as sidechain and reorg only if TD grows enough
  1138  	case err == consensus.ErrPrunedAncestor:
  1139  		return bc.insertSidechain(it)
  1140  
  1141  	// First block is future, shove it (and all children) to the future queue (unknown ancestor)
  1142  	case err == consensus.ErrFutureBlock || (err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(it.first().ParentHash())):
  1143  		for block != nil && (it.index == 0 || err == consensus.ErrUnknownAncestor) {
  1144  			if err := bc.addFutureBlock(block); err != nil {
  1145  				return it.index, events, coalescedLogs, err
  1146  			}
  1147  			block, err = it.next()
  1148  		}
  1149  		stats.queued += it.processed()
  1150  		stats.ignored += it.remaining()
  1151  
  1152  		// If there are any still remaining, mark as ignored
  1153  		return it.index, events, coalescedLogs, err
  1154  
  1155  	// First block (and state) is known
  1156  	//   1. We did a roll-back, and should now do a re-import
  1157  	//   2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
  1158  	// 	    from the canonical chain, which has not been verified.
  1159  	case err == ErrKnownBlock:
  1160  		// Skip all known blocks that behind us
  1161  		current := bc.CurrentBlock().NumberU64()
  1162  
  1163  		for block != nil && err == ErrKnownBlock && current >= block.NumberU64() {
  1164  			stats.ignored++
  1165  			block, err = it.next()
  1166  		}
  1167  		// Falls through to the block import
  1168  
  1169  	// Some other error occurred, abort
  1170  	case err != nil:
  1171  		stats.ignored += len(it.chain)
  1172  		bc.reportBlock(block, nil, err)
  1173  		return it.index, events, coalescedLogs, err
  1174  	}
  1175  	// No validation errors for the first block (or chain prefix skipped)
  1176  	for ; block != nil && err == nil; block, err = it.next() {
  1177  		// If the chain is terminating, stop processing blocks
  1178  		if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1179  			log.Debug("Premature abort during blocks processing")
  1180  			break
  1181  		}
  1182  		// If the header is a banned one, straight out abort
  1183  		if BadHashes[block.Hash()] {
  1184  			bc.reportBlock(block, nil, ErrBlacklistedHash)
  1185  			return it.index, events, coalescedLogs, ErrBlacklistedHash
  1186  		}
  1187  		// Retrieve the parent block and it's state to execute on top
  1188  		start := time.Now()
  1189  
  1190  		parent := it.previous()
  1191  		if parent == nil {
  1192  			parent = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  1193  		}
  1194  		state, err := state.New(parent.Root(), bc.stateCache)
  1195  		if err != nil {
  1196  			return it.index, events, coalescedLogs, err
  1197  		}
  1198  		// Process block using the parent state as reference point.
  1199  		t0 := time.Now()
  1200  		receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig)
  1201  		t1 := time.Now()
  1202  		if err != nil {
  1203  			bc.reportBlock(block, receipts, err)
  1204  			return it.index, events, coalescedLogs, err
  1205  		}
  1206  		// Validate the state using the default validator
  1207  		if err := bc.Validator().ValidateState(block, parent, state, receipts, usedGas); err != nil {
  1208  			bc.reportBlock(block, receipts, err)
  1209  			return it.index, events, coalescedLogs, err
  1210  		}
  1211  		t2 := time.Now()
  1212  		proctime := time.Since(start)
  1213  
  1214  		// Write the block to the chain and get the status.
  1215  		status, err := bc.WriteBlockWithState(block, receipts, state)
  1216  		t3 := time.Now()
  1217  		if err != nil {
  1218  			return it.index, events, coalescedLogs, err
  1219  		}
  1220  		blockInsertTimer.UpdateSince(start)
  1221  		blockExecutionTimer.Update(t1.Sub(t0))
  1222  		blockValidationTimer.Update(t2.Sub(t1))
  1223  		blockWriteTimer.Update(t3.Sub(t2))
  1224  		switch status {
  1225  		case CanonStatTy:
  1226  			log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
  1227  				"uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1228  				"elapsed", common.PrettyDuration(time.Since(start)),
  1229  				"root", block.Root())
  1230  
  1231  			coalescedLogs = append(coalescedLogs, logs...)
  1232  			events = append(events, ChainEvent{block, block.Hash(), logs})
  1233  			lastCanon = block
  1234  
  1235  			// Only count canonical blocks for GC processing time
  1236  			bc.gcproc += proctime
  1237  
  1238  		case SideStatTy:
  1239  			log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(),
  1240  				"diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1241  				"txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1242  				"root", block.Root())
  1243  			events = append(events, ChainSideEvent{block})
  1244  		}
  1245  		blockInsertTimer.UpdateSince(start)
  1246  		stats.processed++
  1247  		stats.usedGas += usedGas
  1248  
  1249  		cache, _ := bc.stateCache.TrieDB().Size()
  1250  		stats.report(chain, it.index, cache)
  1251  	}
  1252  	// Any blocks remaining here? The only ones we care about are the future ones
  1253  	if block != nil && err == consensus.ErrFutureBlock {
  1254  		if err := bc.addFutureBlock(block); err != nil {
  1255  			return it.index, events, coalescedLogs, err
  1256  		}
  1257  		block, err = it.next()
  1258  
  1259  		for ; block != nil && err == consensus.ErrUnknownAncestor; block, err = it.next() {
  1260  			if err := bc.addFutureBlock(block); err != nil {
  1261  				return it.index, events, coalescedLogs, err
  1262  			}
  1263  			stats.queued++
  1264  		}
  1265  	}
  1266  	stats.ignored += it.remaining()
  1267  
  1268  	// Append a single chain head event if we've progressed the chain
  1269  	if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1270  		events = append(events, ChainHeadEvent{lastCanon})
  1271  	}
  1272  	return it.index, events, coalescedLogs, err
  1273  }
  1274  
  1275  // insertSidechain is called when an import batch hits upon a pruned ancestor
  1276  // error, which happens when a sidechain with a sufficiently old fork-block is
  1277  // found.
  1278  //
  1279  // The method writes all (header-and-body-valid) blocks to disk, then tries to
  1280  // switch over to the new chain if the TD exceeded the current chain.
  1281  func (bc *BlockChain) insertSidechain(it *insertIterator) (int, []interface{}, []*types.Log, error) {
  1282  	var (
  1283  		externTd *big.Int
  1284  		current  = bc.CurrentBlock().NumberU64()
  1285  	)
  1286  	// The first sidechain block error is already verified to be ErrPrunedAncestor.
  1287  	// Since we don't import them here, we expect ErrUnknownAncestor for the remaining
  1288  	// ones. Any other errors means that the block is invalid, and should not be written
  1289  	// to disk.
  1290  	block, err := it.current(), consensus.ErrPrunedAncestor
  1291  	for ; block != nil && (err == consensus.ErrPrunedAncestor); block, err = it.next() {
  1292  		// Check the canonical state root for that number
  1293  		if number := block.NumberU64(); current >= number {
  1294  			if canonical := bc.GetBlockByNumber(number); canonical != nil && canonical.Root() == block.Root() {
  1295  				// This is most likely a shadow-state attack. When a fork is imported into the
  1296  				// database, and it eventually reaches a block height which is not pruned, we
  1297  				// just found that the state already exist! This means that the sidechain block
  1298  				// refers to a state which already exists in our canon chain.
  1299  				//
  1300  				// If left unchecked, we would now proceed importing the blocks, without actually
  1301  				// having verified the state of the previous blocks.
  1302  				log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root())
  1303  
  1304  				// If someone legitimately side-mines blocks, they would still be imported as usual. However,
  1305  				// we cannot risk writing unverified blocks to disk when they obviously target the pruning
  1306  				// mechanism.
  1307  				return it.index, nil, nil, errors.New("sidechain ghost-state attack")
  1308  			}
  1309  		}
  1310  		if externTd == nil {
  1311  			externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1312  		}
  1313  		externTd = new(big.Int).Add(externTd, block.Difficulty())
  1314  
  1315  		if !bc.HasBlock(block.Hash(), block.NumberU64()) {
  1316  			start := time.Now()
  1317  			if err := bc.WriteBlockWithoutState(block, externTd); err != nil {
  1318  				return it.index, nil, nil, err
  1319  			}
  1320  			log.Debug("Inserted sidechain block", "number", block.Number(), "hash", block.Hash(),
  1321  				"diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1322  				"txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1323  				"root", block.Root())
  1324  		}
  1325  	}
  1326  	// At this point, we've written all sidechain blocks to database. Loop ended
  1327  	// either on some other error or all were processed. If there was some other
  1328  	// error, we can ignore the rest of those blocks.
  1329  	//
  1330  	// If the externTd was larger than our local TD, we now need to reimport the previous
  1331  	// blocks to regenerate the required state
  1332  	localTd := bc.GetTd(bc.CurrentBlock().Hash(), current)
  1333  	if localTd.Cmp(externTd) > 0 {
  1334  		log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().NumberU64(), "sidetd", externTd, "localtd", localTd)
  1335  		return it.index, nil, nil, err
  1336  	}
  1337  	// Gather all the sidechain hashes (full blocks may be memory heavy)
  1338  	var (
  1339  		hashes  []common.Hash
  1340  		numbers []uint64
  1341  	)
  1342  	parent := bc.GetHeader(it.previous().Hash(), it.previous().NumberU64())
  1343  	for parent != nil && !bc.HasState(parent.Root) {
  1344  		hashes = append(hashes, parent.Hash())
  1345  		numbers = append(numbers, parent.Number.Uint64())
  1346  
  1347  		parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1)
  1348  	}
  1349  	if parent == nil {
  1350  		return it.index, nil, nil, errors.New("missing parent")
  1351  	}
  1352  	// Import all the pruned blocks to make the state available
  1353  	var (
  1354  		blocks []*types.Block
  1355  		memory common.StorageSize
  1356  	)
  1357  	for i := len(hashes) - 1; i >= 0; i-- {
  1358  		// Append the next block to our batch
  1359  		block := bc.GetBlock(hashes[i], numbers[i])
  1360  
  1361  		blocks = append(blocks, block)
  1362  		memory += block.Size()
  1363  
  1364  		// If memory use grew too large, import and continue. Sadly we need to discard
  1365  		// all raised events and logs from notifications since we're too heavy on the
  1366  		// memory here.
  1367  		if len(blocks) >= 2048 || memory > 64*1024*1024 {
  1368  			log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64())
  1369  			if _, _, _, err := bc.insertChain(blocks, false); err != nil {
  1370  				return 0, nil, nil, err
  1371  			}
  1372  			blocks, memory = blocks[:0], 0
  1373  
  1374  			// If the chain is terminating, stop processing blocks
  1375  			if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1376  				log.Debug("Premature abort during blocks processing")
  1377  				return 0, nil, nil, nil
  1378  			}
  1379  		}
  1380  	}
  1381  	if len(blocks) > 0 {
  1382  		log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64())
  1383  		return bc.insertChain(blocks, false)
  1384  	}
  1385  	return 0, nil, nil, nil
  1386  }
  1387  
  1388  // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  1389  // to be part of the new canonical chain and accumulates potential missing transactions and post an
  1390  // event about them
  1391  func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  1392  	var (
  1393  		newChain    types.Blocks
  1394  		oldChain    types.Blocks
  1395  		commonBlock *types.Block
  1396  		deletedTxs  types.Transactions
  1397  		deletedLogs []*types.Log
  1398  		// collectLogs collects the logs that were generated during the
  1399  		// processing of the block that corresponds with the given hash.
  1400  		// These logs are later announced as deleted.
  1401  		collectLogs = func(hash common.Hash) {
  1402  			// Coalesce logs and set 'Removed'.
  1403  			number := bc.hc.GetBlockNumber(hash)
  1404  			if number == nil {
  1405  				return
  1406  			}
  1407  			receipts := rawdb.ReadReceipts(bc.db, hash, *number)
  1408  			for _, receipt := range receipts {
  1409  				for _, log := range receipt.Logs {
  1410  					del := *log
  1411  					del.Removed = true
  1412  					deletedLogs = append(deletedLogs, &del)
  1413  				}
  1414  			}
  1415  		}
  1416  	)
  1417  
  1418  	// first reduce whoever is higher bound
  1419  	if oldBlock.NumberU64() > newBlock.NumberU64() {
  1420  		// reduce old chain
  1421  		for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  1422  			oldChain = append(oldChain, oldBlock)
  1423  			deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1424  
  1425  			collectLogs(oldBlock.Hash())
  1426  		}
  1427  	} else {
  1428  		// reduce new chain and append new chain blocks for inserting later on
  1429  		for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  1430  			newChain = append(newChain, newBlock)
  1431  		}
  1432  	}
  1433  	if oldBlock == nil {
  1434  		return fmt.Errorf("Invalid old chain")
  1435  	}
  1436  	if newBlock == nil {
  1437  		return fmt.Errorf("Invalid new chain")
  1438  	}
  1439  
  1440  	for {
  1441  		if oldBlock.Hash() == newBlock.Hash() {
  1442  			commonBlock = oldBlock
  1443  			break
  1444  		}
  1445  
  1446  		oldChain = append(oldChain, oldBlock)
  1447  		newChain = append(newChain, newBlock)
  1448  		deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1449  		collectLogs(oldBlock.Hash())
  1450  
  1451  		oldBlock, newBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1452  		if oldBlock == nil {
  1453  			return fmt.Errorf("Invalid old chain")
  1454  		}
  1455  		if newBlock == nil {
  1456  			return fmt.Errorf("Invalid new chain")
  1457  		}
  1458  	}
  1459  	// Ensure the user sees large reorgs
  1460  	if len(oldChain) > 0 && len(newChain) > 0 {
  1461  		logFn := log.Debug
  1462  		if len(oldChain) > 63 {
  1463  			logFn = log.Warn
  1464  		}
  1465  		logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1466  			"drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1467  	} else {
  1468  		log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1469  	}
  1470  	// Insert the new chain, taking care of the proper incremental order
  1471  	var addedTxs types.Transactions
  1472  	for i := len(newChain) - 1; i >= 0; i-- {
  1473  		// insert the block in the canonical way, re-writing history
  1474  		bc.insert(newChain[i])
  1475  		// write lookup entries for hash based transaction/receipt searches
  1476  		rawdb.WriteTxLookupEntries(bc.db, newChain[i])
  1477  		addedTxs = append(addedTxs, newChain[i].Transactions()...)
  1478  	}
  1479  	// calculate the difference between deleted and added transactions
  1480  	diff := types.TxDifference(deletedTxs, addedTxs)
  1481  	// When transactions get deleted from the database that means the
  1482  	// receipts that were created in the fork must also be deleted
  1483  	batch := bc.db.NewBatch()
  1484  	for _, tx := range diff {
  1485  		rawdb.DeleteTxLookupEntry(batch, tx.Hash())
  1486  	}
  1487  	batch.Write()
  1488  
  1489  	if len(deletedLogs) > 0 {
  1490  		go bc.rmLogsFeed.Send(RemovedLogsEvent{deletedLogs})
  1491  	}
  1492  	if len(oldChain) > 0 {
  1493  		go func() {
  1494  			for _, block := range oldChain {
  1495  				bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1496  			}
  1497  		}()
  1498  	}
  1499  
  1500  	return nil
  1501  }
  1502  
  1503  // PostChainEvents iterates over the events generated by a chain insertion and
  1504  // posts them into the event feed.
  1505  // TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock.
  1506  func (bc *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log) {
  1507  	// post event logs for further processing
  1508  	if logs != nil {
  1509  		bc.logsFeed.Send(logs)
  1510  	}
  1511  	for _, event := range events {
  1512  		switch ev := event.(type) {
  1513  		case ChainEvent:
  1514  			bc.chainFeed.Send(ev)
  1515  
  1516  		case ChainHeadEvent:
  1517  			bc.chainHeadFeed.Send(ev)
  1518  
  1519  		case ChainSideEvent:
  1520  			bc.chainSideFeed.Send(ev)
  1521  		}
  1522  	}
  1523  }
  1524  
  1525  func (bc *BlockChain) update() {
  1526  	futureTimer := time.NewTicker(5 * time.Second)
  1527  	defer futureTimer.Stop()
  1528  	for {
  1529  		select {
  1530  		case <-futureTimer.C:
  1531  			bc.procFutureBlocks()
  1532  		case <-bc.quit:
  1533  			return
  1534  		}
  1535  	}
  1536  }
  1537  
  1538  // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1539  func (bc *BlockChain) BadBlocks() []*types.Block {
  1540  	blocks := make([]*types.Block, 0, bc.badBlocks.Len())
  1541  	for _, hash := range bc.badBlocks.Keys() {
  1542  		if blk, exist := bc.badBlocks.Peek(hash); exist {
  1543  			block := blk.(*types.Block)
  1544  			blocks = append(blocks, block)
  1545  		}
  1546  	}
  1547  	return blocks
  1548  }
  1549  
  1550  // addBadBlock adds a bad block to the bad-block LRU cache
  1551  func (bc *BlockChain) addBadBlock(block *types.Block) {
  1552  	bc.badBlocks.Add(block.Hash(), block)
  1553  }
  1554  
  1555  // reportBlock logs a bad block error.
  1556  func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1557  	bc.addBadBlock(block)
  1558  
  1559  	var receiptString string
  1560  	for i, receipt := range receipts {
  1561  		receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
  1562  			i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
  1563  			receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
  1564  	}
  1565  	log.Error(fmt.Sprintf(`
  1566  ########## BAD BLOCK #########
  1567  Chain config: %v
  1568  
  1569  Number: %v
  1570  Hash: 0x%x
  1571  %v
  1572  
  1573  Error: %v
  1574  ##############################
  1575  `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  1576  }
  1577  
  1578  // InsertHeaderChain attempts to insert the given header chain in to the local
  1579  // chain, possibly creating a reorg. If an error is returned, it will return the
  1580  // index number of the failing header as well an error describing what went wrong.
  1581  //
  1582  // The verify parameter can be used to fine tune whether nonce verification
  1583  // should be done or not. The reason behind the optional check is because some
  1584  // of the header retrieval mechanisms already need to verify nonces, as well as
  1585  // because nonces can be verified sparsely, not needing to check each.
  1586  func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1587  	start := time.Now()
  1588  	if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1589  		return i, err
  1590  	}
  1591  
  1592  	// Make sure only one thread manipulates the chain at once
  1593  	bc.chainmu.Lock()
  1594  	defer bc.chainmu.Unlock()
  1595  
  1596  	bc.wg.Add(1)
  1597  	defer bc.wg.Done()
  1598  
  1599  	whFunc := func(header *types.Header) error {
  1600  		bc.mu.Lock()
  1601  		defer bc.mu.Unlock()
  1602  
  1603  		_, err := bc.hc.WriteHeader(header)
  1604  		return err
  1605  	}
  1606  
  1607  	return bc.hc.InsertHeaderChain(chain, whFunc, start)
  1608  }
  1609  
  1610  // writeHeader writes a header into the local chain, given that its parent is
  1611  // already known. If the total difficulty of the newly inserted header becomes
  1612  // greater than the current known TD, the canonical chain is re-routed.
  1613  //
  1614  // Note: This method is not concurrent-safe with inserting blocks simultaneously
  1615  // into the chain, as side effects caused by reorganisations cannot be emulated
  1616  // without the real blocks. Hence, writing headers directly should only be done
  1617  // in two scenarios: pure-header mode of operation (light clients), or properly
  1618  // separated header/block phases (non-archive clients).
  1619  func (bc *BlockChain) writeHeader(header *types.Header) error {
  1620  	bc.wg.Add(1)
  1621  	defer bc.wg.Done()
  1622  
  1623  	bc.mu.Lock()
  1624  	defer bc.mu.Unlock()
  1625  
  1626  	_, err := bc.hc.WriteHeader(header)
  1627  	return err
  1628  }
  1629  
  1630  // CurrentHeader retrieves the current head header of the canonical chain. The
  1631  // header is retrieved from the HeaderChain's internal cache.
  1632  func (bc *BlockChain) CurrentHeader() *types.Header {
  1633  	return bc.hc.CurrentHeader()
  1634  }
  1635  
  1636  // GetTd retrieves a block's total difficulty in the canonical chain from the
  1637  // database by hash and number, caching it if found.
  1638  func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1639  	return bc.hc.GetTd(hash, number)
  1640  }
  1641  
  1642  // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1643  // database by hash, caching it if found.
  1644  func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1645  	return bc.hc.GetTdByHash(hash)
  1646  }
  1647  
  1648  // GetHeader retrieves a block header from the database by hash and number,
  1649  // caching it if found.
  1650  func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1651  	return bc.hc.GetHeader(hash, number)
  1652  }
  1653  
  1654  // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1655  // found.
  1656  func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1657  	return bc.hc.GetHeaderByHash(hash)
  1658  }
  1659  
  1660  // HasHeader checks if a block header is present in the database or not, caching
  1661  // it if present.
  1662  func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  1663  	return bc.hc.HasHeader(hash, number)
  1664  }
  1665  
  1666  // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1667  // hash, fetching towards the genesis block.
  1668  func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1669  	return bc.hc.GetBlockHashesFromHash(hash, max)
  1670  }
  1671  
  1672  // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  1673  // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  1674  // number of blocks to be individually checked before we reach the canonical chain.
  1675  //
  1676  // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  1677  func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  1678  	bc.chainmu.Lock()
  1679  	defer bc.chainmu.Unlock()
  1680  
  1681  	return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  1682  }
  1683  
  1684  // GetHeaderByNumber retrieves a block header from the database by number,
  1685  // caching it (associated with its hash) if found.
  1686  func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1687  	return bc.hc.GetHeaderByNumber(number)
  1688  }
  1689  
  1690  // Config retrieves the blockchain's chain configuration.
  1691  func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  1692  
  1693  // Engine retrieves the blockchain's consensus engine.
  1694  func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  1695  
  1696  // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  1697  func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  1698  	return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  1699  }
  1700  
  1701  // SubscribeChainEvent registers a subscription of ChainEvent.
  1702  func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  1703  	return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  1704  }
  1705  
  1706  // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  1707  func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  1708  	return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  1709  }
  1710  
  1711  // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  1712  func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  1713  	return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  1714  }
  1715  
  1716  // SubscribeLogsEvent registers a subscription of []*types.Log.
  1717  func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  1718  	return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  1719  }