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