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