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