github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/miner/miner.go (about)

     1  // Copyright 2014 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 implements Ethereum block creation and mining.
    18  package miner
    19  
    20  import (
    21  	"fmt"
    22  	"math/big"
    23  	"sync"
    24  	"time"
    25  
    26  	"github.com/scroll-tech/go-ethereum/common"
    27  	"github.com/scroll-tech/go-ethereum/common/hexutil"
    28  	"github.com/scroll-tech/go-ethereum/consensus"
    29  	"github.com/scroll-tech/go-ethereum/core"
    30  	"github.com/scroll-tech/go-ethereum/core/state"
    31  	"github.com/scroll-tech/go-ethereum/core/types"
    32  	"github.com/scroll-tech/go-ethereum/eth/downloader"
    33  	"github.com/scroll-tech/go-ethereum/ethdb"
    34  	"github.com/scroll-tech/go-ethereum/event"
    35  	"github.com/scroll-tech/go-ethereum/log"
    36  	"github.com/scroll-tech/go-ethereum/params"
    37  	"github.com/scroll-tech/go-ethereum/rollup/sync_service"
    38  )
    39  
    40  // Backend wraps all methods required for mining.
    41  type Backend interface {
    42  	BlockChain() *core.BlockChain
    43  	TxPool() *core.TxPool
    44  	ChainDb() ethdb.Database
    45  	SyncService() *sync_service.SyncService
    46  }
    47  
    48  // Config is the configuration parameters of mining.
    49  type Config struct {
    50  	Etherbase  common.Address `toml:",omitempty"` // Public address for block mining rewards (default = first account)
    51  	Notify     []string       `toml:",omitempty"` // HTTP URL list to be notified of new work packages (only useful in ethash).
    52  	NotifyFull bool           `toml:",omitempty"` // Notify with pending block headers instead of work packages
    53  	ExtraData  hexutil.Bytes  `toml:",omitempty"` // Block extra data set by the miner
    54  	GasFloor   uint64         // Target gas floor for mined blocks.
    55  	GasCeil    uint64         // Target gas ceiling for mined blocks.
    56  	GasPrice   *big.Int       // Minimum gas price for mining a transaction
    57  	Recommit   time.Duration  // The time interval for miner to re-create mining work.
    58  	Noverify   bool           // Disable remote mining solution verification(only useful in ethash).
    59  
    60  	StoreSkippedTxTraces bool // Whether store the wrapped traces when storing a skipped tx
    61  }
    62  
    63  // Miner creates blocks and searches for proof-of-work values.
    64  type Miner struct {
    65  	mux      *event.TypeMux
    66  	worker   *worker
    67  	coinbase common.Address
    68  	eth      Backend
    69  	engine   consensus.Engine
    70  	exitCh   chan struct{}
    71  	startCh  chan common.Address
    72  	stopCh   chan struct{}
    73  
    74  	wg sync.WaitGroup
    75  }
    76  
    77  func New(eth Backend, config *Config, chainConfig *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, isLocalBlock func(block *types.Block) bool) *Miner {
    78  	miner := &Miner{
    79  		eth:     eth,
    80  		mux:     mux,
    81  		engine:  engine,
    82  		exitCh:  make(chan struct{}),
    83  		startCh: make(chan common.Address),
    84  		stopCh:  make(chan struct{}),
    85  		worker:  newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, true),
    86  	}
    87  	miner.wg.Add(1)
    88  	go miner.update()
    89  	return miner
    90  }
    91  
    92  // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
    93  // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
    94  // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
    95  // and halt your mining operation for as long as the DOS continues.
    96  func (miner *Miner) update() {
    97  	defer miner.wg.Done()
    98  
    99  	events := miner.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
   100  	defer func() {
   101  		if !events.Closed() {
   102  			events.Unsubscribe()
   103  		}
   104  	}()
   105  
   106  	shouldStart := false
   107  	canStart := true
   108  	dlEventCh := events.Chan()
   109  	for {
   110  		select {
   111  		case ev := <-dlEventCh:
   112  			if ev == nil {
   113  				// Unsubscription done, stop listening
   114  				dlEventCh = nil
   115  				continue
   116  			}
   117  			switch ev.Data.(type) {
   118  			case downloader.StartEvent:
   119  				wasMining := miner.Mining()
   120  				miner.worker.stop()
   121  				canStart = false
   122  				if wasMining {
   123  					// Resume mining after sync was finished
   124  					shouldStart = true
   125  					log.Info("Mining aborted due to sync")
   126  				}
   127  			case downloader.FailedEvent:
   128  				canStart = true
   129  				if shouldStart {
   130  					miner.SetEtherbase(miner.coinbase)
   131  					miner.worker.start()
   132  				}
   133  			case downloader.DoneEvent:
   134  				canStart = true
   135  				if shouldStart {
   136  					miner.SetEtherbase(miner.coinbase)
   137  					miner.worker.start()
   138  				}
   139  				// Stop reacting to downloader events
   140  				events.Unsubscribe()
   141  			}
   142  		case addr := <-miner.startCh:
   143  			miner.SetEtherbase(addr)
   144  			if canStart {
   145  				miner.worker.start()
   146  			}
   147  			shouldStart = true
   148  		case <-miner.stopCh:
   149  			shouldStart = false
   150  			miner.worker.stop()
   151  		case <-miner.exitCh:
   152  			miner.worker.close()
   153  			return
   154  		}
   155  	}
   156  }
   157  
   158  func (miner *Miner) Start(coinbase common.Address) {
   159  	miner.startCh <- coinbase
   160  }
   161  
   162  func (miner *Miner) Stop() {
   163  	miner.stopCh <- struct{}{}
   164  }
   165  
   166  func (miner *Miner) Close() {
   167  	close(miner.exitCh)
   168  	miner.wg.Wait()
   169  }
   170  
   171  func (miner *Miner) Mining() bool {
   172  	return miner.worker.isRunning()
   173  }
   174  
   175  func (miner *Miner) Hashrate() uint64 {
   176  	if pow, ok := miner.engine.(consensus.PoW); ok {
   177  		return uint64(pow.Hashrate())
   178  	}
   179  	return 0
   180  }
   181  
   182  func (miner *Miner) SetExtra(extra []byte) error {
   183  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   184  		return fmt.Errorf("extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   185  	}
   186  	miner.worker.setExtra(extra)
   187  	return nil
   188  }
   189  
   190  // SetRecommitInterval sets the interval for sealing work resubmitting.
   191  func (miner *Miner) SetRecommitInterval(interval time.Duration) {
   192  	miner.worker.setRecommitInterval(interval)
   193  }
   194  
   195  // Pending returns the currently pending block and associated state.
   196  func (miner *Miner) Pending() (*types.Block, *state.StateDB) {
   197  	return miner.worker.pending()
   198  }
   199  
   200  // PendingBlock returns the currently pending block.
   201  //
   202  // Note, to access both the pending block and the pending state
   203  // simultaneously, please use Pending(), as the pending state can
   204  // change between multiple method calls
   205  func (miner *Miner) PendingBlock() *types.Block {
   206  	return miner.worker.pendingBlock()
   207  }
   208  
   209  // PendingBlockAndReceipts returns the currently pending block and corresponding receipts.
   210  func (miner *Miner) PendingBlockAndReceipts() (*types.Block, types.Receipts) {
   211  	return miner.worker.pendingBlockAndReceipts()
   212  }
   213  
   214  func (miner *Miner) SetEtherbase(addr common.Address) {
   215  	miner.coinbase = addr
   216  	miner.worker.setEtherbase(addr)
   217  }
   218  
   219  // SetGasCeil sets the gaslimit to strive for when mining blocks post 1559.
   220  // For pre-1559 blocks, it sets the ceiling.
   221  func (miner *Miner) SetGasCeil(ceil uint64) {
   222  	miner.worker.setGasCeil(ceil)
   223  }
   224  
   225  // EnablePreseal turns on the preseal mining feature. It's enabled by default.
   226  // Note this function shouldn't be exposed to API, it's unnecessary for users
   227  // (miners) to actually know the underlying detail. It's only for outside project
   228  // which uses this library.
   229  func (miner *Miner) EnablePreseal() {
   230  	miner.worker.enablePreseal()
   231  }
   232  
   233  // DisablePreseal turns off the preseal mining feature. It's necessary for some
   234  // fake consensus engine which can seal blocks instantaneously.
   235  // Note this function shouldn't be exposed to API, it's unnecessary for users
   236  // (miners) to actually know the underlying detail. It's only for outside project
   237  // which uses this library.
   238  func (miner *Miner) DisablePreseal() {
   239  	miner.worker.disablePreseal()
   240  }
   241  
   242  // SubscribePendingLogs starts delivering logs from pending transactions
   243  // to the given channel.
   244  func (miner *Miner) SubscribePendingLogs(ch chan<- []*types.Log) event.Subscription {
   245  	return miner.worker.pendingLogsFeed.Subscribe(ch)
   246  }