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