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