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