github.com/authcall/reference-optimistic-geth@v0.0.0-20220816224302-06313bfeb8d2/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/ethereum/go-ethereum/common"
    27  	"github.com/ethereum/go-ethereum/common/hexutil"
    28  	"github.com/ethereum/go-ethereum/consensus"
    29  	"github.com/ethereum/go-ethereum/core"
    30  	"github.com/ethereum/go-ethereum/core/state"
    31  	"github.com/ethereum/go-ethereum/core/types"
    32  	"github.com/ethereum/go-ethereum/eth/downloader"
    33  	"github.com/ethereum/go-ethereum/event"
    34  	"github.com/ethereum/go-ethereum/log"
    35  	"github.com/ethereum/go-ethereum/params"
    36  )
    37  
    38  // Backend wraps all methods required for mining. Only full node is capable
    39  // to offer all the functions here.
    40  type Backend interface {
    41  	BlockChain() *core.BlockChain
    42  	TxPool() *core.TxPool
    43  	StateAtBlock(block *types.Block, reexec uint64, base *state.StateDB, checkLive bool, preferDisk bool) (statedb *state.StateDB, err error)
    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  	NotifyFull bool           `toml:",omitempty"` // Notify with pending block headers instead of work packages
    51  	ExtraData  hexutil.Bytes  `toml:",omitempty"` // Block extra data set by the miner
    52  	GasFloor   uint64         // Target gas floor for mined blocks.
    53  	GasCeil    uint64         // Target gas ceiling for mined blocks.
    54  	GasPrice   *big.Int       // Minimum gas price for mining a transaction
    55  	Recommit   time.Duration  // The time interval for miner to re-create mining work.
    56  	Noverify   bool           // Disable remote mining solution verification(only useful in ethash).
    57  }
    58  
    59  // Miner creates blocks and searches for proof-of-work values.
    60  type Miner struct {
    61  	mux      *event.TypeMux
    62  	worker   *worker
    63  	coinbase common.Address
    64  	eth      Backend
    65  	engine   consensus.Engine
    66  	exitCh   chan struct{}
    67  	startCh  chan common.Address
    68  	stopCh   chan struct{}
    69  
    70  	wg sync.WaitGroup
    71  }
    72  
    73  func New(eth Backend, config *Config, chainConfig *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, isLocalBlock func(header *types.Header) bool) *Miner {
    74  	miner := &Miner{
    75  		eth:     eth,
    76  		mux:     mux,
    77  		engine:  engine,
    78  		exitCh:  make(chan struct{}),
    79  		startCh: make(chan common.Address),
    80  		stopCh:  make(chan struct{}),
    81  		worker:  newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, true),
    82  	}
    83  	miner.wg.Add(1)
    84  	go miner.update()
    85  	return miner
    86  }
    87  
    88  // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
    89  // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
    90  // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
    91  // and halt your mining operation for as long as the DOS continues.
    92  func (miner *Miner) update() {
    93  	defer miner.wg.Done()
    94  
    95  	events := miner.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
    96  	defer func() {
    97  		if !events.Closed() {
    98  			events.Unsubscribe()
    99  		}
   100  	}()
   101  
   102  	shouldStart := false
   103  	canStart := true
   104  	dlEventCh := events.Chan()
   105  	for {
   106  		select {
   107  		case ev := <-dlEventCh:
   108  			if ev == nil {
   109  				// Unsubscription done, stop listening
   110  				dlEventCh = nil
   111  				continue
   112  			}
   113  			switch ev.Data.(type) {
   114  			case downloader.StartEvent:
   115  				wasMining := miner.Mining()
   116  				miner.worker.stop()
   117  				canStart = false
   118  				if wasMining {
   119  					// Resume mining after sync was finished
   120  					shouldStart = true
   121  					log.Info("Mining aborted due to sync")
   122  				}
   123  			case downloader.FailedEvent:
   124  				canStart = true
   125  				if shouldStart {
   126  					miner.SetEtherbase(miner.coinbase)
   127  					miner.worker.start()
   128  				}
   129  			case downloader.DoneEvent:
   130  				canStart = true
   131  				if shouldStart {
   132  					miner.SetEtherbase(miner.coinbase)
   133  					miner.worker.start()
   134  				}
   135  				// Stop reacting to downloader events
   136  				events.Unsubscribe()
   137  			}
   138  		case addr := <-miner.startCh:
   139  			miner.SetEtherbase(addr)
   140  			if canStart {
   141  				miner.worker.start()
   142  			}
   143  			shouldStart = true
   144  		case <-miner.stopCh:
   145  			shouldStart = false
   146  			miner.worker.stop()
   147  		case <-miner.exitCh:
   148  			miner.worker.close()
   149  			return
   150  		}
   151  	}
   152  }
   153  
   154  func (miner *Miner) Start(coinbase common.Address) {
   155  	miner.startCh <- coinbase
   156  }
   157  
   158  func (miner *Miner) Stop() {
   159  	miner.stopCh <- struct{}{}
   160  }
   161  
   162  func (miner *Miner) Close() {
   163  	close(miner.exitCh)
   164  	miner.wg.Wait()
   165  }
   166  
   167  func (miner *Miner) Mining() bool {
   168  	return miner.worker.isRunning()
   169  }
   170  
   171  func (miner *Miner) Hashrate() uint64 {
   172  	if pow, ok := miner.engine.(consensus.PoW); ok {
   173  		return uint64(pow.Hashrate())
   174  	}
   175  	return 0
   176  }
   177  
   178  func (miner *Miner) SetExtra(extra []byte) error {
   179  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   180  		return fmt.Errorf("extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   181  	}
   182  	miner.worker.setExtra(extra)
   183  	return nil
   184  }
   185  
   186  // SetRecommitInterval sets the interval for sealing work resubmitting.
   187  func (miner *Miner) SetRecommitInterval(interval time.Duration) {
   188  	miner.worker.setRecommitInterval(interval)
   189  }
   190  
   191  // Pending returns the currently pending block and associated state.
   192  func (miner *Miner) Pending() (*types.Block, *state.StateDB) {
   193  	return miner.worker.pending()
   194  }
   195  
   196  // PendingBlock returns the currently pending block.
   197  //
   198  // Note, to access both the pending block and the pending state
   199  // simultaneously, please use Pending(), as the pending state can
   200  // change between multiple method calls
   201  func (miner *Miner) PendingBlock() *types.Block {
   202  	return miner.worker.pendingBlock()
   203  }
   204  
   205  // PendingBlockAndReceipts returns the currently pending block and corresponding receipts.
   206  func (miner *Miner) PendingBlockAndReceipts() (*types.Block, types.Receipts) {
   207  	return miner.worker.pendingBlockAndReceipts()
   208  }
   209  
   210  func (miner *Miner) SetEtherbase(addr common.Address) {
   211  	miner.coinbase = addr
   212  	miner.worker.setEtherbase(addr)
   213  }
   214  
   215  // SetGasCeil sets the gaslimit to strive for when mining blocks post 1559.
   216  // For pre-1559 blocks, it sets the ceiling.
   217  func (miner *Miner) SetGasCeil(ceil uint64) {
   218  	miner.worker.setGasCeil(ceil)
   219  }
   220  
   221  // EnablePreseal turns on the preseal mining feature. It's enabled by default.
   222  // Note this function shouldn't be exposed to API, it's unnecessary for users
   223  // (miners) to actually know the underlying detail. It's only for outside project
   224  // which uses this library.
   225  func (miner *Miner) EnablePreseal() {
   226  	miner.worker.enablePreseal()
   227  }
   228  
   229  // DisablePreseal turns off the preseal mining feature. It's necessary for some
   230  // fake consensus engine which can seal blocks instantaneously.
   231  // Note this function shouldn't be exposed to API, it's unnecessary for users
   232  // (miners) to actually know the underlying detail. It's only for outside project
   233  // which uses this library.
   234  func (miner *Miner) DisablePreseal() {
   235  	miner.worker.disablePreseal()
   236  }
   237  
   238  // SubscribePendingLogs starts delivering logs from pending transactions
   239  // to the given channel.
   240  func (miner *Miner) SubscribePendingLogs(ch chan<- []*types.Log) event.Subscription {
   241  	return miner.worker.pendingLogsFeed.Subscribe(ch)
   242  }
   243  
   244  // GetSealingBlockAsync requests to generate a sealing block according to the
   245  // given parameters. Regardless of whether the generation is successful or not,
   246  // there is always a result that will be returned through the result channel.
   247  // The difference is that if the execution fails, the returned result is nil
   248  // and the concrete error is dropped silently.
   249  func (miner *Miner) GetSealingBlockAsync(parent common.Hash, timestamp uint64, coinbase common.Address, random common.Hash, noTxs bool, forceTxs types.Transactions) (chan *types.Block, error) {
   250  	resCh, _, err := miner.worker.getSealingBlock(parent, timestamp, coinbase, random, noTxs, forceTxs)
   251  	if err != nil {
   252  		return nil, err
   253  	}
   254  	return resCh, nil
   255  }
   256  
   257  // GetSealingBlockSync creates a sealing block according to the given parameters.
   258  // If the generation is failed or the underlying work is already closed, an error
   259  // will be returned.
   260  func (miner *Miner) GetSealingBlockSync(parent common.Hash, timestamp uint64, coinbase common.Address, random common.Hash, noTxs bool, forceTxs types.Transactions) (*types.Block, error) {
   261  	resCh, errCh, err := miner.worker.getSealingBlock(parent, timestamp, coinbase, random, noTxs, forceTxs)
   262  	if err != nil {
   263  		return nil, err
   264  	}
   265  	return <-resCh, <-errCh
   266  }