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