github.com/JFJun/bsc@v1.0.0/miner/worker.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package miner
    18  
    19  import (
    20  	"bytes"
    21  	"errors"
    22  	"math/big"
    23  	"sync"
    24  	"sync/atomic"
    25  	"time"
    26  
    27  	mapset "github.com/deckarep/golang-set"
    28  	"github.com/JFJun/bsc/common"
    29  	"github.com/JFJun/bsc/consensus"
    30  	"github.com/JFJun/bsc/consensus/misc"
    31  	"github.com/JFJun/bsc/consensus/parlia"
    32  	"github.com/JFJun/bsc/core"
    33  	"github.com/JFJun/bsc/core/state"
    34  	"github.com/JFJun/bsc/core/systemcontracts"
    35  	"github.com/JFJun/bsc/core/types"
    36  	"github.com/JFJun/bsc/event"
    37  	"github.com/JFJun/bsc/log"
    38  	"github.com/JFJun/bsc/metrics"
    39  	"github.com/JFJun/bsc/params"
    40  )
    41  
    42  const (
    43  	// resultQueueSize is the size of channel listening to sealing result.
    44  	resultQueueSize = 10
    45  
    46  	// txChanSize is the size of channel listening to NewTxsEvent.
    47  	// The number is referenced from the size of tx pool.
    48  	txChanSize = 4096
    49  
    50  	// chainHeadChanSize is the size of channel listening to ChainHeadEvent.
    51  	chainHeadChanSize = 10
    52  
    53  	// chainSideChanSize is the size of channel listening to ChainSideEvent.
    54  	chainSideChanSize = 10
    55  
    56  	// resubmitAdjustChanSize is the size of resubmitting interval adjustment channel.
    57  	resubmitAdjustChanSize = 10
    58  
    59  	// miningLogAtDepth is the number of confirmations before logging successful mining.
    60  	miningLogAtDepth = 11
    61  
    62  	// minRecommitInterval is the minimal time interval to recreate the mining block with
    63  	// any newly arrived transactions.
    64  	minRecommitInterval = 1 * time.Second
    65  
    66  	// maxRecommitInterval is the maximum time interval to recreate the mining block with
    67  	// any newly arrived transactions.
    68  	maxRecommitInterval = 15 * time.Second
    69  
    70  	// intervalAdjustRatio is the impact a single interval adjustment has on sealing work
    71  	// resubmitting interval.
    72  	intervalAdjustRatio = 0.1
    73  
    74  	// intervalAdjustBias is applied during the new resubmit interval calculation in favor of
    75  	// increasing upper limit or decreasing lower limit so that the limit can be reachable.
    76  	intervalAdjustBias = 200 * 1000.0 * 1000.0
    77  
    78  	// staleThreshold is the maximum depth of the acceptable stale block.
    79  	staleThreshold = 11
    80  )
    81  
    82  var (
    83  	commitTxsTimer = metrics.NewRegisteredTimer("worker/committxs", nil)
    84  )
    85  
    86  // environment is the worker's current environment and holds all of the current state information.
    87  type environment struct {
    88  	signer types.Signer
    89  
    90  	state     *state.StateDB // apply state changes here
    91  	ancestors mapset.Set     // ancestor set (used for checking uncle parent validity)
    92  	family    mapset.Set     // family set (used for checking uncle invalidity)
    93  	uncles    mapset.Set     // uncle set
    94  	tcount    int            // tx count in cycle
    95  	gasPool   *core.GasPool  // available gas used to pack transactions
    96  
    97  	header   *types.Header
    98  	txs      []*types.Transaction
    99  	receipts []*types.Receipt
   100  }
   101  
   102  // task contains all information for consensus engine sealing and result submitting.
   103  type task struct {
   104  	receipts  []*types.Receipt
   105  	state     *state.StateDB
   106  	block     *types.Block
   107  	createdAt time.Time
   108  }
   109  
   110  const (
   111  	commitInterruptNone int32 = iota
   112  	commitInterruptNewHead
   113  	commitInterruptResubmit
   114  )
   115  
   116  // newWorkReq represents a request for new sealing work submitting with relative interrupt notifier.
   117  type newWorkReq struct {
   118  	interrupt *int32
   119  	noempty   bool
   120  	timestamp int64
   121  }
   122  
   123  // intervalAdjust represents a resubmitting interval adjustment.
   124  type intervalAdjust struct {
   125  	ratio float64
   126  	inc   bool
   127  }
   128  
   129  // worker is the main object which takes care of submitting new work to consensus engine
   130  // and gathering the sealing result.
   131  type worker struct {
   132  	config      *Config
   133  	chainConfig *params.ChainConfig
   134  	engine      consensus.Engine
   135  	eth         Backend
   136  	chain       *core.BlockChain
   137  
   138  	// Feeds
   139  	pendingLogsFeed event.Feed
   140  
   141  	// Subscriptions
   142  	mux          *event.TypeMux
   143  	txsCh        chan core.NewTxsEvent
   144  	txsSub       event.Subscription
   145  	chainHeadCh  chan core.ChainHeadEvent
   146  	chainHeadSub event.Subscription
   147  	chainSideCh  chan core.ChainSideEvent
   148  	chainSideSub event.Subscription
   149  
   150  	// Channels
   151  	newWorkCh          chan *newWorkReq
   152  	taskCh             chan *task
   153  	resultCh           chan *types.Block
   154  	startCh            chan struct{}
   155  	exitCh             chan struct{}
   156  	resubmitIntervalCh chan time.Duration
   157  	resubmitAdjustCh   chan *intervalAdjust
   158  
   159  	current      *environment                 // An environment for current running cycle.
   160  	localUncles  map[common.Hash]*types.Block // A set of side blocks generated locally as the possible uncle blocks.
   161  	remoteUncles map[common.Hash]*types.Block // A set of side blocks as the possible uncle blocks.
   162  	unconfirmed  *unconfirmedBlocks           // A set of locally mined blocks pending canonicalness confirmations.
   163  
   164  	mu       sync.RWMutex // The lock used to protect the coinbase and extra fields
   165  	coinbase common.Address
   166  	extra    []byte
   167  
   168  	pendingMu    sync.RWMutex
   169  	pendingTasks map[common.Hash]*task
   170  
   171  	snapshotMu    sync.RWMutex // The lock used to protect the block snapshot and state snapshot
   172  	snapshotBlock *types.Block
   173  	snapshotState *state.StateDB
   174  
   175  	// atomic status counters
   176  	running int32 // The indicator whether the consensus engine is running or not.
   177  	newTxs  int32 // New arrival transaction count since last sealing work submitting.
   178  
   179  	// External functions
   180  	isLocalBlock func(block *types.Block) bool // Function used to determine whether the specified block is mined by local miner.
   181  
   182  	// Test hooks
   183  	newTaskHook  func(*task)                        // Method to call upon receiving a new sealing task.
   184  	skipSealHook func(*task) bool                   // Method to decide whether skipping the sealing.
   185  	fullTaskHook func()                             // Method to call before pushing the full sealing task.
   186  	resubmitHook func(time.Duration, time.Duration) // Method to call upon updating resubmitting interval.
   187  }
   188  
   189  func newWorker(config *Config, chainConfig *params.ChainConfig, engine consensus.Engine, eth Backend, mux *event.TypeMux, isLocalBlock func(*types.Block) bool, init bool) *worker {
   190  	worker := &worker{
   191  		config:             config,
   192  		chainConfig:        chainConfig,
   193  		engine:             engine,
   194  		eth:                eth,
   195  		mux:                mux,
   196  		chain:              eth.BlockChain(),
   197  		isLocalBlock:       isLocalBlock,
   198  		localUncles:        make(map[common.Hash]*types.Block),
   199  		remoteUncles:       make(map[common.Hash]*types.Block),
   200  		unconfirmed:        newUnconfirmedBlocks(eth.BlockChain(), miningLogAtDepth),
   201  		pendingTasks:       make(map[common.Hash]*task),
   202  		txsCh:              make(chan core.NewTxsEvent, txChanSize),
   203  		chainHeadCh:        make(chan core.ChainHeadEvent, chainHeadChanSize),
   204  		chainSideCh:        make(chan core.ChainSideEvent, chainSideChanSize),
   205  		newWorkCh:          make(chan *newWorkReq),
   206  		taskCh:             make(chan *task),
   207  		resultCh:           make(chan *types.Block, resultQueueSize),
   208  		exitCh:             make(chan struct{}),
   209  		startCh:            make(chan struct{}, 1),
   210  		resubmitIntervalCh: make(chan time.Duration),
   211  		resubmitAdjustCh:   make(chan *intervalAdjust, resubmitAdjustChanSize),
   212  	}
   213  	// Subscribe NewTxsEvent for tx pool
   214  	worker.txsSub = eth.TxPool().SubscribeNewTxsEvent(worker.txsCh)
   215  	// Subscribe events for blockchain
   216  	worker.chainHeadSub = eth.BlockChain().SubscribeChainHeadEvent(worker.chainHeadCh)
   217  	worker.chainSideSub = eth.BlockChain().SubscribeChainSideEvent(worker.chainSideCh)
   218  
   219  	// Sanitize recommit interval if the user-specified one is too short.
   220  	recommit := worker.config.Recommit
   221  	if recommit < minRecommitInterval {
   222  		log.Warn("Sanitizing miner recommit interval", "provided", recommit, "updated", minRecommitInterval)
   223  		recommit = minRecommitInterval
   224  	}
   225  
   226  	go worker.mainLoop()
   227  	go worker.newWorkLoop(recommit)
   228  	go worker.resultLoop()
   229  	go worker.taskLoop()
   230  
   231  	// Submit first work to initialize pending state.
   232  	if init {
   233  		worker.startCh <- struct{}{}
   234  	}
   235  	return worker
   236  }
   237  
   238  // setEtherbase sets the etherbase used to initialize the block coinbase field.
   239  func (w *worker) setEtherbase(addr common.Address) {
   240  	w.mu.Lock()
   241  	defer w.mu.Unlock()
   242  	w.coinbase = addr
   243  }
   244  
   245  // setExtra sets the content used to initialize the block extra field.
   246  func (w *worker) setExtra(extra []byte) {
   247  	w.mu.Lock()
   248  	defer w.mu.Unlock()
   249  	w.extra = extra
   250  }
   251  
   252  // setRecommitInterval updates the interval for miner sealing work recommitting.
   253  func (w *worker) setRecommitInterval(interval time.Duration) {
   254  	w.resubmitIntervalCh <- interval
   255  }
   256  
   257  // pending returns the pending state and corresponding block.
   258  func (w *worker) pending() (*types.Block, *state.StateDB) {
   259  	// return a snapshot to avoid contention on currentMu mutex
   260  	w.snapshotMu.RLock()
   261  	defer w.snapshotMu.RUnlock()
   262  	if w.snapshotState == nil {
   263  		return nil, nil
   264  	}
   265  	return w.snapshotBlock, w.snapshotState.Copy()
   266  }
   267  
   268  // pendingBlock returns pending block.
   269  func (w *worker) pendingBlock() *types.Block {
   270  	// return a snapshot to avoid contention on currentMu mutex
   271  	w.snapshotMu.RLock()
   272  	defer w.snapshotMu.RUnlock()
   273  	return w.snapshotBlock
   274  }
   275  
   276  // start sets the running status as 1 and triggers new work submitting.
   277  func (w *worker) start() {
   278  	atomic.StoreInt32(&w.running, 1)
   279  	w.startCh <- struct{}{}
   280  }
   281  
   282  // stop sets the running status as 0.
   283  func (w *worker) stop() {
   284  	atomic.StoreInt32(&w.running, 0)
   285  }
   286  
   287  // isRunning returns an indicator whether worker is running or not.
   288  func (w *worker) isRunning() bool {
   289  	return atomic.LoadInt32(&w.running) == 1
   290  }
   291  
   292  // close terminates all background threads maintained by the worker.
   293  // Note the worker does not support being closed multiple times.
   294  func (w *worker) close() {
   295  	close(w.exitCh)
   296  }
   297  
   298  // newWorkLoop is a standalone goroutine to submit new mining work upon received events.
   299  func (w *worker) newWorkLoop(recommit time.Duration) {
   300  	var (
   301  		interrupt   *int32
   302  		minRecommit = recommit // minimal resubmit interval specified by user.
   303  		timestamp   int64      // timestamp for each round of mining.
   304  	)
   305  
   306  	timer := time.NewTimer(0)
   307  	defer timer.Stop()
   308  	<-timer.C // discard the initial tick
   309  
   310  	// commit aborts in-flight transaction execution with given signal and resubmits a new one.
   311  	commit := func(noempty bool, s int32) {
   312  		if interrupt != nil {
   313  			atomic.StoreInt32(interrupt, s)
   314  		}
   315  		interrupt = new(int32)
   316  		w.newWorkCh <- &newWorkReq{interrupt: interrupt, noempty: noempty, timestamp: timestamp}
   317  		timer.Reset(recommit)
   318  		atomic.StoreInt32(&w.newTxs, 0)
   319  	}
   320  	// recalcRecommit recalculates the resubmitting interval upon feedback.
   321  	recalcRecommit := func(target float64, inc bool) {
   322  		var (
   323  			prev = float64(recommit.Nanoseconds())
   324  			next float64
   325  		)
   326  		if inc {
   327  			next = prev*(1-intervalAdjustRatio) + intervalAdjustRatio*(target+intervalAdjustBias)
   328  			// Recap if interval is larger than the maximum time interval
   329  			if next > float64(maxRecommitInterval.Nanoseconds()) {
   330  				next = float64(maxRecommitInterval.Nanoseconds())
   331  			}
   332  		} else {
   333  			next = prev*(1-intervalAdjustRatio) + intervalAdjustRatio*(target-intervalAdjustBias)
   334  			// Recap if interval is less than the user specified minimum
   335  			if next < float64(minRecommit.Nanoseconds()) {
   336  				next = float64(minRecommit.Nanoseconds())
   337  			}
   338  		}
   339  		recommit = time.Duration(int64(next))
   340  	}
   341  	// clearPending cleans the stale pending tasks.
   342  	clearPending := func(number uint64) {
   343  		w.pendingMu.Lock()
   344  		for h, t := range w.pendingTasks {
   345  			if t.block.NumberU64()+staleThreshold <= number {
   346  				delete(w.pendingTasks, h)
   347  			}
   348  		}
   349  		w.pendingMu.Unlock()
   350  	}
   351  
   352  	for {
   353  		select {
   354  		case <-w.startCh:
   355  			clearPending(w.chain.CurrentBlock().NumberU64())
   356  			timestamp = time.Now().Unix()
   357  			commit(false, commitInterruptNewHead)
   358  
   359  		case head := <-w.chainHeadCh:
   360  			if !w.isRunning() {
   361  				continue
   362  			}
   363  			clearPending(head.Block.NumberU64())
   364  			timestamp = time.Now().Unix()
   365  			commit(false, commitInterruptNewHead)
   366  
   367  		case <-timer.C:
   368  			// If mining is running resubmit a new work cycle periodically to pull in
   369  			// higher priced transactions. Disable this overhead for pending blocks.
   370  			if w.isRunning() && ((w.chainConfig.Ethash != nil) || (w.chainConfig.Clique != nil &&
   371  				w.chainConfig.Clique.Period > 0) || (w.chainConfig.Parlia != nil && w.chainConfig.Parlia.Period > 0)) {
   372  				// Short circuit if no new transaction arrives.
   373  				if atomic.LoadInt32(&w.newTxs) == 0 {
   374  					timer.Reset(recommit)
   375  					continue
   376  				}
   377  				commit(true, commitInterruptResubmit)
   378  			}
   379  
   380  		case interval := <-w.resubmitIntervalCh:
   381  			// Adjust resubmit interval explicitly by user.
   382  			if interval < minRecommitInterval {
   383  				log.Warn("Sanitizing miner recommit interval", "provided", interval, "updated", minRecommitInterval)
   384  				interval = minRecommitInterval
   385  			}
   386  			log.Info("Miner recommit interval update", "from", minRecommit, "to", interval)
   387  			minRecommit, recommit = interval, interval
   388  
   389  			if w.resubmitHook != nil {
   390  				w.resubmitHook(minRecommit, recommit)
   391  			}
   392  
   393  		case adjust := <-w.resubmitAdjustCh:
   394  			// Adjust resubmit interval by feedback.
   395  			if adjust.inc {
   396  				before := recommit
   397  				recalcRecommit(float64(recommit.Nanoseconds())/adjust.ratio, true)
   398  				log.Trace("Increase miner recommit interval", "from", before, "to", recommit)
   399  			} else {
   400  				before := recommit
   401  				recalcRecommit(float64(minRecommit.Nanoseconds()), false)
   402  				log.Trace("Decrease miner recommit interval", "from", before, "to", recommit)
   403  			}
   404  
   405  			if w.resubmitHook != nil {
   406  				w.resubmitHook(minRecommit, recommit)
   407  			}
   408  
   409  		case <-w.exitCh:
   410  			return
   411  		}
   412  	}
   413  }
   414  
   415  // mainLoop is a standalone goroutine to regenerate the sealing task based on the received event.
   416  func (w *worker) mainLoop() {
   417  	defer w.txsSub.Unsubscribe()
   418  	defer w.chainHeadSub.Unsubscribe()
   419  	defer w.chainSideSub.Unsubscribe()
   420  
   421  	for {
   422  		select {
   423  		case req := <-w.newWorkCh:
   424  			w.commitNewWork(req.interrupt, req.noempty, req.timestamp)
   425  
   426  		case ev := <-w.chainSideCh:
   427  			// Short circuit for duplicate side blocks
   428  			if _, ok := w.engine.(*parlia.Parlia); ok {
   429  				continue
   430  			}
   431  			if _, exist := w.localUncles[ev.Block.Hash()]; exist {
   432  				continue
   433  			}
   434  			if _, exist := w.remoteUncles[ev.Block.Hash()]; exist {
   435  				continue
   436  			}
   437  			// Add side block to possible uncle block set depending on the author.
   438  			if w.isLocalBlock != nil && w.isLocalBlock(ev.Block) {
   439  				w.localUncles[ev.Block.Hash()] = ev.Block
   440  			} else {
   441  				w.remoteUncles[ev.Block.Hash()] = ev.Block
   442  			}
   443  			// If our mining block contains less than 2 uncle blocks,
   444  			// add the new uncle block if valid and regenerate a mining block.
   445  			if w.isRunning() && w.current != nil && w.current.uncles.Cardinality() < 2 {
   446  				start := time.Now()
   447  				if err := w.commitUncle(w.current, ev.Block.Header()); err == nil {
   448  					var uncles []*types.Header
   449  					w.current.uncles.Each(func(item interface{}) bool {
   450  						hash, ok := item.(common.Hash)
   451  						if !ok {
   452  							return false
   453  						}
   454  						uncle, exist := w.localUncles[hash]
   455  						if !exist {
   456  							uncle, exist = w.remoteUncles[hash]
   457  						}
   458  						if !exist {
   459  							return false
   460  						}
   461  						uncles = append(uncles, uncle.Header())
   462  						return false
   463  					})
   464  					w.commit(uncles, nil, true, start)
   465  				}
   466  			}
   467  
   468  		case ev := <-w.txsCh:
   469  			// Apply transactions to the pending state if we're not mining.
   470  			//
   471  			// Note all transactions received may not be continuous with transactions
   472  			// already included in the current mining block. These transactions will
   473  			// be automatically eliminated.
   474  			if !w.isRunning() && w.current != nil {
   475  				// If block is already full, abort
   476  				if gp := w.current.gasPool; gp != nil && gp.Gas() < params.TxGas {
   477  					continue
   478  				}
   479  				w.mu.RLock()
   480  				coinbase := w.coinbase
   481  				w.mu.RUnlock()
   482  
   483  				txs := make(map[common.Address]types.Transactions)
   484  				for _, tx := range ev.Txs {
   485  					acc, _ := types.Sender(w.current.signer, tx)
   486  					txs[acc] = append(txs[acc], tx)
   487  				}
   488  				txset := types.NewTransactionsByPriceAndNonce(w.current.signer, txs)
   489  				tcount := w.current.tcount
   490  				w.commitTransactions(txset, coinbase, nil)
   491  				// Only update the snapshot if any new transactons were added
   492  				// to the pending block
   493  				if tcount != w.current.tcount {
   494  					w.updateSnapshot()
   495  				}
   496  			} else {
   497  				// If clique is running in dev mode(period is 0), disable
   498  				// advance sealing here.
   499  				if (w.chainConfig.Clique != nil && w.chainConfig.Clique.Period == 0) ||
   500  					(w.chainConfig.Parlia != nil && w.chainConfig.Parlia.Period == 0) {
   501  					w.commitNewWork(nil, true, time.Now().Unix())
   502  				}
   503  			}
   504  			atomic.AddInt32(&w.newTxs, int32(len(ev.Txs)))
   505  
   506  		// System stopped
   507  		case <-w.exitCh:
   508  			return
   509  		case <-w.txsSub.Err():
   510  			return
   511  		case <-w.chainHeadSub.Err():
   512  			return
   513  		case <-w.chainSideSub.Err():
   514  			return
   515  		}
   516  	}
   517  }
   518  
   519  // taskLoop is a standalone goroutine to fetch sealing task from the generator and
   520  // push them to consensus engine.
   521  func (w *worker) taskLoop() {
   522  	var (
   523  		stopCh chan struct{}
   524  		prev   common.Hash
   525  	)
   526  
   527  	// interrupt aborts the in-flight sealing task.
   528  	interrupt := func() {
   529  		if stopCh != nil {
   530  			close(stopCh)
   531  			stopCh = nil
   532  		}
   533  	}
   534  	for {
   535  		select {
   536  		case task := <-w.taskCh:
   537  			if w.newTaskHook != nil {
   538  				w.newTaskHook(task)
   539  			}
   540  			// Reject duplicate sealing work due to resubmitting.
   541  			sealHash := w.engine.SealHash(task.block.Header())
   542  			if sealHash == prev {
   543  				continue
   544  			}
   545  			// Interrupt previous sealing operation
   546  			interrupt()
   547  			stopCh, prev = make(chan struct{}), sealHash
   548  
   549  			if w.skipSealHook != nil && w.skipSealHook(task) {
   550  				continue
   551  			}
   552  			w.pendingMu.Lock()
   553  			w.pendingTasks[w.engine.SealHash(task.block.Header())] = task
   554  			w.pendingMu.Unlock()
   555  
   556  			if err := w.engine.Seal(w.chain, task.block, w.resultCh, stopCh); err != nil {
   557  				log.Warn("Block sealing failed", "err", err)
   558  			}
   559  		case <-w.exitCh:
   560  			interrupt()
   561  			return
   562  		}
   563  	}
   564  }
   565  
   566  // resultLoop is a standalone goroutine to handle sealing result submitting
   567  // and flush relative data to the database.
   568  func (w *worker) resultLoop() {
   569  	for {
   570  		select {
   571  		case block := <-w.resultCh:
   572  			// Short circuit when receiving empty result.
   573  			if block == nil {
   574  				continue
   575  			}
   576  			// Short circuit when receiving duplicate result caused by resubmitting.
   577  			if w.chain.HasBlock(block.Hash(), block.NumberU64()) {
   578  				continue
   579  			}
   580  			var (
   581  				sealhash = w.engine.SealHash(block.Header())
   582  				hash     = block.Hash()
   583  			)
   584  			w.pendingMu.RLock()
   585  			task, exist := w.pendingTasks[sealhash]
   586  			w.pendingMu.RUnlock()
   587  			if !exist {
   588  				log.Error("Block found but no relative pending task", "number", block.Number(), "sealhash", sealhash, "hash", hash)
   589  				continue
   590  			}
   591  			// Different block could share same sealhash, deep copy here to prevent write-write conflict.
   592  			var (
   593  				receipts = make([]*types.Receipt, len(task.receipts))
   594  				logs     []*types.Log
   595  			)
   596  			for i, receipt := range task.receipts {
   597  				// add block location fields
   598  				receipt.BlockHash = hash
   599  				receipt.BlockNumber = block.Number()
   600  				receipt.TransactionIndex = uint(i)
   601  
   602  				receipts[i] = new(types.Receipt)
   603  				*receipts[i] = *receipt
   604  				// Update the block hash in all logs since it is now available and not when the
   605  				// receipt/log of individual transactions were created.
   606  				for _, log := range receipt.Logs {
   607  					log.BlockHash = hash
   608  				}
   609  				logs = append(logs, receipt.Logs...)
   610  			}
   611  			// Commit block and state to database.
   612  			_, err := w.chain.WriteBlockWithState(block, receipts, logs, task.state, true)
   613  			if err != nil {
   614  				log.Error("Failed writing block to chain", "err", err)
   615  				continue
   616  			}
   617  			log.Info("Successfully sealed new block", "number", block.Number(), "sealhash", sealhash, "hash", hash,
   618  				"elapsed", common.PrettyDuration(time.Since(task.createdAt)))
   619  
   620  			// Broadcast the block and announce chain insertion event
   621  			w.mux.Post(core.NewMinedBlockEvent{Block: block})
   622  
   623  			// Insert the block into the set of pending ones to resultLoop for confirmations
   624  			w.unconfirmed.Insert(block.NumberU64(), block.Hash())
   625  
   626  		case <-w.exitCh:
   627  			return
   628  		}
   629  	}
   630  }
   631  
   632  // makeCurrent creates a new environment for the current cycle.
   633  func (w *worker) makeCurrent(parent *types.Block, header *types.Header) error {
   634  	state, err := w.chain.StateAt(parent.Root())
   635  	if err != nil {
   636  		return err
   637  	}
   638  	env := &environment{
   639  		signer:    types.NewEIP155Signer(w.chainConfig.ChainID),
   640  		state:     state,
   641  		ancestors: mapset.NewSet(),
   642  		family:    mapset.NewSet(),
   643  		uncles:    mapset.NewSet(),
   644  		header:    header,
   645  	}
   646  
   647  	// when 08 is processed ancestors contain 07 (quick block)
   648  	for _, ancestor := range w.chain.GetBlocksFromHash(parent.Hash(), 7) {
   649  		for _, uncle := range ancestor.Uncles() {
   650  			env.family.Add(uncle.Hash())
   651  		}
   652  		env.family.Add(ancestor.Hash())
   653  		env.ancestors.Add(ancestor.Hash())
   654  	}
   655  
   656  	// Keep track of transactions which return errors so they can be removed
   657  	env.tcount = 0
   658  	w.current = env
   659  	return nil
   660  }
   661  
   662  // commitUncle adds the given block to uncle block set, returns error if failed to add.
   663  func (w *worker) commitUncle(env *environment, uncle *types.Header) error {
   664  	hash := uncle.Hash()
   665  	if env.uncles.Contains(hash) {
   666  		return errors.New("uncle not unique")
   667  	}
   668  	if env.header.ParentHash == uncle.ParentHash {
   669  		return errors.New("uncle is sibling")
   670  	}
   671  	if !env.ancestors.Contains(uncle.ParentHash) {
   672  		return errors.New("uncle's parent unknown")
   673  	}
   674  	if env.family.Contains(hash) {
   675  		return errors.New("uncle already included")
   676  	}
   677  	env.uncles.Add(uncle.Hash())
   678  	return nil
   679  }
   680  
   681  // updateSnapshot updates pending snapshot block and state.
   682  // Note this function assumes the current variable is thread safe.
   683  func (w *worker) updateSnapshot() {
   684  	w.snapshotMu.Lock()
   685  	defer w.snapshotMu.Unlock()
   686  
   687  	var uncles []*types.Header
   688  	w.current.uncles.Each(func(item interface{}) bool {
   689  		hash, ok := item.(common.Hash)
   690  		if !ok {
   691  			return false
   692  		}
   693  		uncle, exist := w.localUncles[hash]
   694  		if !exist {
   695  			uncle, exist = w.remoteUncles[hash]
   696  		}
   697  		if !exist {
   698  			return false
   699  		}
   700  		uncles = append(uncles, uncle.Header())
   701  		return false
   702  	})
   703  
   704  	w.snapshotBlock = types.NewBlock(
   705  		w.current.header,
   706  		w.current.txs,
   707  		uncles,
   708  		w.current.receipts,
   709  	)
   710  
   711  	w.snapshotState = w.current.state.Copy()
   712  }
   713  
   714  func (w *worker) commitTransaction(tx *types.Transaction, coinbase common.Address) ([]*types.Log, error) {
   715  	snap := w.current.state.Snapshot()
   716  
   717  	receipt, err := core.ApplyTransaction(w.chainConfig, w.chain, &coinbase, w.current.gasPool, w.current.state, w.current.header, tx, &w.current.header.GasUsed, *w.chain.GetVMConfig())
   718  	if err != nil {
   719  		w.current.state.RevertToSnapshot(snap)
   720  		return nil, err
   721  	}
   722  	w.current.txs = append(w.current.txs, tx)
   723  	w.current.receipts = append(w.current.receipts, receipt)
   724  
   725  	return receipt.Logs, nil
   726  }
   727  
   728  func (w *worker) commitTransactions(txs *types.TransactionsByPriceAndNonce, coinbase common.Address, interrupt *int32) bool {
   729  	// Short circuit if current is nil
   730  	if w.current == nil {
   731  		return true
   732  	}
   733  
   734  	if w.current.gasPool == nil {
   735  		w.current.gasPool = new(core.GasPool).AddGas(w.current.header.GasLimit)
   736  		w.current.gasPool.SubGas(params.SystemTxsGas)
   737  	}
   738  
   739  	var coalescedLogs []*types.Log
   740  
   741  	for {
   742  		// In the following three cases, we will interrupt the execution of the transaction.
   743  		// (1) new head block event arrival, the interrupt signal is 1
   744  		// (2) worker start or restart, the interrupt signal is 1
   745  		// (3) worker recreate the mining block with any newly arrived transactions, the interrupt signal is 2.
   746  		// For the first two cases, the semi-finished work will be discarded.
   747  		// For the third case, the semi-finished work will be submitted to the consensus engine.
   748  		if interrupt != nil && atomic.LoadInt32(interrupt) != commitInterruptNone {
   749  			// Notify resubmit loop to increase resubmitting interval due to too frequent commits.
   750  			if atomic.LoadInt32(interrupt) == commitInterruptResubmit {
   751  				ratio := float64(w.current.header.GasLimit-w.current.gasPool.Gas()) / float64(w.current.header.GasLimit)
   752  				if ratio < 0.1 {
   753  					ratio = 0.1
   754  				}
   755  				w.resubmitAdjustCh <- &intervalAdjust{
   756  					ratio: ratio,
   757  					inc:   true,
   758  				}
   759  			}
   760  			return atomic.LoadInt32(interrupt) == commitInterruptNewHead
   761  		}
   762  		// If we don't have enough gas for any further transactions then we're done
   763  		if w.current.gasPool.Gas() < params.TxGas {
   764  			log.Trace("Not enough gas for further transactions", "have", w.current.gasPool, "want", params.TxGas)
   765  			break
   766  		}
   767  		// Retrieve the next transaction and abort if all done
   768  		tx := txs.Peek()
   769  		if tx == nil {
   770  			break
   771  		}
   772  		// Error may be ignored here. The error has already been checked
   773  		// during transaction acceptance is the transaction pool.
   774  		//
   775  		// We use the eip155 signer regardless of the current hf.
   776  		from, _ := types.Sender(w.current.signer, tx)
   777  		// Check whether the tx is replay protected. If we're not in the EIP155 hf
   778  		// phase, start ignoring the sender until we do.
   779  		if tx.Protected() && !w.chainConfig.IsEIP155(w.current.header.Number) {
   780  			log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", w.chainConfig.EIP155Block)
   781  
   782  			txs.Pop()
   783  			continue
   784  		}
   785  		// Start executing the transaction
   786  		w.current.state.Prepare(tx.Hash(), common.Hash{}, w.current.tcount)
   787  
   788  		logs, err := w.commitTransaction(tx, coinbase)
   789  		switch err {
   790  		case core.ErrGasLimitReached:
   791  			// Pop the current out-of-gas transaction without shifting in the next from the account
   792  			log.Trace("Gas limit exceeded for current block", "sender", from)
   793  			txs.Pop()
   794  
   795  		case core.ErrNonceTooLow:
   796  			// New head notification data race between the transaction pool and miner, shift
   797  			log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
   798  			txs.Shift()
   799  
   800  		case core.ErrNonceTooHigh:
   801  			// Reorg notification data race between the transaction pool and miner, skip account =
   802  			log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce())
   803  			txs.Pop()
   804  
   805  		case nil:
   806  			// Everything ok, collect the logs and shift in the next transaction from the same account
   807  			coalescedLogs = append(coalescedLogs, logs...)
   808  			w.current.tcount++
   809  			txs.Shift()
   810  
   811  		default:
   812  			// Strange error, discard the transaction and get the next in line (note, the
   813  			// nonce-too-high clause will prevent us from executing in vain).
   814  			log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
   815  			txs.Shift()
   816  		}
   817  	}
   818  
   819  	if !w.isRunning() && len(coalescedLogs) > 0 {
   820  		// We don't push the pendingLogsEvent while we are mining. The reason is that
   821  		// when we are mining, the worker will regenerate a mining block every 3 seconds.
   822  		// In order to avoid pushing the repeated pendingLog, we disable the pending log pushing.
   823  
   824  		// make a copy, the state caches the logs and these logs get "upgraded" from pending to mined
   825  		// logs by filling in the block hash when the block was mined by the local miner. This can
   826  		// cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed.
   827  		cpy := make([]*types.Log, len(coalescedLogs))
   828  		for i, l := range coalescedLogs {
   829  			cpy[i] = new(types.Log)
   830  			*cpy[i] = *l
   831  		}
   832  		w.pendingLogsFeed.Send(cpy)
   833  	}
   834  	// Notify resubmit loop to decrease resubmitting interval if current interval is larger
   835  	// than the user-specified one.
   836  	if interrupt != nil {
   837  		w.resubmitAdjustCh <- &intervalAdjust{inc: false}
   838  	}
   839  	return false
   840  }
   841  
   842  // commitNewWork generates several new sealing tasks based on the parent block.
   843  func (w *worker) commitNewWork(interrupt *int32, noempty bool, timestamp int64) {
   844  	w.mu.RLock()
   845  	defer w.mu.RUnlock()
   846  
   847  	tstart := time.Now()
   848  	parent := w.chain.CurrentBlock()
   849  
   850  	if parent.Time() >= uint64(timestamp) {
   851  		timestamp = int64(parent.Time() + 1)
   852  	}
   853  	// this will ensure we're not going off too far in the future
   854  	if now := time.Now().Unix(); timestamp > now+1 {
   855  		wait := time.Duration(timestamp-now) * time.Second
   856  		log.Info("Mining too far in the future", "wait", common.PrettyDuration(wait))
   857  		time.Sleep(wait)
   858  	}
   859  
   860  	num := parent.Number()
   861  	header := &types.Header{
   862  		ParentHash: parent.Hash(),
   863  		Number:     num.Add(num, common.Big1),
   864  		GasLimit:   core.CalcGasLimit(parent, w.config.GasFloor, w.config.GasCeil),
   865  		Extra:      w.extra,
   866  		Time:       uint64(timestamp),
   867  	}
   868  	// Only set the coinbase if our consensus engine is running (avoid spurious block rewards)
   869  	if w.isRunning() {
   870  		if w.coinbase == (common.Address{}) {
   871  			log.Error("Refusing to mine without etherbase")
   872  			return
   873  		}
   874  		header.Coinbase = w.coinbase
   875  	}
   876  	if err := w.engine.Prepare(w.chain, header); err != nil {
   877  		log.Error("Failed to prepare header for mining", "err", err)
   878  		return
   879  	}
   880  	// If we are care about TheDAO hard-fork check whether to override the extra-data or not
   881  	if daoBlock := w.chainConfig.DAOForkBlock; daoBlock != nil {
   882  		// Check whether the block is among the fork extra-override range
   883  		limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
   884  		if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
   885  			// Depending whether we support or oppose the fork, override differently
   886  			if w.chainConfig.DAOForkSupport {
   887  				header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
   888  			} else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
   889  				header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
   890  			}
   891  		}
   892  	}
   893  	// Could potentially happen if starting to mine in an odd state.
   894  	err := w.makeCurrent(parent, header)
   895  	if err != nil {
   896  		log.Error("Failed to create mining context", "err", err)
   897  		return
   898  	}
   899  	// Create the current work task and check any fork transitions needed
   900  	env := w.current
   901  	if w.chainConfig.DAOForkSupport && w.chainConfig.DAOForkBlock != nil && w.chainConfig.DAOForkBlock.Cmp(header.Number) == 0 {
   902  		misc.ApplyDAOHardFork(env.state)
   903  	}
   904  	systemcontracts.UpgradeBuildInSystemContract(w.chainConfig, header.Number, env.state)
   905  	// Accumulate the uncles for the current block
   906  	uncles := make([]*types.Header, 0, 2)
   907  	commitUncles := func(blocks map[common.Hash]*types.Block) {
   908  		// Clean up stale uncle blocks first
   909  		for hash, uncle := range blocks {
   910  			if uncle.NumberU64()+staleThreshold <= header.Number.Uint64() {
   911  				delete(blocks, hash)
   912  			}
   913  		}
   914  		for hash, uncle := range blocks {
   915  			if len(uncles) == 2 {
   916  				break
   917  			}
   918  			if err := w.commitUncle(env, uncle.Header()); err != nil {
   919  				log.Trace("Possible uncle rejected", "hash", hash, "reason", err)
   920  			} else {
   921  				log.Debug("Committing new uncle to block", "hash", hash)
   922  				uncles = append(uncles, uncle.Header())
   923  			}
   924  		}
   925  	}
   926  	// Prefer to locally generated uncle
   927  	commitUncles(w.localUncles)
   928  	commitUncles(w.remoteUncles)
   929  
   930  	if !noempty {
   931  		// Create an empty block based on temporary copied state for sealing in advance without waiting block
   932  		// execution finished.
   933  		w.commit(uncles, nil, false, tstart)
   934  	}
   935  
   936  	// Fill the block with all available pending transactions.
   937  	pending, err := w.eth.TxPool().Pending()
   938  	if err != nil {
   939  		log.Error("Failed to fetch pending transactions", "err", err)
   940  		return
   941  	}
   942  	// Short circuit if there is no available pending transactions
   943  	if len(pending) == 0 {
   944  		w.updateSnapshot()
   945  		return
   946  	}
   947  	start := time.Now()
   948  	// Split the pending transactions into locals and remotes
   949  	localTxs, remoteTxs := make(map[common.Address]types.Transactions), pending
   950  	for _, account := range w.eth.TxPool().Locals() {
   951  		if txs := remoteTxs[account]; len(txs) > 0 {
   952  			delete(remoteTxs, account)
   953  			localTxs[account] = txs
   954  		}
   955  	}
   956  	if len(localTxs) > 0 {
   957  		txs := types.NewTransactionsByPriceAndNonce(w.current.signer, localTxs)
   958  		if w.commitTransactions(txs, w.coinbase, interrupt) {
   959  			return
   960  		}
   961  	}
   962  	if len(remoteTxs) > 0 {
   963  		txs := types.NewTransactionsByPriceAndNonce(w.current.signer, remoteTxs)
   964  		if w.commitTransactions(txs, w.coinbase, interrupt) {
   965  			return
   966  		}
   967  	}
   968  	commitTxsTimer.UpdateSince(start)
   969  	log.Info("Gas pool", "height", header.Number.String(), "pool", w.current.gasPool.String())
   970  	w.commit(uncles, w.fullTaskHook, true, tstart)
   971  }
   972  
   973  // commit runs any post-transaction state modifications, assembles the final block
   974  // and commits new work if consensus engine is running.
   975  func (w *worker) commit(uncles []*types.Header, interval func(), update bool, start time.Time) error {
   976  	s := w.current.state.Copy()
   977  	block, receipts, err := w.engine.FinalizeAndAssemble(w.chain, types.CopyHeader(w.current.header), s, w.current.txs, uncles, w.current.receipts)
   978  	if err != nil {
   979  		return err
   980  	}
   981  	if w.isRunning() {
   982  		if interval != nil {
   983  			interval()
   984  		}
   985  		select {
   986  		case w.taskCh <- &task{receipts: receipts, state: s, block: block, createdAt: time.Now()}:
   987  			w.unconfirmed.Shift(block.NumberU64() - 1)
   988  
   989  			feesWei := new(big.Int)
   990  			for i, tx := range block.Transactions() {
   991  				feesWei.Add(feesWei, new(big.Int).Mul(new(big.Int).SetUint64(receipts[i].GasUsed), tx.GasPrice()))
   992  			}
   993  			feesEth := new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(params.Ether)))
   994  
   995  			log.Info("Commit new mining work", "number", block.Number(), "sealhash", w.engine.SealHash(block.Header()),
   996  				"uncles", len(uncles), "txs", w.current.tcount, "gas", block.GasUsed(), "fees", feesEth, "elapsed", common.PrettyDuration(time.Since(start)))
   997  
   998  		case <-w.exitCh:
   999  			log.Info("Worker has exited")
  1000  		}
  1001  	}
  1002  	if update {
  1003  		w.updateSnapshot()
  1004  	}
  1005  	return nil
  1006  }
  1007  
  1008  // postSideBlock fires a side chain event, only use it for testing.
  1009  func (w *worker) postSideBlock(event core.ChainSideEvent) {
  1010  	select {
  1011  	case w.chainSideCh <- event:
  1012  	case <-w.exitCh:
  1013  	}
  1014  }