github.com/puppeth/go-ethereum@v0.8.6-0.20171014130046-e9295163aa25/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/ethereum/go-ethereum/common"
    31  	"github.com/ethereum/go-ethereum/common/mclock"
    32  	"github.com/ethereum/go-ethereum/consensus"
    33  	"github.com/ethereum/go-ethereum/core/state"
    34  	"github.com/ethereum/go-ethereum/core/types"
    35  	"github.com/ethereum/go-ethereum/core/vm"
    36  	"github.com/ethereum/go-ethereum/crypto"
    37  	"github.com/ethereum/go-ethereum/ethdb"
    38  	"github.com/ethereum/go-ethereum/event"
    39  	"github.com/ethereum/go-ethereum/log"
    40  	"github.com/ethereum/go-ethereum/metrics"
    41  	"github.com/ethereum/go-ethereum/params"
    42  	"github.com/ethereum/go-ethereum/rlp"
    43  	"github.com/ethereum/go-ethereum/trie"
    44  	"github.com/hashicorp/golang-lru"
    45  )
    46  
    47  var (
    48  	blockInsertTimer = metrics.NewTimer("chain/inserts")
    49  
    50  	ErrNoGenesis = errors.New("Genesis not found in chain")
    51  )
    52  
    53  const (
    54  	bodyCacheLimit      = 256
    55  	blockCacheLimit     = 256
    56  	maxFutureBlocks     = 256
    57  	maxTimeFutureBlocks = 30
    58  	badBlockLimit       = 10
    59  
    60  	// BlockChainVersion ensures that an incompatible database forces a resync from scratch.
    61  	BlockChainVersion = 3
    62  )
    63  
    64  // BlockChain represents the canonical chain given a database with a genesis
    65  // block. The Blockchain manages chain imports, reverts, chain reorganisations.
    66  //
    67  // Importing blocks in to the block chain happens according to the set of rules
    68  // defined by the two stage Validator. Processing of blocks is done using the
    69  // Processor which processes the included transaction. The validation of the state
    70  // is done in the second part of the Validator. Failing results in aborting of
    71  // the import.
    72  //
    73  // The BlockChain also helps in returning blocks from **any** chain included
    74  // in the database as well as blocks that represents the canonical chain. It's
    75  // important to note that GetBlock can return any block and does not need to be
    76  // included in the canonical one where as GetBlockByNumber always represents the
    77  // canonical chain.
    78  type BlockChain struct {
    79  	config *params.ChainConfig // chain & network configuration
    80  
    81  	hc            *HeaderChain
    82  	chainDb       ethdb.Database
    83  	rmLogsFeed    event.Feed
    84  	chainFeed     event.Feed
    85  	chainSideFeed event.Feed
    86  	chainHeadFeed event.Feed
    87  	logsFeed      event.Feed
    88  	scope         event.SubscriptionScope
    89  	genesisBlock  *types.Block
    90  
    91  	mu      sync.RWMutex // global mutex for locking chain operations
    92  	chainmu sync.RWMutex // blockchain insertion lock
    93  	procmu  sync.RWMutex // block processor lock
    94  
    95  	checkpoint       int          // checkpoint counts towards the new checkpoint
    96  	currentBlock     *types.Block // Current head of the block chain
    97  	currentFastBlock *types.Block // Current head of the fast-sync chain (may be above the block chain!)
    98  
    99  	stateCache   state.Database // State database to reuse between imports (contains state cache)
   100  	bodyCache    *lru.Cache     // Cache for the most recent block bodies
   101  	bodyRLPCache *lru.Cache     // Cache for the most recent block bodies in RLP encoded format
   102  	blockCache   *lru.Cache     // Cache for the most recent entire blocks
   103  	futureBlocks *lru.Cache     // future blocks are blocks added for later processing
   104  
   105  	quit    chan struct{} // blockchain quit channel
   106  	running int32         // running must be called atomically
   107  	// procInterrupt must be atomically called
   108  	procInterrupt int32          // interrupt signaler for block processing
   109  	wg            sync.WaitGroup // chain processing wait group for shutting down
   110  
   111  	engine    consensus.Engine
   112  	processor Processor // block processor interface
   113  	validator Validator // block and state validator interface
   114  	vmConfig  vm.Config
   115  
   116  	badBlocks *lru.Cache // Bad block cache
   117  }
   118  
   119  // NewBlockChain returns a fully initialised block chain using information
   120  // available in the database. It initialises the default Ethereum Validator and
   121  // Processor.
   122  func NewBlockChain(chainDb ethdb.Database, config *params.ChainConfig, engine consensus.Engine, vmConfig vm.Config) (*BlockChain, error) {
   123  	bodyCache, _ := lru.New(bodyCacheLimit)
   124  	bodyRLPCache, _ := lru.New(bodyCacheLimit)
   125  	blockCache, _ := lru.New(blockCacheLimit)
   126  	futureBlocks, _ := lru.New(maxFutureBlocks)
   127  	badBlocks, _ := lru.New(badBlockLimit)
   128  
   129  	bc := &BlockChain{
   130  		config:       config,
   131  		chainDb:      chainDb,
   132  		stateCache:   state.NewDatabase(chainDb),
   133  		quit:         make(chan struct{}),
   134  		bodyCache:    bodyCache,
   135  		bodyRLPCache: bodyRLPCache,
   136  		blockCache:   blockCache,
   137  		futureBlocks: futureBlocks,
   138  		engine:       engine,
   139  		vmConfig:     vmConfig,
   140  		badBlocks:    badBlocks,
   141  	}
   142  	bc.SetValidator(NewBlockValidator(config, bc, engine))
   143  	bc.SetProcessor(NewStateProcessor(config, bc, engine))
   144  
   145  	var err error
   146  	bc.hc, err = NewHeaderChain(chainDb, config, engine, bc.getProcInterrupt)
   147  	if err != nil {
   148  		return nil, err
   149  	}
   150  	bc.genesisBlock = bc.GetBlockByNumber(0)
   151  	if bc.genesisBlock == nil {
   152  		return nil, ErrNoGenesis
   153  	}
   154  	if err := bc.loadLastState(); err != nil {
   155  		return nil, err
   156  	}
   157  	// Check the current state of the block hashes and make sure that we do not have any of the bad blocks in our chain
   158  	for hash := range BadHashes {
   159  		if header := bc.GetHeaderByHash(hash); header != nil {
   160  			// get the canonical block corresponding to the offending header's number
   161  			headerByNumber := bc.GetHeaderByNumber(header.Number.Uint64())
   162  			// make sure the headerByNumber (if present) is in our current canonical chain
   163  			if headerByNumber != nil && headerByNumber.Hash() == header.Hash() {
   164  				log.Error("Found bad hash, rewinding chain", "number", header.Number, "hash", header.ParentHash)
   165  				bc.SetHead(header.Number.Uint64() - 1)
   166  				log.Error("Chain rewind was successful, resuming normal operation")
   167  			}
   168  		}
   169  	}
   170  	// Take ownership of this particular state
   171  	go bc.update()
   172  	return bc, nil
   173  }
   174  
   175  func (bc *BlockChain) getProcInterrupt() bool {
   176  	return atomic.LoadInt32(&bc.procInterrupt) == 1
   177  }
   178  
   179  // loadLastState loads the last known chain state from the database. This method
   180  // assumes that the chain manager mutex is held.
   181  func (bc *BlockChain) loadLastState() error {
   182  	// Restore the last known head block
   183  	head := GetHeadBlockHash(bc.chainDb)
   184  	if head == (common.Hash{}) {
   185  		// Corrupt or empty database, init from scratch
   186  		log.Warn("Empty database, resetting chain")
   187  		return bc.Reset()
   188  	}
   189  	// Make sure the entire head block is available
   190  	currentBlock := bc.GetBlockByHash(head)
   191  	if currentBlock == nil {
   192  		// Corrupt or empty database, init from scratch
   193  		log.Warn("Head block missing, resetting chain", "hash", head)
   194  		return bc.Reset()
   195  	}
   196  	// Make sure the state associated with the block is available
   197  	if _, err := state.New(currentBlock.Root(), bc.stateCache); err != nil {
   198  		// Dangling block without a state associated, init from scratch
   199  		log.Warn("Head state missing, resetting chain", "number", currentBlock.Number(), "hash", currentBlock.Hash())
   200  		return bc.Reset()
   201  	}
   202  	// Everything seems to be fine, set as the head block
   203  	bc.currentBlock = currentBlock
   204  
   205  	// Restore the last known head header
   206  	currentHeader := bc.currentBlock.Header()
   207  	if head := GetHeadHeaderHash(bc.chainDb); head != (common.Hash{}) {
   208  		if header := bc.GetHeaderByHash(head); header != nil {
   209  			currentHeader = header
   210  		}
   211  	}
   212  	bc.hc.SetCurrentHeader(currentHeader)
   213  
   214  	// Restore the last known head fast block
   215  	bc.currentFastBlock = bc.currentBlock
   216  	if head := GetHeadFastBlockHash(bc.chainDb); head != (common.Hash{}) {
   217  		if block := bc.GetBlockByHash(head); block != nil {
   218  			bc.currentFastBlock = block
   219  		}
   220  	}
   221  
   222  	// Issue a status log for the user
   223  	headerTd := bc.GetTd(currentHeader.Hash(), currentHeader.Number.Uint64())
   224  	blockTd := bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64())
   225  	fastTd := bc.GetTd(bc.currentFastBlock.Hash(), bc.currentFastBlock.NumberU64())
   226  
   227  	log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd)
   228  	log.Info("Loaded most recent local full block", "number", bc.currentBlock.Number(), "hash", bc.currentBlock.Hash(), "td", blockTd)
   229  	log.Info("Loaded most recent local fast block", "number", bc.currentFastBlock.Number(), "hash", bc.currentFastBlock.Hash(), "td", fastTd)
   230  
   231  	return nil
   232  }
   233  
   234  // SetHead rewinds the local chain to a new head. In the case of headers, everything
   235  // above the new head will be deleted and the new one set. In the case of blocks
   236  // though, the head may be further rewound if block bodies are missing (non-archive
   237  // nodes after a fast sync).
   238  func (bc *BlockChain) SetHead(head uint64) error {
   239  	log.Warn("Rewinding blockchain", "target", head)
   240  
   241  	bc.mu.Lock()
   242  	defer bc.mu.Unlock()
   243  
   244  	// Rewind the header chain, deleting all block bodies until then
   245  	delFn := func(hash common.Hash, num uint64) {
   246  		DeleteBody(bc.chainDb, hash, num)
   247  	}
   248  	bc.hc.SetHead(head, delFn)
   249  	currentHeader := bc.hc.CurrentHeader()
   250  
   251  	// Clear out any stale content from the caches
   252  	bc.bodyCache.Purge()
   253  	bc.bodyRLPCache.Purge()
   254  	bc.blockCache.Purge()
   255  	bc.futureBlocks.Purge()
   256  
   257  	// Rewind the block chain, ensuring we don't end up with a stateless head block
   258  	if bc.currentBlock != nil && currentHeader.Number.Uint64() < bc.currentBlock.NumberU64() {
   259  		bc.currentBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64())
   260  	}
   261  	if bc.currentBlock != nil {
   262  		if _, err := state.New(bc.currentBlock.Root(), bc.stateCache); err != nil {
   263  			// Rewound state missing, rolled back to before pivot, reset to genesis
   264  			bc.currentBlock = nil
   265  		}
   266  	}
   267  	// Rewind the fast block in a simpleton way to the target head
   268  	if bc.currentFastBlock != nil && currentHeader.Number.Uint64() < bc.currentFastBlock.NumberU64() {
   269  		bc.currentFastBlock = bc.GetBlock(currentHeader.Hash(), currentHeader.Number.Uint64())
   270  	}
   271  	// If either blocks reached nil, reset to the genesis state
   272  	if bc.currentBlock == nil {
   273  		bc.currentBlock = bc.genesisBlock
   274  	}
   275  	if bc.currentFastBlock == nil {
   276  		bc.currentFastBlock = bc.genesisBlock
   277  	}
   278  	if err := WriteHeadBlockHash(bc.chainDb, bc.currentBlock.Hash()); err != nil {
   279  		log.Crit("Failed to reset head full block", "err", err)
   280  	}
   281  	if err := WriteHeadFastBlockHash(bc.chainDb, bc.currentFastBlock.Hash()); err != nil {
   282  		log.Crit("Failed to reset head fast block", "err", err)
   283  	}
   284  	return bc.loadLastState()
   285  }
   286  
   287  // FastSyncCommitHead sets the current head block to the one defined by the hash
   288  // irrelevant what the chain contents were prior.
   289  func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
   290  	// Make sure that both the block as well at its state trie exists
   291  	block := bc.GetBlockByHash(hash)
   292  	if block == nil {
   293  		return fmt.Errorf("non existent block [%x…]", hash[:4])
   294  	}
   295  	if _, err := trie.NewSecure(block.Root(), bc.chainDb, 0); err != nil {
   296  		return err
   297  	}
   298  	// If all checks out, manually set the head block
   299  	bc.mu.Lock()
   300  	bc.currentBlock = block
   301  	bc.mu.Unlock()
   302  
   303  	log.Info("Committed new head block", "number", block.Number(), "hash", hash)
   304  	return nil
   305  }
   306  
   307  // GasLimit returns the gas limit of the current HEAD block.
   308  func (bc *BlockChain) GasLimit() *big.Int {
   309  	bc.mu.RLock()
   310  	defer bc.mu.RUnlock()
   311  
   312  	return bc.currentBlock.GasLimit()
   313  }
   314  
   315  // LastBlockHash return the hash of the HEAD block.
   316  func (bc *BlockChain) LastBlockHash() common.Hash {
   317  	bc.mu.RLock()
   318  	defer bc.mu.RUnlock()
   319  
   320  	return bc.currentBlock.Hash()
   321  }
   322  
   323  // CurrentBlock retrieves the current head block of the canonical chain. The
   324  // block is retrieved from the blockchain's internal cache.
   325  func (bc *BlockChain) CurrentBlock() *types.Block {
   326  	bc.mu.RLock()
   327  	defer bc.mu.RUnlock()
   328  
   329  	return bc.currentBlock
   330  }
   331  
   332  // CurrentFastBlock retrieves the current fast-sync head block of the canonical
   333  // chain. The block is retrieved from the blockchain's internal cache.
   334  func (bc *BlockChain) CurrentFastBlock() *types.Block {
   335  	bc.mu.RLock()
   336  	defer bc.mu.RUnlock()
   337  
   338  	return bc.currentFastBlock
   339  }
   340  
   341  // Status returns status information about the current chain such as the HEAD Td,
   342  // the HEAD hash and the hash of the genesis block.
   343  func (bc *BlockChain) Status() (td *big.Int, currentBlock common.Hash, genesisBlock common.Hash) {
   344  	bc.mu.RLock()
   345  	defer bc.mu.RUnlock()
   346  
   347  	return bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64()), bc.currentBlock.Hash(), bc.genesisBlock.Hash()
   348  }
   349  
   350  // SetProcessor sets the processor required for making state modifications.
   351  func (bc *BlockChain) SetProcessor(processor Processor) {
   352  	bc.procmu.Lock()
   353  	defer bc.procmu.Unlock()
   354  	bc.processor = processor
   355  }
   356  
   357  // SetValidator sets the validator which is used to validate incoming blocks.
   358  func (bc *BlockChain) SetValidator(validator Validator) {
   359  	bc.procmu.Lock()
   360  	defer bc.procmu.Unlock()
   361  	bc.validator = validator
   362  }
   363  
   364  // Validator returns the current validator.
   365  func (bc *BlockChain) Validator() Validator {
   366  	bc.procmu.RLock()
   367  	defer bc.procmu.RUnlock()
   368  	return bc.validator
   369  }
   370  
   371  // Processor returns the current processor.
   372  func (bc *BlockChain) Processor() Processor {
   373  	bc.procmu.RLock()
   374  	defer bc.procmu.RUnlock()
   375  	return bc.processor
   376  }
   377  
   378  // State returns a new mutable state based on the current HEAD block.
   379  func (bc *BlockChain) State() (*state.StateDB, error) {
   380  	return bc.StateAt(bc.CurrentBlock().Root())
   381  }
   382  
   383  // StateAt returns a new mutable state based on a particular point in time.
   384  func (bc *BlockChain) StateAt(root common.Hash) (*state.StateDB, error) {
   385  	return state.New(root, bc.stateCache)
   386  }
   387  
   388  // Reset purges the entire blockchain, restoring it to its genesis state.
   389  func (bc *BlockChain) Reset() error {
   390  	return bc.ResetWithGenesisBlock(bc.genesisBlock)
   391  }
   392  
   393  // ResetWithGenesisBlock purges the entire blockchain, restoring it to the
   394  // specified genesis state.
   395  func (bc *BlockChain) ResetWithGenesisBlock(genesis *types.Block) error {
   396  	// Dump the entire block chain and purge the caches
   397  	if err := bc.SetHead(0); err != nil {
   398  		return err
   399  	}
   400  	bc.mu.Lock()
   401  	defer bc.mu.Unlock()
   402  
   403  	// Prepare the genesis block and reinitialise the chain
   404  	if err := bc.hc.WriteTd(genesis.Hash(), genesis.NumberU64(), genesis.Difficulty()); err != nil {
   405  		log.Crit("Failed to write genesis block TD", "err", err)
   406  	}
   407  	if err := WriteBlock(bc.chainDb, genesis); err != nil {
   408  		log.Crit("Failed to write genesis block", "err", err)
   409  	}
   410  	bc.genesisBlock = genesis
   411  	bc.insert(bc.genesisBlock)
   412  	bc.currentBlock = bc.genesisBlock
   413  	bc.hc.SetGenesis(bc.genesisBlock.Header())
   414  	bc.hc.SetCurrentHeader(bc.genesisBlock.Header())
   415  	bc.currentFastBlock = bc.genesisBlock
   416  
   417  	return nil
   418  }
   419  
   420  // Export writes the active chain to the given writer.
   421  func (bc *BlockChain) Export(w io.Writer) error {
   422  	return bc.ExportN(w, uint64(0), bc.currentBlock.NumberU64())
   423  }
   424  
   425  // ExportN writes a subset of the active chain to the given writer.
   426  func (bc *BlockChain) ExportN(w io.Writer, first uint64, last uint64) error {
   427  	bc.mu.RLock()
   428  	defer bc.mu.RUnlock()
   429  
   430  	if first > last {
   431  		return fmt.Errorf("export failed: first (%d) is greater than last (%d)", first, last)
   432  	}
   433  	log.Info("Exporting batch of blocks", "count", last-first+1)
   434  
   435  	for nr := first; nr <= last; nr++ {
   436  		block := bc.GetBlockByNumber(nr)
   437  		if block == nil {
   438  			return fmt.Errorf("export failed on #%d: not found", nr)
   439  		}
   440  
   441  		if err := block.EncodeRLP(w); err != nil {
   442  			return err
   443  		}
   444  	}
   445  
   446  	return nil
   447  }
   448  
   449  // insert injects a new head block into the current block chain. This method
   450  // assumes that the block is indeed a true head. It will also reset the head
   451  // header and the head fast sync block to this very same block if they are older
   452  // or if they are on a different side chain.
   453  //
   454  // Note, this function assumes that the `mu` mutex is held!
   455  func (bc *BlockChain) insert(block *types.Block) {
   456  	// If the block is on a side chain or an unknown one, force other heads onto it too
   457  	updateHeads := GetCanonicalHash(bc.chainDb, block.NumberU64()) != block.Hash()
   458  
   459  	// Add the block to the canonical chain number scheme and mark as the head
   460  	if err := WriteCanonicalHash(bc.chainDb, block.Hash(), block.NumberU64()); err != nil {
   461  		log.Crit("Failed to insert block number", "err", err)
   462  	}
   463  	if err := WriteHeadBlockHash(bc.chainDb, block.Hash()); err != nil {
   464  		log.Crit("Failed to insert head block hash", "err", err)
   465  	}
   466  	bc.currentBlock = block
   467  
   468  	// If the block is better than out head or is on a different chain, force update heads
   469  	if updateHeads {
   470  		bc.hc.SetCurrentHeader(block.Header())
   471  
   472  		if err := WriteHeadFastBlockHash(bc.chainDb, block.Hash()); err != nil {
   473  			log.Crit("Failed to insert head fast block hash", "err", err)
   474  		}
   475  		bc.currentFastBlock = block
   476  	}
   477  }
   478  
   479  // Genesis retrieves the chain's genesis block.
   480  func (bc *BlockChain) Genesis() *types.Block {
   481  	return bc.genesisBlock
   482  }
   483  
   484  // GetBody retrieves a block body (transactions and uncles) from the database by
   485  // hash, caching it if found.
   486  func (bc *BlockChain) GetBody(hash common.Hash) *types.Body {
   487  	// Short circuit if the body's already in the cache, retrieve otherwise
   488  	if cached, ok := bc.bodyCache.Get(hash); ok {
   489  		body := cached.(*types.Body)
   490  		return body
   491  	}
   492  	body := GetBody(bc.chainDb, hash, bc.hc.GetBlockNumber(hash))
   493  	if body == nil {
   494  		return nil
   495  	}
   496  	// Cache the found body for next time and return
   497  	bc.bodyCache.Add(hash, body)
   498  	return body
   499  }
   500  
   501  // GetBodyRLP retrieves a block body in RLP encoding from the database by hash,
   502  // caching it if found.
   503  func (bc *BlockChain) GetBodyRLP(hash common.Hash) rlp.RawValue {
   504  	// Short circuit if the body's already in the cache, retrieve otherwise
   505  	if cached, ok := bc.bodyRLPCache.Get(hash); ok {
   506  		return cached.(rlp.RawValue)
   507  	}
   508  	body := GetBodyRLP(bc.chainDb, hash, bc.hc.GetBlockNumber(hash))
   509  	if len(body) == 0 {
   510  		return nil
   511  	}
   512  	// Cache the found body for next time and return
   513  	bc.bodyRLPCache.Add(hash, body)
   514  	return body
   515  }
   516  
   517  // HasBlock checks if a block is fully present in the database or not.
   518  func (bc *BlockChain) HasBlock(hash common.Hash, number uint64) bool {
   519  	if bc.blockCache.Contains(hash) {
   520  		return true
   521  	}
   522  	ok, _ := bc.chainDb.Has(blockBodyKey(hash, number))
   523  	return ok
   524  }
   525  
   526  // HasBlockAndState checks if a block and associated state trie is fully present
   527  // in the database or not, caching it if present.
   528  func (bc *BlockChain) HasBlockAndState(hash common.Hash) bool {
   529  	// Check first that the block itself is known
   530  	block := bc.GetBlockByHash(hash)
   531  	if block == nil {
   532  		return false
   533  	}
   534  	// Ensure the associated state is also present
   535  	_, err := bc.stateCache.OpenTrie(block.Root())
   536  	return err == nil
   537  }
   538  
   539  // GetBlock retrieves a block from the database by hash and number,
   540  // caching it if found.
   541  func (bc *BlockChain) GetBlock(hash common.Hash, number uint64) *types.Block {
   542  	// Short circuit if the block's already in the cache, retrieve otherwise
   543  	if block, ok := bc.blockCache.Get(hash); ok {
   544  		return block.(*types.Block)
   545  	}
   546  	block := GetBlock(bc.chainDb, hash, number)
   547  	if block == nil {
   548  		return nil
   549  	}
   550  	// Cache the found block for next time and return
   551  	bc.blockCache.Add(block.Hash(), block)
   552  	return block
   553  }
   554  
   555  // GetBlockByHash retrieves a block from the database by hash, caching it if found.
   556  func (bc *BlockChain) GetBlockByHash(hash common.Hash) *types.Block {
   557  	return bc.GetBlock(hash, bc.hc.GetBlockNumber(hash))
   558  }
   559  
   560  // GetBlockByNumber retrieves a block from the database by number, caching it
   561  // (associated with its hash) if found.
   562  func (bc *BlockChain) GetBlockByNumber(number uint64) *types.Block {
   563  	hash := GetCanonicalHash(bc.chainDb, number)
   564  	if hash == (common.Hash{}) {
   565  		return nil
   566  	}
   567  	return bc.GetBlock(hash, number)
   568  }
   569  
   570  // GetBlocksFromHash returns the block corresponding to hash and up to n-1 ancestors.
   571  // [deprecated by eth/62]
   572  func (bc *BlockChain) GetBlocksFromHash(hash common.Hash, n int) (blocks []*types.Block) {
   573  	number := bc.hc.GetBlockNumber(hash)
   574  	for i := 0; i < n; i++ {
   575  		block := bc.GetBlock(hash, number)
   576  		if block == nil {
   577  			break
   578  		}
   579  		blocks = append(blocks, block)
   580  		hash = block.ParentHash()
   581  		number--
   582  	}
   583  	return
   584  }
   585  
   586  // GetUnclesInChain retrieves all the uncles from a given block backwards until
   587  // a specific distance is reached.
   588  func (bc *BlockChain) GetUnclesInChain(block *types.Block, length int) []*types.Header {
   589  	uncles := []*types.Header{}
   590  	for i := 0; block != nil && i < length; i++ {
   591  		uncles = append(uncles, block.Uncles()...)
   592  		block = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
   593  	}
   594  	return uncles
   595  }
   596  
   597  // Stop stops the blockchain service. If any imports are currently in progress
   598  // it will abort them using the procInterrupt.
   599  func (bc *BlockChain) Stop() {
   600  	if !atomic.CompareAndSwapInt32(&bc.running, 0, 1) {
   601  		return
   602  	}
   603  	// Unsubscribe all subscriptions registered from blockchain
   604  	bc.scope.Close()
   605  	close(bc.quit)
   606  	atomic.StoreInt32(&bc.procInterrupt, 1)
   607  
   608  	bc.wg.Wait()
   609  	log.Info("Blockchain manager stopped")
   610  }
   611  
   612  func (bc *BlockChain) procFutureBlocks() {
   613  	blocks := make([]*types.Block, 0, bc.futureBlocks.Len())
   614  	for _, hash := range bc.futureBlocks.Keys() {
   615  		if block, exist := bc.futureBlocks.Peek(hash); exist {
   616  			blocks = append(blocks, block.(*types.Block))
   617  		}
   618  	}
   619  	if len(blocks) > 0 {
   620  		types.BlockBy(types.Number).Sort(blocks)
   621  
   622  		// Insert one by one as chain insertion needs contiguous ancestry between blocks
   623  		for i := range blocks {
   624  			bc.InsertChain(blocks[i : i+1])
   625  		}
   626  	}
   627  }
   628  
   629  // WriteStatus status of write
   630  type WriteStatus byte
   631  
   632  const (
   633  	NonStatTy WriteStatus = iota
   634  	CanonStatTy
   635  	SideStatTy
   636  )
   637  
   638  // Rollback is designed to remove a chain of links from the database that aren't
   639  // certain enough to be valid.
   640  func (bc *BlockChain) Rollback(chain []common.Hash) {
   641  	bc.mu.Lock()
   642  	defer bc.mu.Unlock()
   643  
   644  	for i := len(chain) - 1; i >= 0; i-- {
   645  		hash := chain[i]
   646  
   647  		currentHeader := bc.hc.CurrentHeader()
   648  		if currentHeader.Hash() == hash {
   649  			bc.hc.SetCurrentHeader(bc.GetHeader(currentHeader.ParentHash, currentHeader.Number.Uint64()-1))
   650  		}
   651  		if bc.currentFastBlock.Hash() == hash {
   652  			bc.currentFastBlock = bc.GetBlock(bc.currentFastBlock.ParentHash(), bc.currentFastBlock.NumberU64()-1)
   653  			WriteHeadFastBlockHash(bc.chainDb, bc.currentFastBlock.Hash())
   654  		}
   655  		if bc.currentBlock.Hash() == hash {
   656  			bc.currentBlock = bc.GetBlock(bc.currentBlock.ParentHash(), bc.currentBlock.NumberU64()-1)
   657  			WriteHeadBlockHash(bc.chainDb, bc.currentBlock.Hash())
   658  		}
   659  	}
   660  }
   661  
   662  // SetReceiptsData computes all the non-consensus fields of the receipts
   663  func SetReceiptsData(config *params.ChainConfig, block *types.Block, receipts types.Receipts) {
   664  	signer := types.MakeSigner(config, block.Number())
   665  
   666  	transactions, logIndex := block.Transactions(), uint(0)
   667  
   668  	for j := 0; j < len(receipts); j++ {
   669  		// The transaction hash can be retrieved from the transaction itself
   670  		receipts[j].TxHash = transactions[j].Hash()
   671  
   672  		// The contract address can be derived from the transaction itself
   673  		if transactions[j].To() == nil {
   674  			// Deriving the signer is expensive, only do if it's actually needed
   675  			from, _ := types.Sender(signer, transactions[j])
   676  			receipts[j].ContractAddress = crypto.CreateAddress(from, transactions[j].Nonce())
   677  		}
   678  		// The used gas can be calculated based on previous receipts
   679  		if j == 0 {
   680  			receipts[j].GasUsed = new(big.Int).Set(receipts[j].CumulativeGasUsed)
   681  		} else {
   682  			receipts[j].GasUsed = new(big.Int).Sub(receipts[j].CumulativeGasUsed, receipts[j-1].CumulativeGasUsed)
   683  		}
   684  		// The derived log fields can simply be set from the block and transaction
   685  		for k := 0; k < len(receipts[j].Logs); k++ {
   686  			receipts[j].Logs[k].BlockNumber = block.NumberU64()
   687  			receipts[j].Logs[k].BlockHash = block.Hash()
   688  			receipts[j].Logs[k].TxHash = receipts[j].TxHash
   689  			receipts[j].Logs[k].TxIndex = uint(j)
   690  			receipts[j].Logs[k].Index = logIndex
   691  			logIndex++
   692  		}
   693  	}
   694  }
   695  
   696  // InsertReceiptChain attempts to complete an already existing header chain with
   697  // transaction and receipt data.
   698  func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain []types.Receipts) (int, error) {
   699  	bc.wg.Add(1)
   700  	defer bc.wg.Done()
   701  
   702  	// Do a sanity check that the provided chain is actually ordered and linked
   703  	for i := 1; i < len(blockChain); i++ {
   704  		if blockChain[i].NumberU64() != blockChain[i-1].NumberU64()+1 || blockChain[i].ParentHash() != blockChain[i-1].Hash() {
   705  			log.Error("Non contiguous receipt insert", "number", blockChain[i].Number(), "hash", blockChain[i].Hash(), "parent", blockChain[i].ParentHash(),
   706  				"prevnumber", blockChain[i-1].Number(), "prevhash", blockChain[i-1].Hash())
   707  			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(),
   708  				blockChain[i-1].Hash().Bytes()[:4], i, blockChain[i].NumberU64(), blockChain[i].Hash().Bytes()[:4], blockChain[i].ParentHash().Bytes()[:4])
   709  		}
   710  	}
   711  
   712  	var (
   713  		stats = struct{ processed, ignored int32 }{}
   714  		start = time.Now()
   715  		bytes = 0
   716  		batch = bc.chainDb.NewBatch()
   717  	)
   718  	for i, block := range blockChain {
   719  		receipts := receiptChain[i]
   720  		// Short circuit insertion if shutting down or processing failed
   721  		if atomic.LoadInt32(&bc.procInterrupt) == 1 {
   722  			return 0, nil
   723  		}
   724  		// Short circuit if the owner header is unknown
   725  		if !bc.HasHeader(block.Hash(), block.NumberU64()) {
   726  			return i, fmt.Errorf("containing header #%d [%x…] unknown", block.Number(), block.Hash().Bytes()[:4])
   727  		}
   728  		// Skip if the entire data is already known
   729  		if bc.HasBlock(block.Hash(), block.NumberU64()) {
   730  			stats.ignored++
   731  			continue
   732  		}
   733  		// Compute all the non-consensus fields of the receipts
   734  		SetReceiptsData(bc.config, block, receipts)
   735  		// Write all the data out into the database
   736  		if err := WriteBody(batch, block.Hash(), block.NumberU64(), block.Body()); err != nil {
   737  			return i, fmt.Errorf("failed to write block body: %v", err)
   738  		}
   739  		if err := WriteBlockReceipts(batch, block.Hash(), block.NumberU64(), receipts); err != nil {
   740  			return i, fmt.Errorf("failed to write block receipts: %v", err)
   741  		}
   742  		if err := WriteTxLookupEntries(batch, block); err != nil {
   743  			return i, fmt.Errorf("failed to write lookup metadata: %v", err)
   744  		}
   745  		stats.processed++
   746  
   747  		if batch.ValueSize() >= ethdb.IdealBatchSize {
   748  			if err := batch.Write(); err != nil {
   749  				return 0, err
   750  			}
   751  			bytes += batch.ValueSize()
   752  			batch = bc.chainDb.NewBatch()
   753  		}
   754  	}
   755  	if batch.ValueSize() > 0 {
   756  		bytes += batch.ValueSize()
   757  		if err := batch.Write(); err != nil {
   758  			return 0, err
   759  		}
   760  	}
   761  
   762  	// Update the head fast sync block if better
   763  	bc.mu.Lock()
   764  	head := blockChain[len(blockChain)-1]
   765  	if td := bc.GetTd(head.Hash(), head.NumberU64()); td != nil { // Rewind may have occurred, skip in that case
   766  		if bc.GetTd(bc.currentFastBlock.Hash(), bc.currentFastBlock.NumberU64()).Cmp(td) < 0 {
   767  			if err := WriteHeadFastBlockHash(bc.chainDb, head.Hash()); err != nil {
   768  				log.Crit("Failed to update head fast block hash", "err", err)
   769  			}
   770  			bc.currentFastBlock = head
   771  		}
   772  	}
   773  	bc.mu.Unlock()
   774  
   775  	log.Info("Imported new block receipts",
   776  		"count", stats.processed,
   777  		"elapsed", common.PrettyDuration(time.Since(start)),
   778  		"bytes", bytes,
   779  		"number", head.Number(),
   780  		"hash", head.Hash(),
   781  		"ignored", stats.ignored)
   782  	return 0, nil
   783  }
   784  
   785  // WriteBlock writes the block to the chain.
   786  func (bc *BlockChain) WriteBlockAndState(block *types.Block, receipts []*types.Receipt, state *state.StateDB) (status WriteStatus, err error) {
   787  	bc.wg.Add(1)
   788  	defer bc.wg.Done()
   789  
   790  	// Calculate the total difficulty of the block
   791  	ptd := bc.GetTd(block.ParentHash(), block.NumberU64()-1)
   792  	if ptd == nil {
   793  		return NonStatTy, consensus.ErrUnknownAncestor
   794  	}
   795  	// Make sure no inconsistent state is leaked during insertion
   796  	bc.mu.Lock()
   797  	defer bc.mu.Unlock()
   798  
   799  	localTd := bc.GetTd(bc.currentBlock.Hash(), bc.currentBlock.NumberU64())
   800  	externTd := new(big.Int).Add(block.Difficulty(), ptd)
   801  
   802  	// Irrelevant of the canonical status, write the block itself to the database
   803  	if err := bc.hc.WriteTd(block.Hash(), block.NumberU64(), externTd); err != nil {
   804  		return NonStatTy, err
   805  	}
   806  	// Write other block data using a batch.
   807  	batch := bc.chainDb.NewBatch()
   808  	if err := WriteBlock(batch, block); err != nil {
   809  		return NonStatTy, err
   810  	}
   811  	if _, err := state.CommitTo(batch, bc.config.IsEIP158(block.Number())); err != nil {
   812  		return NonStatTy, err
   813  	}
   814  	if err := WriteBlockReceipts(batch, block.Hash(), block.NumberU64(), receipts); err != nil {
   815  		return NonStatTy, err
   816  	}
   817  
   818  	// If the total difficulty is higher than our known, add it to the canonical chain
   819  	// Second clause in the if statement reduces the vulnerability to selfish mining.
   820  	// Please refer to http://www.cs.cornell.edu/~ie53/publications/btcProcFC.pdf
   821  	if externTd.Cmp(localTd) > 0 || (externTd.Cmp(localTd) == 0 && mrand.Float64() < 0.5) {
   822  		// Reorganise the chain if the parent is not the head block
   823  		if block.ParentHash() != bc.currentBlock.Hash() {
   824  			if err := bc.reorg(bc.currentBlock, block); err != nil {
   825  				return NonStatTy, err
   826  			}
   827  		}
   828  		// Write the positional metadata for transaction and receipt lookups
   829  		if err := WriteTxLookupEntries(batch, block); err != nil {
   830  			return NonStatTy, err
   831  		}
   832  		// Write hash preimages
   833  		if err := WritePreimages(bc.chainDb, block.NumberU64(), state.Preimages()); err != nil {
   834  			return NonStatTy, err
   835  		}
   836  		status = CanonStatTy
   837  	} else {
   838  		status = SideStatTy
   839  	}
   840  	if err := batch.Write(); err != nil {
   841  		return NonStatTy, err
   842  	}
   843  
   844  	// Set new head.
   845  	if status == CanonStatTy {
   846  		bc.insert(block)
   847  	}
   848  	bc.futureBlocks.Remove(block.Hash())
   849  	return status, nil
   850  }
   851  
   852  // InsertChain attempts to insert the given batch of blocks in to the canonical
   853  // chain or, otherwise, create a fork. If an error is returned it will return
   854  // the index number of the failing block as well an error describing what went
   855  // wrong.
   856  //
   857  // After insertion is done, all accumulated events will be fired.
   858  func (bc *BlockChain) InsertChain(chain types.Blocks) (int, error) {
   859  	n, events, logs, err := bc.insertChain(chain)
   860  	bc.PostChainEvents(events, logs)
   861  	return n, err
   862  }
   863  
   864  // insertChain will execute the actual chain insertion and event aggregation. The
   865  // only reason this method exists as a separate one is to make locking cleaner
   866  // with deferred statements.
   867  func (bc *BlockChain) insertChain(chain types.Blocks) (int, []interface{}, []*types.Log, error) {
   868  	// Do a sanity check that the provided chain is actually ordered and linked
   869  	for i := 1; i < len(chain); i++ {
   870  		if chain[i].NumberU64() != chain[i-1].NumberU64()+1 || chain[i].ParentHash() != chain[i-1].Hash() {
   871  			// Chain broke ancestry, log a messge (programming error) and skip insertion
   872  			log.Error("Non contiguous block insert", "number", chain[i].Number(), "hash", chain[i].Hash(),
   873  				"parent", chain[i].ParentHash(), "prevnumber", chain[i-1].Number(), "prevhash", chain[i-1].Hash())
   874  
   875  			return 0, nil, nil, fmt.Errorf("non contiguous insert: item %d is #%d [%x…], item %d is #%d [%x…] (parent [%x…])", i-1, chain[i-1].NumberU64(),
   876  				chain[i-1].Hash().Bytes()[:4], i, chain[i].NumberU64(), chain[i].Hash().Bytes()[:4], chain[i].ParentHash().Bytes()[:4])
   877  		}
   878  	}
   879  	// Pre-checks passed, start the full block imports
   880  	bc.wg.Add(1)
   881  	defer bc.wg.Done()
   882  
   883  	bc.chainmu.Lock()
   884  	defer bc.chainmu.Unlock()
   885  
   886  	// A queued approach to delivering events. This is generally
   887  	// faster than direct delivery and requires much less mutex
   888  	// acquiring.
   889  	var (
   890  		stats         = insertStats{startTime: mclock.Now()}
   891  		events        = make([]interface{}, 0, len(chain))
   892  		lastCanon     *types.Block
   893  		coalescedLogs []*types.Log
   894  	)
   895  	// Start the parallel header verifier
   896  	headers := make([]*types.Header, len(chain))
   897  	seals := make([]bool, len(chain))
   898  
   899  	for i, block := range chain {
   900  		headers[i] = block.Header()
   901  		seals[i] = true
   902  	}
   903  	abort, results := bc.engine.VerifyHeaders(bc, headers, seals)
   904  	defer close(abort)
   905  
   906  	// Iterate over the blocks and insert when the verifier permits
   907  	for i, block := range chain {
   908  		// If the chain is terminating, stop processing blocks
   909  		if atomic.LoadInt32(&bc.procInterrupt) == 1 {
   910  			log.Debug("Premature abort during blocks processing")
   911  			break
   912  		}
   913  		// If the header is a banned one, straight out abort
   914  		if BadHashes[block.Hash()] {
   915  			bc.reportBlock(block, nil, ErrBlacklistedHash)
   916  			return i, events, coalescedLogs, ErrBlacklistedHash
   917  		}
   918  		// Wait for the block's verification to complete
   919  		bstart := time.Now()
   920  
   921  		err := <-results
   922  		if err == nil {
   923  			err = bc.Validator().ValidateBody(block)
   924  		}
   925  		if err != nil {
   926  			if err == ErrKnownBlock {
   927  				stats.ignored++
   928  				continue
   929  			}
   930  
   931  			if err == consensus.ErrFutureBlock {
   932  				// Allow up to MaxFuture second in the future blocks. If this limit
   933  				// is exceeded the chain is discarded and processed at a later time
   934  				// if given.
   935  				max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks)
   936  				if block.Time().Cmp(max) > 0 {
   937  					return i, events, coalescedLogs, fmt.Errorf("future block: %v > %v", block.Time(), max)
   938  				}
   939  				bc.futureBlocks.Add(block.Hash(), block)
   940  				stats.queued++
   941  				continue
   942  			}
   943  
   944  			if err == consensus.ErrUnknownAncestor && bc.futureBlocks.Contains(block.ParentHash()) {
   945  				bc.futureBlocks.Add(block.Hash(), block)
   946  				stats.queued++
   947  				continue
   948  			}
   949  
   950  			bc.reportBlock(block, nil, err)
   951  			return i, events, coalescedLogs, err
   952  		}
   953  		// Create a new statedb using the parent block and report an
   954  		// error if it fails.
   955  		var parent *types.Block
   956  		if i == 0 {
   957  			parent = bc.GetBlock(block.ParentHash(), block.NumberU64()-1)
   958  		} else {
   959  			parent = chain[i-1]
   960  		}
   961  		state, err := state.New(parent.Root(), bc.stateCache)
   962  		if err != nil {
   963  			return i, events, coalescedLogs, err
   964  		}
   965  		// Process block using the parent state as reference point.
   966  		receipts, logs, usedGas, err := bc.processor.Process(block, state, bc.vmConfig)
   967  		if err != nil {
   968  			bc.reportBlock(block, receipts, err)
   969  			return i, events, coalescedLogs, err
   970  		}
   971  		// Validate the state using the default validator
   972  		err = bc.Validator().ValidateState(block, parent, state, receipts, usedGas)
   973  		if err != nil {
   974  			bc.reportBlock(block, receipts, err)
   975  			return i, events, coalescedLogs, err
   976  		}
   977  		// Write the block to the chain and get the status.
   978  		status, err := bc.WriteBlockAndState(block, receipts, state)
   979  		if err != nil {
   980  			return i, events, coalescedLogs, err
   981  		}
   982  		switch status {
   983  		case CanonStatTy:
   984  			log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(), "uncles", len(block.Uncles()),
   985  				"txs", len(block.Transactions()), "gas", block.GasUsed(), "elapsed", common.PrettyDuration(time.Since(bstart)))
   986  
   987  			coalescedLogs = append(coalescedLogs, logs...)
   988  			blockInsertTimer.UpdateSince(bstart)
   989  			events = append(events, ChainEvent{block, block.Hash(), logs})
   990  			lastCanon = block
   991  
   992  		case SideStatTy:
   993  			log.Debug("Inserted forked block", "number", block.Number(), "hash", block.Hash(), "diff", block.Difficulty(), "elapsed",
   994  				common.PrettyDuration(time.Since(bstart)), "txs", len(block.Transactions()), "gas", block.GasUsed(), "uncles", len(block.Uncles()))
   995  
   996  			blockInsertTimer.UpdateSince(bstart)
   997  			events = append(events, ChainSideEvent{block})
   998  		}
   999  		stats.processed++
  1000  		stats.usedGas += usedGas.Uint64()
  1001  		stats.report(chain, i)
  1002  	}
  1003  	// Append a single chain head event if we've progressed the chain
  1004  	if lastCanon != nil && bc.LastBlockHash() == lastCanon.Hash() {
  1005  		events = append(events, ChainHeadEvent{lastCanon})
  1006  	}
  1007  	return 0, events, coalescedLogs, nil
  1008  }
  1009  
  1010  // insertStats tracks and reports on block insertion.
  1011  type insertStats struct {
  1012  	queued, processed, ignored int
  1013  	usedGas                    uint64
  1014  	lastIndex                  int
  1015  	startTime                  mclock.AbsTime
  1016  }
  1017  
  1018  // statsReportLimit is the time limit during import after which we always print
  1019  // out progress. This avoids the user wondering what's going on.
  1020  const statsReportLimit = 8 * time.Second
  1021  
  1022  // report prints statistics if some number of blocks have been processed
  1023  // or more than a few seconds have passed since the last message.
  1024  func (st *insertStats) report(chain []*types.Block, index int) {
  1025  	// Fetch the timings for the batch
  1026  	var (
  1027  		now     = mclock.Now()
  1028  		elapsed = time.Duration(now) - time.Duration(st.startTime)
  1029  	)
  1030  	// If we're at the last block of the batch or report period reached, log
  1031  	if index == len(chain)-1 || elapsed >= statsReportLimit {
  1032  		var (
  1033  			end = chain[index]
  1034  			txs = countTransactions(chain[st.lastIndex : index+1])
  1035  		)
  1036  		context := []interface{}{
  1037  			"blocks", st.processed, "txs", txs, "mgas", float64(st.usedGas) / 1000000,
  1038  			"elapsed", common.PrettyDuration(elapsed), "mgasps", float64(st.usedGas) * 1000 / float64(elapsed),
  1039  			"number", end.Number(), "hash", end.Hash(),
  1040  		}
  1041  		if st.queued > 0 {
  1042  			context = append(context, []interface{}{"queued", st.queued}...)
  1043  		}
  1044  		if st.ignored > 0 {
  1045  			context = append(context, []interface{}{"ignored", st.ignored}...)
  1046  		}
  1047  		log.Info("Imported new chain segment", context...)
  1048  
  1049  		*st = insertStats{startTime: now, lastIndex: index + 1}
  1050  	}
  1051  }
  1052  
  1053  func countTransactions(chain []*types.Block) (c int) {
  1054  	for _, b := range chain {
  1055  		c += len(b.Transactions())
  1056  	}
  1057  	return c
  1058  }
  1059  
  1060  // reorgs takes two blocks, an old chain and a new chain and will reconstruct the blocks and inserts them
  1061  // to be part of the new canonical chain and accumulates potential missing transactions and post an
  1062  // event about them
  1063  func (bc *BlockChain) reorg(oldBlock, newBlock *types.Block) error {
  1064  	var (
  1065  		newChain    types.Blocks
  1066  		oldChain    types.Blocks
  1067  		commonBlock *types.Block
  1068  		deletedTxs  types.Transactions
  1069  		deletedLogs []*types.Log
  1070  		// collectLogs collects the logs that were generated during the
  1071  		// processing of the block that corresponds with the given hash.
  1072  		// These logs are later announced as deleted.
  1073  		collectLogs = func(h common.Hash) {
  1074  			// Coalesce logs and set 'Removed'.
  1075  			receipts := GetBlockReceipts(bc.chainDb, h, bc.hc.GetBlockNumber(h))
  1076  			for _, receipt := range receipts {
  1077  				for _, log := range receipt.Logs {
  1078  					del := *log
  1079  					del.Removed = true
  1080  					deletedLogs = append(deletedLogs, &del)
  1081  				}
  1082  			}
  1083  		}
  1084  	)
  1085  
  1086  	// first reduce whoever is higher bound
  1087  	if oldBlock.NumberU64() > newBlock.NumberU64() {
  1088  		// reduce old chain
  1089  		for ; oldBlock != nil && oldBlock.NumberU64() != newBlock.NumberU64(); oldBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1) {
  1090  			oldChain = append(oldChain, oldBlock)
  1091  			deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1092  
  1093  			collectLogs(oldBlock.Hash())
  1094  		}
  1095  	} else {
  1096  		// reduce new chain and append new chain blocks for inserting later on
  1097  		for ; newBlock != nil && newBlock.NumberU64() != oldBlock.NumberU64(); newBlock = bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1) {
  1098  			newChain = append(newChain, newBlock)
  1099  		}
  1100  	}
  1101  	if oldBlock == nil {
  1102  		return fmt.Errorf("Invalid old chain")
  1103  	}
  1104  	if newBlock == nil {
  1105  		return fmt.Errorf("Invalid new chain")
  1106  	}
  1107  
  1108  	for {
  1109  		if oldBlock.Hash() == newBlock.Hash() {
  1110  			commonBlock = oldBlock
  1111  			break
  1112  		}
  1113  
  1114  		oldChain = append(oldChain, oldBlock)
  1115  		newChain = append(newChain, newBlock)
  1116  		deletedTxs = append(deletedTxs, oldBlock.Transactions()...)
  1117  		collectLogs(oldBlock.Hash())
  1118  
  1119  		oldBlock, newBlock = bc.GetBlock(oldBlock.ParentHash(), oldBlock.NumberU64()-1), bc.GetBlock(newBlock.ParentHash(), newBlock.NumberU64()-1)
  1120  		if oldBlock == nil {
  1121  			return fmt.Errorf("Invalid old chain")
  1122  		}
  1123  		if newBlock == nil {
  1124  			return fmt.Errorf("Invalid new chain")
  1125  		}
  1126  	}
  1127  	// Ensure the user sees large reorgs
  1128  	if len(oldChain) > 0 && len(newChain) > 0 {
  1129  		logFn := log.Debug
  1130  		if len(oldChain) > 63 {
  1131  			logFn = log.Warn
  1132  		}
  1133  		logFn("Chain split detected", "number", commonBlock.Number(), "hash", commonBlock.Hash(),
  1134  			"drop", len(oldChain), "dropfrom", oldChain[0].Hash(), "add", len(newChain), "addfrom", newChain[0].Hash())
  1135  	} else {
  1136  		log.Error("Impossible reorg, please file an issue", "oldnum", oldBlock.Number(), "oldhash", oldBlock.Hash(), "newnum", newBlock.Number(), "newhash", newBlock.Hash())
  1137  	}
  1138  	var addedTxs types.Transactions
  1139  	// insert blocks. Order does not matter. Last block will be written in ImportChain itself which creates the new head properly
  1140  	for _, block := range newChain {
  1141  		// insert the block in the canonical way, re-writing history
  1142  		bc.insert(block)
  1143  		// write lookup entries for hash based transaction/receipt searches
  1144  		if err := WriteTxLookupEntries(bc.chainDb, block); err != nil {
  1145  			return err
  1146  		}
  1147  		addedTxs = append(addedTxs, block.Transactions()...)
  1148  	}
  1149  
  1150  	// calculate the difference between deleted and added transactions
  1151  	diff := types.TxDifference(deletedTxs, addedTxs)
  1152  	// When transactions get deleted from the database that means the
  1153  	// receipts that were created in the fork must also be deleted
  1154  	for _, tx := range diff {
  1155  		DeleteTxLookupEntry(bc.chainDb, tx.Hash())
  1156  	}
  1157  	if len(deletedLogs) > 0 {
  1158  		go bc.rmLogsFeed.Send(RemovedLogsEvent{deletedLogs})
  1159  	}
  1160  	if len(oldChain) > 0 {
  1161  		go func() {
  1162  			for _, block := range oldChain {
  1163  				bc.chainSideFeed.Send(ChainSideEvent{Block: block})
  1164  			}
  1165  		}()
  1166  	}
  1167  
  1168  	return nil
  1169  }
  1170  
  1171  // PostChainEvents iterates over the events generated by a chain insertion and
  1172  // posts them into the event feed.
  1173  // TODO: Should not expose PostChainEvents. The chain events should be posted in WriteBlock.
  1174  func (bc *BlockChain) PostChainEvents(events []interface{}, logs []*types.Log) {
  1175  	// post event logs for further processing
  1176  	if logs != nil {
  1177  		bc.logsFeed.Send(logs)
  1178  	}
  1179  	for _, event := range events {
  1180  		switch ev := event.(type) {
  1181  		case ChainEvent:
  1182  			bc.chainFeed.Send(ev)
  1183  
  1184  		case ChainHeadEvent:
  1185  			bc.chainHeadFeed.Send(ev)
  1186  
  1187  		case ChainSideEvent:
  1188  			bc.chainSideFeed.Send(ev)
  1189  		}
  1190  	}
  1191  }
  1192  
  1193  func (bc *BlockChain) update() {
  1194  	futureTimer := time.Tick(5 * time.Second)
  1195  	for {
  1196  		select {
  1197  		case <-futureTimer:
  1198  			bc.procFutureBlocks()
  1199  		case <-bc.quit:
  1200  			return
  1201  		}
  1202  	}
  1203  }
  1204  
  1205  // BadBlockArgs represents the entries in the list returned when bad blocks are queried.
  1206  type BadBlockArgs struct {
  1207  	Hash   common.Hash   `json:"hash"`
  1208  	Header *types.Header `json:"header"`
  1209  }
  1210  
  1211  // BadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  1212  func (bc *BlockChain) BadBlocks() ([]BadBlockArgs, error) {
  1213  	headers := make([]BadBlockArgs, 0, bc.badBlocks.Len())
  1214  	for _, hash := range bc.badBlocks.Keys() {
  1215  		if hdr, exist := bc.badBlocks.Peek(hash); exist {
  1216  			header := hdr.(*types.Header)
  1217  			headers = append(headers, BadBlockArgs{header.Hash(), header})
  1218  		}
  1219  	}
  1220  	return headers, nil
  1221  }
  1222  
  1223  // addBadBlock adds a bad block to the bad-block LRU cache
  1224  func (bc *BlockChain) addBadBlock(block *types.Block) {
  1225  	bc.badBlocks.Add(block.Header().Hash(), block.Header())
  1226  }
  1227  
  1228  // reportBlock logs a bad block error.
  1229  func (bc *BlockChain) reportBlock(block *types.Block, receipts types.Receipts, err error) {
  1230  	bc.addBadBlock(block)
  1231  
  1232  	var receiptString string
  1233  	for _, receipt := range receipts {
  1234  		receiptString += fmt.Sprintf("\t%v\n", receipt)
  1235  	}
  1236  	log.Error(fmt.Sprintf(`
  1237  ########## BAD BLOCK #########
  1238  Chain config: %v
  1239  
  1240  Number: %v
  1241  Hash: 0x%x
  1242  %v
  1243  
  1244  Error: %v
  1245  ##############################
  1246  `, bc.config, block.Number(), block.Hash(), receiptString, err))
  1247  }
  1248  
  1249  // InsertHeaderChain attempts to insert the given header chain in to the local
  1250  // chain, possibly creating a reorg. If an error is returned, it will return the
  1251  // index number of the failing header as well an error describing what went wrong.
  1252  //
  1253  // The verify parameter can be used to fine tune whether nonce verification
  1254  // should be done or not. The reason behind the optional check is because some
  1255  // of the header retrieval mechanisms already need to verify nonces, as well as
  1256  // because nonces can be verified sparsely, not needing to check each.
  1257  func (bc *BlockChain) InsertHeaderChain(chain []*types.Header, checkFreq int) (int, error) {
  1258  	start := time.Now()
  1259  	if i, err := bc.hc.ValidateHeaderChain(chain, checkFreq); err != nil {
  1260  		return i, err
  1261  	}
  1262  
  1263  	// Make sure only one thread manipulates the chain at once
  1264  	bc.chainmu.Lock()
  1265  	defer bc.chainmu.Unlock()
  1266  
  1267  	bc.wg.Add(1)
  1268  	defer bc.wg.Done()
  1269  
  1270  	whFunc := func(header *types.Header) error {
  1271  		bc.mu.Lock()
  1272  		defer bc.mu.Unlock()
  1273  
  1274  		_, err := bc.hc.WriteHeader(header)
  1275  		return err
  1276  	}
  1277  
  1278  	return bc.hc.InsertHeaderChain(chain, whFunc, start)
  1279  }
  1280  
  1281  // writeHeader writes a header into the local chain, given that its parent is
  1282  // already known. If the total difficulty of the newly inserted header becomes
  1283  // greater than the current known TD, the canonical chain is re-routed.
  1284  //
  1285  // Note: This method is not concurrent-safe with inserting blocks simultaneously
  1286  // into the chain, as side effects caused by reorganisations cannot be emulated
  1287  // without the real blocks. Hence, writing headers directly should only be done
  1288  // in two scenarios: pure-header mode of operation (light clients), or properly
  1289  // separated header/block phases (non-archive clients).
  1290  func (bc *BlockChain) writeHeader(header *types.Header) error {
  1291  	bc.wg.Add(1)
  1292  	defer bc.wg.Done()
  1293  
  1294  	bc.mu.Lock()
  1295  	defer bc.mu.Unlock()
  1296  
  1297  	_, err := bc.hc.WriteHeader(header)
  1298  	return err
  1299  }
  1300  
  1301  // CurrentHeader retrieves the current head header of the canonical chain. The
  1302  // header is retrieved from the HeaderChain's internal cache.
  1303  func (bc *BlockChain) CurrentHeader() *types.Header {
  1304  	bc.mu.RLock()
  1305  	defer bc.mu.RUnlock()
  1306  
  1307  	return bc.hc.CurrentHeader()
  1308  }
  1309  
  1310  // GetTd retrieves a block's total difficulty in the canonical chain from the
  1311  // database by hash and number, caching it if found.
  1312  func (bc *BlockChain) GetTd(hash common.Hash, number uint64) *big.Int {
  1313  	return bc.hc.GetTd(hash, number)
  1314  }
  1315  
  1316  // GetTdByHash retrieves a block's total difficulty in the canonical chain from the
  1317  // database by hash, caching it if found.
  1318  func (bc *BlockChain) GetTdByHash(hash common.Hash) *big.Int {
  1319  	return bc.hc.GetTdByHash(hash)
  1320  }
  1321  
  1322  // GetHeader retrieves a block header from the database by hash and number,
  1323  // caching it if found.
  1324  func (bc *BlockChain) GetHeader(hash common.Hash, number uint64) *types.Header {
  1325  	return bc.hc.GetHeader(hash, number)
  1326  }
  1327  
  1328  // GetHeaderByHash retrieves a block header from the database by hash, caching it if
  1329  // found.
  1330  func (bc *BlockChain) GetHeaderByHash(hash common.Hash) *types.Header {
  1331  	return bc.hc.GetHeaderByHash(hash)
  1332  }
  1333  
  1334  // HasHeader checks if a block header is present in the database or not, caching
  1335  // it if present.
  1336  func (bc *BlockChain) HasHeader(hash common.Hash, number uint64) bool {
  1337  	return bc.hc.HasHeader(hash, number)
  1338  }
  1339  
  1340  // GetBlockHashesFromHash retrieves a number of block hashes starting at a given
  1341  // hash, fetching towards the genesis block.
  1342  func (bc *BlockChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []common.Hash {
  1343  	return bc.hc.GetBlockHashesFromHash(hash, max)
  1344  }
  1345  
  1346  // GetHeaderByNumber retrieves a block header from the database by number,
  1347  // caching it (associated with its hash) if found.
  1348  func (bc *BlockChain) GetHeaderByNumber(number uint64) *types.Header {
  1349  	return bc.hc.GetHeaderByNumber(number)
  1350  }
  1351  
  1352  // Config retrieves the blockchain's chain configuration.
  1353  func (bc *BlockChain) Config() *params.ChainConfig { return bc.config }
  1354  
  1355  // Engine retrieves the blockchain's consensus engine.
  1356  func (bc *BlockChain) Engine() consensus.Engine { return bc.engine }
  1357  
  1358  // SubscribeRemovedLogsEvent registers a subscription of RemovedLogsEvent.
  1359  func (bc *BlockChain) SubscribeRemovedLogsEvent(ch chan<- RemovedLogsEvent) event.Subscription {
  1360  	return bc.scope.Track(bc.rmLogsFeed.Subscribe(ch))
  1361  }
  1362  
  1363  // SubscribeChainEvent registers a subscription of ChainEvent.
  1364  func (bc *BlockChain) SubscribeChainEvent(ch chan<- ChainEvent) event.Subscription {
  1365  	return bc.scope.Track(bc.chainFeed.Subscribe(ch))
  1366  }
  1367  
  1368  // SubscribeChainHeadEvent registers a subscription of ChainHeadEvent.
  1369  func (bc *BlockChain) SubscribeChainHeadEvent(ch chan<- ChainHeadEvent) event.Subscription {
  1370  	return bc.scope.Track(bc.chainHeadFeed.Subscribe(ch))
  1371  }
  1372  
  1373  // SubscribeChainSideEvent registers a subscription of ChainSideEvent.
  1374  func (bc *BlockChain) SubscribeChainSideEvent(ch chan<- ChainSideEvent) event.Subscription {
  1375  	return bc.scope.Track(bc.chainSideFeed.Subscribe(ch))
  1376  }
  1377  
  1378  // SubscribeLogsEvent registers a subscription of []*types.Log.
  1379  func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription {
  1380  	return bc.scope.Track(bc.logsFeed.Subscribe(ch))
  1381  }