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