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