github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/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/atomic"
    24  	"time"
    25  
    26  	"github.com/ethereum-optimism/optimism/l2geth/common"
    27  	"github.com/ethereum-optimism/optimism/l2geth/common/hexutil"
    28  	"github.com/ethereum-optimism/optimism/l2geth/consensus"
    29  	"github.com/ethereum-optimism/optimism/l2geth/core"
    30  	"github.com/ethereum-optimism/optimism/l2geth/core/state"
    31  	"github.com/ethereum-optimism/optimism/l2geth/core/types"
    32  	"github.com/ethereum-optimism/optimism/l2geth/eth/downloader"
    33  	"github.com/ethereum-optimism/optimism/l2geth/event"
    34  	"github.com/ethereum-optimism/optimism/l2geth/log"
    35  	"github.com/ethereum-optimism/optimism/l2geth/params"
    36  	"github.com/ethereum-optimism/optimism/l2geth/rollup"
    37  )
    38  
    39  // Backend wraps all methods required for mining.
    40  type Backend interface {
    41  	BlockChain() *core.BlockChain
    42  	TxPool() *core.TxPool
    43  	SyncService() *rollup.SyncService
    44  }
    45  
    46  // Config is the configuration parameters of mining.
    47  type Config struct {
    48  	Etherbase common.Address `toml:",omitempty"` // Public address for block mining rewards (default = first account)
    49  	Notify    []string       `toml:",omitempty"` // HTTP URL list to be notified of new work packages(only useful in ethash).
    50  	ExtraData hexutil.Bytes  `toml:",omitempty"` // Block extra data set by the miner
    51  	GasFloor  uint64         // Target gas floor for mined blocks.
    52  	GasCeil   uint64         // Target gas ceiling for mined blocks.
    53  	GasPrice  *big.Int       // Minimum gas price for mining a transaction
    54  	Recommit  time.Duration  // The time interval for miner to re-create mining work.
    55  	Noverify  bool           // Disable remote mining solution verification(only useful in ethash).
    56  }
    57  
    58  // Miner creates blocks and searches for proof-of-work values.
    59  type Miner struct {
    60  	mux      *event.TypeMux
    61  	worker   *worker
    62  	coinbase common.Address
    63  	eth      Backend
    64  	engine   consensus.Engine
    65  	exitCh   chan struct{}
    66  
    67  	canStart    int32 // can start indicates whether we can start the mining operation
    68  	shouldStart int32 // should start indicates whether we should start after sync
    69  }
    70  
    71  func New(eth Backend, config *Config, chainConfig *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, isLocalBlock func(block *types.Block) bool) *Miner {
    72  	miner := &Miner{
    73  		eth:      eth,
    74  		mux:      mux,
    75  		engine:   engine,
    76  		exitCh:   make(chan struct{}),
    77  		worker:   newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, true),
    78  		canStart: 1,
    79  	}
    80  	go miner.update()
    81  
    82  	return miner
    83  }
    84  
    85  // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
    86  // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
    87  // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
    88  // and halt your mining operation for as long as the DOS continues.
    89  func (miner *Miner) update() {
    90  	events := miner.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
    91  	defer events.Unsubscribe()
    92  
    93  	for {
    94  		select {
    95  		case ev := <-events.Chan():
    96  			if ev == nil {
    97  				return
    98  			}
    99  			switch ev.Data.(type) {
   100  			case downloader.StartEvent:
   101  				atomic.StoreInt32(&miner.canStart, 0)
   102  				if miner.Mining() {
   103  					miner.Stop()
   104  					atomic.StoreInt32(&miner.shouldStart, 1)
   105  					log.Info("Mining aborted due to sync")
   106  				}
   107  			case downloader.DoneEvent, downloader.FailedEvent:
   108  				shouldStart := atomic.LoadInt32(&miner.shouldStart) == 1
   109  
   110  				atomic.StoreInt32(&miner.canStart, 1)
   111  				atomic.StoreInt32(&miner.shouldStart, 0)
   112  				if shouldStart {
   113  					miner.Start(miner.coinbase)
   114  				}
   115  				// stop immediately and ignore all further pending events
   116  				return
   117  			}
   118  		case <-miner.exitCh:
   119  			return
   120  		}
   121  	}
   122  }
   123  
   124  func (miner *Miner) Start(coinbase common.Address) {
   125  	atomic.StoreInt32(&miner.shouldStart, 1)
   126  	miner.SetEtherbase(coinbase)
   127  
   128  	if atomic.LoadInt32(&miner.canStart) == 0 {
   129  		log.Info("Network syncing, will start miner afterwards")
   130  		return
   131  	}
   132  	miner.worker.start()
   133  }
   134  
   135  func (miner *Miner) Stop() {
   136  	miner.worker.stop()
   137  	atomic.StoreInt32(&miner.shouldStart, 0)
   138  }
   139  
   140  func (miner *Miner) Close() {
   141  	miner.worker.close()
   142  	close(miner.exitCh)
   143  }
   144  
   145  func (miner *Miner) Mining() bool {
   146  	return miner.worker.isRunning()
   147  }
   148  
   149  func (miner *Miner) HashRate() uint64 {
   150  	if pow, ok := miner.engine.(consensus.PoW); ok {
   151  		return uint64(pow.Hashrate())
   152  	}
   153  	return 0
   154  }
   155  
   156  func (miner *Miner) SetExtra(extra []byte) error {
   157  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   158  		return fmt.Errorf("extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   159  	}
   160  	miner.worker.setExtra(extra)
   161  	return nil
   162  }
   163  
   164  // SetRecommitInterval sets the interval for sealing work resubmitting.
   165  func (miner *Miner) SetRecommitInterval(interval time.Duration) {
   166  	miner.worker.setRecommitInterval(interval)
   167  }
   168  
   169  // Pending returns the currently pending block and associated state.
   170  func (miner *Miner) Pending() (*types.Block, *state.StateDB) {
   171  	return miner.worker.pending()
   172  }
   173  
   174  // PendingBlock returns the currently pending block.
   175  //
   176  // Note, to access both the pending block and the pending state
   177  // simultaneously, please use Pending(), as the pending state can
   178  // change between multiple method calls
   179  func (miner *Miner) PendingBlock() *types.Block {
   180  	return miner.worker.pendingBlock()
   181  }
   182  
   183  func (miner *Miner) SetEtherbase(addr common.Address) {
   184  	miner.coinbase = addr
   185  	miner.worker.setEtherbase(addr)
   186  }
   187  
   188  // SubscribePendingLogs starts delivering logs from pending transactions
   189  // to the given channel.
   190  func (self *Miner) SubscribePendingLogs(ch chan<- []*types.Log) event.Subscription {
   191  	return self.worker.pendingLogsFeed.Subscribe(ch)
   192  }