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