github.com/alexdevranger/node-1.8.27@v0.0.0-20221128213301-aa5841e41d2d/core/blockchain.go (about)

     1  // Copyright 2014 The go-ethereum Authors
     2  // This file is part of the go-dubxcoin library.
     3  //
     4  // The go-dubxcoin 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-dubxcoin 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-dubxcoin 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/alexdevranger/node-1.8.27/common"
    31  	"github.com/alexdevranger/node-1.8.27/common/mclock"
    32  	"github.com/alexdevranger/node-1.8.27/common/prque"
    33  	"github.com/alexdevranger/node-1.8.27/consensus"
    34  	"github.com/alexdevranger/node-1.8.27/core/rawdb"
    35  	"github.com/alexdevranger/node-1.8.27/core/state"
    36  	"github.com/alexdevranger/node-1.8.27/core/types"
    37  	"github.com/alexdevranger/node-1.8.27/core/vm"
    38  	"github.com/alexdevranger/node-1.8.27/crypto"
    39  	"github.com/alexdevranger/node-1.8.27/ethdb"
    40  	"github.com/alexdevranger/node-1.8.27/event"
    41  	"github.com/alexdevranger/node-1.8.27/log"
    42  	"github.com/alexdevranger/node-1.8.27/metrics"
    43  	"github.com/alexdevranger/node-1.8.27/params"
    44  	"github.com/alexdevranger/node-1.8.27/rlp"
    45  	"github.com/alexdevranger/node-1.8.27/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(int64(currentHeader.Time), 0)))
   271  	log.Info("Loaded most recent local full block", "number", currentBlock.Number(), "hash", currentBlock.Hash(), "td", blockTd, "age", common.PrettyAge(time.Unix(int64(currentBlock.Time()), 0)))
   272  	log.Info("Loaded most recent local fast block", "number", currentFastBlock.Number(), "hash", currentFastBlock.Hash(), "td", fastTd, "age", common.PrettyAge(time.Unix(int64(currentFastBlock.Time()), 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(int64(head.Time()), 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  			chosen := current - triesInMemory
   976  
   977  			// If we exceeded out time allowance, flush an entire trie to disk
   978  			if bc.gcproc > bc.cacheConfig.TrieTimeLimit {
   979  				// If the header is missing (canonical chain behind), we're reorging a low
   980  				// diff sidechain. Suspend committing until this operation is completed.
   981  				header := bc.GetHeaderByNumber(chosen)
   982  				if header == nil {
   983  					log.Warn("Reorg in progress, trie commit postponed", "number", chosen)
   984  				} else {
   985  					// If we're exceeding limits but haven't reached a large enough memory gap,
   986  					// warn the user that the system is becoming unstable.
   987  					if chosen < lastWrite+triesInMemory && bc.gcproc >= 2*bc.cacheConfig.TrieTimeLimit {
   988  						log.Info("State in memory for too long, committing", "time", bc.gcproc, "allowance", bc.cacheConfig.TrieTimeLimit, "optimum", float64(chosen-lastWrite)/triesInMemory)
   989  					}
   990  					// Flush an entire trie and restart the counters
   991  					triedb.Commit(header.Root, true)
   992  					lastWrite = chosen
   993  					bc.gcproc = 0
   994  				}
   995  			}
   996  			// Garbage collect anything below our required write retention
   997  			for !bc.triegc.Empty() {
   998  				root, number := bc.triegc.Pop()
   999  				if uint64(-number) > chosen {
  1000  					bc.triegc.Push(root, number)
  1001  					break
  1002  				}
  1003  				triedb.Dereference(root.(common.Hash))
  1004  			}
  1005  		}
  1006  	}
  1007  
  1008  	// Write other block data using a batch.
  1009  	batch := bc.db.NewBatch()
  1010  	rawdb.WriteReceipts(batch, block.Hash(), block.NumberU64(), receipts)
  1011  
  1012  	// If the total difficulty is higher than our known, add it to the canonical chain
  1013  	// Second clause in the if statement reduces the vulnerability to selfish mining.
  1014  	// Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
  1015  	reorg := externTd.Cmp(localTd) > 0
  1016  	currentBlock = bc.CurrentBlock()
  1017  	if !reorg && externTd.Cmp(localTd) == 0 {
  1018  		// Split same-difficulty blocks by number, then preferentially select
  1019  		// the block generated by the local miner as the canonical block.
  1020  		if block.NumberU64() < currentBlock.NumberU64() {
  1021  			reorg = true
  1022  		} else if block.NumberU64() == currentBlock.NumberU64() {
  1023  			var currentPreserve, blockPreserve bool
  1024  			if bc.shouldPreserve != nil {
  1025  				currentPreserve, blockPreserve = bc.shouldPreserve(currentBlock), bc.shouldPreserve(block)
  1026  			}
  1027  			reorg = !currentPreserve && (blockPreserve || mrand.Float64() < 0.5)
  1028  		}
  1029  	}
  1030  	if reorg {
  1031  		// Reorganise the chain if the parent is not the head block
  1032  		if block.ParentHash() != currentBlock.Hash() {
  1033  			if err := bc.reorg(currentBlock, block); err != nil {
  1034  				return NonStatTy, err
  1035  			}
  1036  		}
  1037  		// Write the positional metadata for transaction/receipt lookups and preimages
  1038  		rawdb.WriteTxLookupEntries(batch, block)
  1039  		rawdb.WritePreimages(batch, state.Preimages())
  1040  
  1041  		status = CanonStatTy
  1042  	} else {
  1043  		status = SideStatTy
  1044  	}
  1045  	if err := batch.Write(); err != nil {
  1046  		return NonStatTy, err
  1047  	}
  1048  
  1049  	// Set new head.
  1050  	if status == CanonStatTy {
  1051  		bc.insert(block)
  1052  	}
  1053  	bc.futureBlocks.Remove(block.Hash())
  1054  	return status, nil
  1055  }
  1056  
  1057  // addFutureBlock checks if the block is within the max allowed window to get
  1058  // accepted for future processing, and returns an error if the block is too far
  1059  // ahead and was not added.
  1060  func (bc *BlockChain) addFutureBlock(block *types.Block) error {
  1061  	max := uint64(time.Now().Unix() + maxTimeFutureBlocks)
  1062  	if block.Time() > max {
  1063  		return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max)
  1064  	}
  1065  	bc.futureBlocks.Add(block.Hash(), block)
  1066  	return nil
  1067  }
  1068  
  1069  // InsertChain attempts to insert the given batch of blocks in to the canonical
  1070  // chain or, otherwise, create a fork. If an error is returned it will return
  1071  // the index number of the failing block as well an error describing what went
  1072  // wrong.
  1073  //
  1074  // After insertion is done, all accumulated events will be fired.
  1075  func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
  1076  	// Sanity check that we have something meaningful to import
  1077  	if len(chain) == 0 {
  1078  		return 0, nil
  1079  	}
  1080  	// Do a sanity check that the provided chain is actually ordered and linked
  1081  	for i := 1; i < len(chain); i++ {
  1082  		if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() {
  1083  			// Chain broke ancestry, log a message (programming error) and skip insertion
  1084  			log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(),
  1085  				"parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash())
  1086  
  1087  			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(),
  1088  				chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4])
  1089  		}
  1090  	}
  1091  	// Pre-checks passed, start the full block imports
  1092  	bc.wg.Add(1)
  1093  	bc.chainmu.Lock()
  1094  	n, events, logs, err := bc.insertChain(chain, true)
  1095  	bc.chainmu.Unlock()
  1096  	bc.wg.Done()
  1097  
  1098  	bc.PostChainEvents(events, logs)
  1099  	return n, err
  1100  }
  1101  
  1102  // insertChain is the internal implementation of insertChain, which assumes that
  1103  // 1) chains are contiguous, and 2) The chain mutex is held.
  1104  //
  1105  // This method is split out so that import batches that require re-injecting
  1106  // historical blocks can do so without releasing the lock, which could lead to
  1107  // racey behaviour. If a sidechain import is in progress, and the historic state
  1108  // is imported, but then new canon-head is added before the actual sidechain
  1109  // completes, then the historic state could be pruned again
  1110  func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []interface{}, []*types.Log, error) {
  1111  	// If the chain is terminating, don't even bother starting u
  1112  	if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1113  		return 0, nil, nil, nil
  1114  	}
  1115  	// Start a parallel signature recovery (signer will fluke on fork transition, minimal perf loss)
  1116  	senderCacher.recoverFromBlocks(types.MakeSigner(bc.chainConfig, chain[0].Number()), chain)
  1117  
  1118  	// A queued approach to delivering events. This is generally
  1119  	// faster than direct delivery and requires much less mutex
  1120  	// acquiring.
  1121  	var (
  1122  		stats         = insertStats{startTime: mclock.Now()}
  1123  		events        = make([]interface{}, 0, len(chain))
  1124  		lastCanon     *types.Block
  1125  		coalescedLogs []*types.Log
  1126  	)
  1127  	// Start the parallel header verifier
  1128  	headers := make([]*types.Header, len(chain))
  1129  	seals := make([]bool, len(chain))
  1130  
  1131  	for i, block := range chain {
  1132  		headers[i] = block.Header()
  1133  		seals[i] = verifySeals
  1134  	}
  1135  	abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
  1136  	defer close(abort)
  1137  
  1138  	// Peek the error for the first block to decide the directing import logic
  1139  	it := newInsertIterator(chain, results, bc.Validator())
  1140  
  1141  	block, err := it.next()
  1142  	switch {
  1143  	// First block is pruned, insert as sidechain and reorg only if TD grows enough
  1144  	case err == consensus.ErrPrunedAncestor:
  1145  		return bc.insertSidechain(block, it)
  1146  
  1147  	// First block is future, shove it (and all children) to the future queue (unknown ancestor)
  1148  	case err == consensus.ErrFutureBlock || (err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(it.first().ParentHash())):
  1149  		for block != nil && (it.index == 0 || err == consensus.ErrUnknownAncestor) {
  1150  			if err := bc.addFutureBlock(block); err != nil {
  1151  				return it.index, events, coalescedLogs, err
  1152  			}
  1153  			block, err = it.next()
  1154  		}
  1155  		stats.queued += it.processed()
  1156  		stats.ignored += it.remaining()
  1157  
  1158  		// If there are any still remaining, mark as ignored
  1159  		return it.index, events, coalescedLogs, err
  1160  
  1161  	// First block (and state) is known
  1162  	//   1. We did a roll-back, and should now do a re-import
  1163  	//   2. The block is stored as a sidechain, and is lying about it's stateroot, and passes a stateroot
  1164  	// 	    from the canonical chain, which has not been verified.
  1165  	case err == ErrKnownBlock:
  1166  		// Skip all known blocks that behind us
  1167  		current := bc.CurrentBlock().NumberU64()
  1168  
  1169  		for block != nil && err == ErrKnownBlock && current >= block.NumberU64() {
  1170  			stats.ignored++
  1171  			block, err = it.next()
  1172  		}
  1173  		// Falls through to the block import
  1174  
  1175  	// Some other error occurred, abort
  1176  	case err != nil:
  1177  		stats.ignored += len(it.chain)
  1178  		bc.reportBlock(block, nil, err)
  1179  		return it.index, events, coalescedLogs, err
  1180  	}
  1181  	// No validation errors for the first block (or chain prefix skipped)
  1182  	for ; block != nil && err == nil; block, err = it.next() {
  1183  		// If the chain is terminating, stop processing blocks
  1184  		if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1185  			log.Debug("Premature abort during blocks processing")
  1186  			break
  1187  		}
  1188  		// If the header is a banned one, straight out abort
  1189  		if BadHashes[block.Hash()] {
  1190  			bc.reportBlock(block, nil, ErrBlacklistedHash)
  1191  			return it.index, events, coalescedLogs, ErrBlacklistedHash
  1192  		}
  1193  		// Retrieve the parent block and it's state to execute on top
  1194  		start := time.Now()
  1195  
  1196  		parent := it.previous()
  1197  		if parent == nil {
  1198  			parent = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
  1199  		}
  1200  		state, err := state.New(parent.Root(), bc.stateCache)
  1201  		if err != nil {
  1202  			return it.index, events, coalescedLogs, err
  1203  		}
  1204  		// Process block using the parent state as reference point.
  1205  		t0 := time.Now()
  1206  		receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig)
  1207  		t1 := time.Now()
  1208  		if err != nil {
  1209  			bc.reportBlock(block, receipts, err)
  1210  			return it.index, events, coalescedLogs, err
  1211  		}
  1212  		// Validate the state using the default validator
  1213  		if err := bc.Validator().ValidateState(block, parent, state, receipts, usedGas); err != nil {
  1214  			bc.reportBlock(block, receipts, err)
  1215  			return it.index, events, coalescedLogs, err
  1216  		}
  1217  		t2 := time.Now()
  1218  		proctime := time.Since(start)
  1219  
  1220  		// Write the block to the chain and get the status.
  1221  		status, err := bc.WriteBlockWithState(block, receipts, state)
  1222  		t3 := time.Now()
  1223  		if err != nil {
  1224  			return it.index, events, coalescedLogs, err
  1225  		}
  1226  		blockInsertTimer.UpdateSince(start)
  1227  		blockExecutionTimer.Update(t1.Sub(t0))
  1228  		blockValidationTimer.Update(t2.Sub(t1))
  1229  		blockWriteTimer.Update(t3.Sub(t2))
  1230  		switch status {
  1231  		case CanonStatTy:
  1232  			log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
  1233  				"uncles", len(block.Uncles()), "txs", len(block.Transactions()), "gas", block.GasUsed(),
  1234  				"elapsed", common.PrettyDuration(time.Since(start)),
  1235  				"root", block.Root())
  1236  
  1237  			coalescedLogs = append(coalescedLogs, logs...)
  1238  			events = append(events, ChainEvent{block, block.Hash(), logs})
  1239  			lastCanon = block
  1240  
  1241  			// Only count canonical blocks for GC processing time
  1242  			bc.gcproc += proctime
  1243  
  1244  		case SideStatTy:
  1245  			log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(),
  1246  				"diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1247  				"txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1248  				"root", block.Root())
  1249  			events = append(events, ChainSideEvent{block})
  1250  		}
  1251  		blockInsertTimer.UpdateSince(start)
  1252  		stats.processed++
  1253  		stats.usedGas += usedGas
  1254  
  1255  		cache, _ := bc.stateCache.TrieDB().Size()
  1256  		stats.report(chain, it.index, cache)
  1257  	}
  1258  	// Any blocks remaining here? The only ones we care about are the future ones
  1259  	if block != nil && err == consensus.ErrFutureBlock {
  1260  		if err := bc.addFutureBlock(block); err != nil {
  1261  			return it.index, events, coalescedLogs, err
  1262  		}
  1263  		block, err = it.next()
  1264  
  1265  		for ; block != nil && err == consensus.ErrUnknownAncestor; block, err = it.next() {
  1266  			if err := bc.addFutureBlock(block); err != nil {
  1267  				return it.index, events, coalescedLogs, err
  1268  			}
  1269  			stats.queued++
  1270  		}
  1271  	}
  1272  	stats.ignored += it.remaining()
  1273  
  1274  	// Append a single chain head event if we've progressed the chain
  1275  	if lastCanon != nil && bc.CurrentBlock().Hash() == lastCanon.Hash() {
  1276  		events = append(events, ChainHeadEvent{lastCanon})
  1277  	}
  1278  	return it.index, events, coalescedLogs, err
  1279  }
  1280  
  1281  // insertSidechain is called when an import batch hits upon a pruned ancestor
  1282  // error, which happens when a sidechain with a sufficiently old fork-block is
  1283  // found.
  1284  //
  1285  // The method writes all (header-and-body-valid) blocks to disk, then tries to
  1286  // switch over to the new chain if the TD exceeded the current chain.
  1287  func (bc *BlockChain) insertSidechain(block *types.Block, it *insertIterator) (int, []interface{}, []*types.Log, error) {
  1288  	var (
  1289  		externTd *big.Int
  1290  		current  = bc.CurrentBlock().NumberU64()
  1291  	)
  1292  	// The first sidechain block error is already verified to be ErrPrunedAncestor.
  1293  	// Since we don't import them here, we expect ErrUnknownAncestor for the remaining
  1294  	// ones. Any other errors means that the block is invalid, and should not be written
  1295  	// to disk.
  1296  	err := consensus.ErrPrunedAncestor
  1297  	for ; block != nil && (err == consensus.ErrPrunedAncestor); block, err = it.next() {
  1298  		// Check the canonical state root for that number
  1299  		if number := block.NumberU64(); current >= number {
  1300  			if canonical := bc.GetBlockByNumber(number); canonical != nil && canonical.Root() == block.Root() {
  1301  				// This is most likely a shadow-state attack. When a fork is imported into the
  1302  				// database, and it eventually reaches a block height which is not pruned, we
  1303  				// just found that the state already exist! This means that the sidechain block
  1304  				// refers to a state which already exists in our canon chain.
  1305  				//
  1306  				// If left unchecked, we would now proceed importing the blocks, without actually
  1307  				// having verified the state of the previous blocks.
  1308  				log.Warn("Sidechain ghost-state attack detected", "number", block.NumberU64(), "sideroot", block.Root(), "canonroot", canonical.Root())
  1309  
  1310  				// If someone legitimately side-mines blocks, they would still be imported as usual. However,
  1311  				// we cannot risk writing unverified blocks to disk when they obviously target the pruning
  1312  				// mechanism.
  1313  				return it.index, nil, nil, errors.New("sidechain ghost-state attack")
  1314  			}
  1315  		}
  1316  		if externTd == nil {
  1317  			externTd = bc.GetTd(block.ParentHash(), block.NumberU64()-1)
  1318  		}
  1319  		externTd = new(big.Int).Add(externTd, block.Difficulty())
  1320  
  1321  		if !bc.HasBlock(block.Hash(), block.NumberU64()) {
  1322  			start := time.Now()
  1323  			if err := bc.WriteBlockWithoutState(block, externTd); err != nil {
  1324  				return it.index, nil, nil, err
  1325  			}
  1326  			log.Debug("Injected sidechain block", "number", block.Number(), "hash", block.Hash(),
  1327  				"diff", block.Difficulty(), "elapsed", common.PrettyDuration(time.Since(start)),
  1328  				"txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()),
  1329  				"root", block.Root())
  1330  		}
  1331  	}
  1332  	// At this point, we've written all sidechain blocks to database. Loop ended
  1333  	// either on some other error or all were processed. If there was some other
  1334  	// error, we can ignore the rest of those blocks.
  1335  	//
  1336  	// If the externTd was larger than our local TD, we now need to reimport the previous
  1337  	// blocks to regenerate the required state
  1338  	localTd := bc.GetTd(bc.CurrentBlock().Hash(), current)
  1339  	if localTd.Cmp(externTd) > 0 {
  1340  		log.Info("Sidechain written to disk", "start", it.first().NumberU64(), "end", it.previous().NumberU64(), "sidetd", externTd, "localtd", localTd)
  1341  		return it.index, nil, nil, err
  1342  	}
  1343  	// Gather all the sidechain hashes (full blocks may be memory heavy)
  1344  	var (
  1345  		hashes  []common.Hash
  1346  		numbers []uint64
  1347  	)
  1348  	parent := bc.GetHeader(it.previous().Hash(), it.previous().NumberU64())
  1349  	for parent != nil && !bc.HasState(parent.Root) {
  1350  		hashes = append(hashes, parent.Hash())
  1351  		numbers = append(numbers, parent.Number.Uint64())
  1352  
  1353  		parent = bc.GetHeader(parent.ParentHash, parent.Number.Uint64()-1)
  1354  	}
  1355  	if parent == nil {
  1356  		return it.index, nil, nil, errors.New("missing parent")
  1357  	}
  1358  	// Import all the pruned blocks to make the state available
  1359  	var (
  1360  		blocks []*types.Block
  1361  		memory common.StorageSize
  1362  	)
  1363  	for i := len(hashes) - 1; i >= 0; i-- {
  1364  		// Append the next block to our batch
  1365  		block := bc.GetBlock(hashes[i], numbers[i])
  1366  
  1367  		blocks = append(blocks, block)
  1368  		memory += block.Size()
  1369  
  1370  		// If memory use grew too large, import and continue. Sadly we need to discard
  1371  		// all raised events and logs from notifications since we're too heavy on the
  1372  		// memory here.
  1373  		if len(blocks) >= 2048 || memory > 64*1024*1024 {
  1374  			log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64())
  1375  			if _, _, _, err := bc.insertChain(blocks, false); err != nil {
  1376  				return 0, nil, nil, err
  1377  			}
  1378  			blocks, memory = blocks[:0], 0
  1379  
  1380  			// If the chain is terminating, stop processing blocks
  1381  			if atomic.LoadInt32(&bc.procInterrupt) == 1 {
  1382  				log.Debug("Premature abort during blocks processing")
  1383  				return 0, nil, nil, nil
  1384  			}
  1385  		}
  1386  	}
  1387  	if len(blocks) > 0 {
  1388  		log.Info("Importing sidechain segment", "start", blocks[0].NumberU64(), "end", blocks[len(blocks)-1].NumberU64())
  1389  		return bc.insertChain(blocks, false)
  1390  	}
  1391  	return 0, nil, nil, nil
  1392  }
  1393  
  1394  // reorg takes two blocks, an old chain and a new chain and will reconstruct the
  1395  // blocks and inserts them to be part of the new canonical chain and accumulates
  1396  // potential missing transactions and post an event about them.
  1397  func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  1398  	var (
  1399  		newChain    types.Blocks
  1400  		oldChain    types.Blocks
  1401  		commonBlock *types.Block
  1402  
  1403  		deletedTxs types.Transactions
  1404  		addedTxs   types.Transactions
  1405  
  1406  		deletedLogs []*types.Log
  1407  		rebirthLogs []*types.Log
  1408  
  1409  		// collectLogs collects the logs that were generated during the
  1410  		// processing of the block that corresponds with the given hash.
  1411  		// These logs are later announced as deleted or reborn
  1412  		collectLogs = func(hash common.Hash, removed bool) {
  1413  			number := bc.hc.GetBlockNumber(hash)
  1414  			if number == nil {
  1415  				return
  1416  			}
  1417  			receipts := rawdb.ReadReceipts(bc.db, hash, *number)
  1418  			for _, receipt := range receipts {
  1419  				for _, log := range receipt.Logs {
  1420  					l := *log
  1421  					if removed {
  1422  						l.Removed = true
  1423  						deletedLogs = append(deletedLogs, &l)
  1424  					} else {
  1425  						rebirthLogs = append(rebirthLogs, &l)
  1426  					}
  1427  				}
  1428  			}
  1429  		}
  1430  	)
  1431  	// Reduce the longer chain to the same number as the shorter one
  1432  	if oldBlock.NumberU64() > newBlock.NumberU64() {
  1433  		// Old chain is longer, gather all transactions and logs as deleted ones
  1434  		for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  1435  			oldChain = append(oldChain, oldBlock)
  1436  			deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1437  			collectLogs(oldBlock.Hash(), true)
  1438  		}
  1439  	} else {
  1440  		// New chain is longer, stash all blocks away for subsequent insertion
  1441  		for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  1442  			newChain = append(newChain, newBlock)
  1443  		}
  1444  	}
  1445  	if oldBlock == nil {
  1446  		return fmt.Errorf("invalid old chain")
  1447  	}
  1448  	if newBlock == nil {
  1449  		return fmt.Errorf("invalid new chain")
  1450  	}
  1451  	// Both sides of the reorg are at the same number, reduce both until the common
  1452  	// ancestor is found
  1453  	for {
  1454  		// If the common ancestor was found, bail out
  1455  		if oldBlock.Hash() == newBlock.Hash() {
  1456  			commonBlock = oldBlock
  1457  			break
  1458  		}
  1459  		// Remove an old block as well as stash away a new block
  1460  		oldChain = append(oldChain, oldBlock)
  1461  		deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1462  		collectLogs(oldBlock.Hash(), true)
  1463  
  1464  		newChain = append(newChain, newBlock)
  1465  
  1466  		// Step back with both chains
  1467  		oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1)
  1468  		if oldBlock == nil {
  1469  			return fmt.Errorf("invalid old chain")
  1470  		}
  1471  		newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1472  		if newBlock == nil {
  1473  			return fmt.Errorf("invalid new chain")
  1474  		}
  1475  	}
  1476  	// Ensure the user sees large reorgs
  1477  	if len(oldChain) > 0 && len(newChain) > 0 {
  1478  		logFn := log.Debug
  1479  		if len(oldChain) > 63 {
  1480  			logFn = log.Warn
  1481  		}
  1482  		logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1483  			"drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1484  	} else {
  1485  		log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1486  	}
  1487  	// Insert the new chain, taking care of the proper incremental order
  1488  	for i := len(newChain) - 1; i >= 0; i-- {
  1489  		// Insert the block in the canonical way, re-writing history
  1490  		bc.insert(newChain[i])
  1491  
  1492  		// Collect reborn logs due to chain reorg (except head block (reverse order))
  1493  		if i != 0 {
  1494  			collectLogs(newChain[i].Hash(), false)
  1495  		}
  1496  		// Write lookup entries for hash based transaction/receipt searches
  1497  		rawdb.WriteTxLookupEntries(bc.db, newChain[i])
  1498  		addedTxs = append(addedTxs, newChain[i].Transactions()...)
  1499  	}
  1500  	// When transactions get deleted from the database, the receipts that were
  1501  	// created in the fork must also be deleted
  1502  	batch := bc.db.NewBatch()
  1503  	for _, tx := range types.TxDifference(deletedTxs, addedTxs) {
  1504  		rawdb.DeleteTxLookupEntry(batch, tx.Hash())
  1505  	}
  1506  	batch.Write()
  1507  
  1508  	// If any logs need to be fired, do it now. In theory we could avoid creating
  1509  	// this goroutine if there are no events to fire, but realistcally that only
  1510  	// ever happens if we're reorging empty blocks, which will only happen on idle
  1511  	// networks where performance is not an issue either way.
  1512  	//
  1513  	// TODO(karalabe): Can we get rid of the goroutine somehow to guarantee correct
  1514  	// event ordering?
  1515  	go func() {
  1516  		if len(deletedLogs) > 0 {
  1517  			bc.rmLogsFeed.Send(RemovedLogsEvent{deletedLogs})
  1518  		}
  1519  		if len(rebirthLogs) > 0 {
  1520  			bc.logsFeed.Send(rebirthLogs)
  1521  		}
  1522  		if len(oldChain) > 0 {
  1523  			for _, block := range oldChain {
  1524  				bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1525  			}
  1526  		}
  1527  	}()
  1528  	return nil
  1529  }
  1530  
  1531  // PostChainEvents iterates over the events generated by a chain insertion and
  1532  // posts them into the event feed.
  1533  // TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock.
  1534  func (bc *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log) {
  1535  	// post event logs for further processing
  1536  	if logs != nil {
  1537  		bc.logsFeed.Send(logs)
  1538  	}
  1539  	for _, event := range events {
  1540  		switch ev := event.(type) {
  1541  		case ChainEvent:
  1542  			bc.chainFeed.Send(ev)
  1543  
  1544  		case ChainHeadEvent:
  1545  			bc.chainHeadFeed.Send(ev)
  1546  
  1547  		case ChainSideEvent:
  1548  			bc.chainSideFeed.Send(ev)
  1549  		}
  1550  	}
  1551  }
  1552  
  1553  func (bc *BlockChain) update() {
  1554  	futureTimer := time.NewTicker(5 * time.Second)
  1555  	defer futureTimer.Stop()
  1556  	for {
  1557  		select {
  1558  		case <-futureTimer.C:
  1559  			bc.procFutureBlocks()
  1560  		case <-bc.quit:
  1561  			return
  1562  		}
  1563  	}
  1564  }
  1565  
  1566  // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1567  func (bc *BlockChain) BadBlocks() []*types.Block {
  1568  	blocks := make([]*types.Block, 0, bc.badBlocks.Len())
  1569  	for _, hash := range bc.badBlocks.Keys() {
  1570  		if blk, exist := bc.badBlocks.Peek(hash); exist {
  1571  			block := blk.(*types.Block)
  1572  			blocks = append(blocks, block)
  1573  		}
  1574  	}
  1575  	return blocks
  1576  }
  1577  
  1578  // addBadBlock adds a bad block to the bad-block LRU cache
  1579  func (bc *BlockChain) addBadBlock(block *types.Block) {
  1580  	bc.badBlocks.Add(block.Hash(), block)
  1581  }
  1582  
  1583  // reportBlock logs a bad block error.
  1584  func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1585  	bc.addBadBlock(block)
  1586  
  1587  	var receiptString string
  1588  	for i, receipt := range receipts {
  1589  		receiptString += fmt.Sprintf("\t %d: cumulative: %v gas: %v contract: %v status: %v tx: %v logs: %v bloom: %x state: %x\n",
  1590  			i, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.ContractAddress.Hex(),
  1591  			receipt.Status, receipt.TxHash.Hex(), receipt.Logs, receipt.Bloom, receipt.PostState)
  1592  	}
  1593  	log.Error(fmt.Sprintf(`
  1594  ########## BAD BLOCK #########
  1595  Chain config: %v
  1596  
  1597  Number: %v
  1598  Hash: 0x%x
  1599  %v
  1600  
  1601  Error: %v
  1602  ##############################
  1603  `, bc.chainConfig, block.Number(), block.Hash(), receiptString, err))
  1604  }
  1605  
  1606  // InsertHeaderChain attempts to insert the given header chain in to the local
  1607  // chain, possibly creating a reorg. If an error is returned, it will return the
  1608  // index number of the failing header as well an error describing what went wrong.
  1609  //
  1610  // The verify parameter can be used to fine tune whether nonce verification
  1611  // should be done or not. The reason behind the optional check is because some
  1612  // of the header retrieval mechanisms already need to verify nonces, as well as
  1613  // because nonces can be verified sparsely, not needing to check each.
  1614  func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1615  	start := time.Now()
  1616  	if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1617  		return i, err
  1618  	}
  1619  
  1620  	// Make sure only one thread manipulates the chain at once
  1621  	bc.chainmu.Lock()
  1622  	defer bc.chainmu.Unlock()
  1623  
  1624  	bc.wg.Add(1)
  1625  	defer bc.wg.Done()
  1626  
  1627  	whFunc := func(header *types.Header) error {
  1628  		bc.mu.Lock()
  1629  		defer bc.mu.Unlock()
  1630  
  1631  		_, err := bc.hc.WriteHeader(header)
  1632  		return err
  1633  	}
  1634  
  1635  	return bc.hc.InsertHeaderChain(chain, whFunc, start)
  1636  }
  1637  
  1638  // writeHeader writes a header into the local chain, given that its parent is
  1639  // already known. If the total difficulty of the newly inserted header becomes
  1640  // greater than the current known TD, the canonical chain is re-routed.
  1641  //
  1642  // Note: This method is not concurrent-safe with inserting blocks simultaneously
  1643  // into the chain, as side effects caused by reorganisations cannot be emulated
  1644  // without the real blocks. Hence, writing headers directly should only be done
  1645  // in two scenarios: pure-header mode of operation (light clients), or properly
  1646  // separated header/block phases (non-archive clients).
  1647  func (bc *BlockChain) writeHeader(header *types.Header) error {
  1648  	bc.wg.Add(1)
  1649  	defer bc.wg.Done()
  1650  
  1651  	bc.mu.Lock()
  1652  	defer bc.mu.Unlock()
  1653  
  1654  	_, err := bc.hc.WriteHeader(header)
  1655  	return err
  1656  }
  1657  
  1658  // CurrentHeader retrieves the current head header of the canonical chain. The
  1659  // header is retrieved from the HeaderChain's internal cache.
  1660  func (bc *BlockChain) CurrentHeader() *types.Header {
  1661  	return bc.hc.CurrentHeader()
  1662  }
  1663  
  1664  // GetTd retrieves a block's total difficulty in the canonical chain from the
  1665  // database by hash and number, caching it if found.
  1666  func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1667  	return bc.hc.GetTd(hash, number)
  1668  }
  1669  
  1670  // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1671  // database by hash, caching it if found.
  1672  func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1673  	return bc.hc.GetTdByHash(hash)
  1674  }
  1675  
  1676  // GetHeader retrieves a block header from the database by hash and number,
  1677  // caching it if found.
  1678  func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1679  	return bc.hc.GetHeader(hash, number)
  1680  }
  1681  
  1682  // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1683  // found.
  1684  func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1685  	return bc.hc.GetHeaderByHash(hash)
  1686  }
  1687  
  1688  // HasHeader checks if a block header is present in the database or not, caching
  1689  // it if present.
  1690  func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  1691  	return bc.hc.HasHeader(hash, number)
  1692  }
  1693  
  1694  // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1695  // hash, fetching towards the genesis block.
  1696  func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1697  	return bc.hc.GetBlockHashesFromHash(hash, max)
  1698  }
  1699  
  1700  // GetAncestor retrieves the Nth ancestor of a given block. It assumes that either the given block or
  1701  // a close ancestor of it is canonical. maxNonCanonical points to a downwards counter limiting the
  1702  // number of blocks to be individually checked before we reach the canonical chain.
  1703  //
  1704  // Note: ancestor == 0 returns the same block, 1 returns its parent and so on.
  1705  func (bc *BlockChain) GetAncestor(hash common.Hash, number, ancestor uint64, maxNonCanonical *uint64) (common.Hash, uint64) {
  1706  	bc.chainmu.Lock()
  1707  	defer bc.chainmu.Unlock()
  1708  
  1709  	return bc.hc.GetAncestor(hash, number, ancestor, maxNonCanonical)
  1710  }
  1711  
  1712  // GetHeaderByNumber retrieves a block header from the database by number,
  1713  // caching it (associated with its hash) if found.
  1714  func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1715  	return bc.hc.GetHeaderByNumber(number)
  1716  }
  1717  
  1718  // Config retrieves the blockchain's chain configuration.
  1719  func (bc *BlockChain) Config() *params.ChainConfig { return bc.chainConfig }
  1720  
  1721  // Engine retrieves the blockchain's consensus engine.
  1722  func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  1723  
  1724  // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  1725  func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  1726  	return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  1727  }
  1728  
  1729  // SubscribeChainEvent registers a subscription of ChainEvent.
  1730  func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  1731  	return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  1732  }
  1733  
  1734  // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  1735  func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  1736  	return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  1737  }
  1738  
  1739  // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  1740  func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  1741  	return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  1742  }
  1743  
  1744  // SubscribeLogsEvent registers a subscription of []*types.Log.
  1745  func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  1746  	return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  1747  }