github.com/ConsenSys/Quorum@v20.10.0+incompatible/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/ethdb"
    34  	"github.com/ethereum/go-ethereum/event"
    35  	"github.com/ethereum/go-ethereum/log"
    36  	"github.com/ethereum/go-ethereum/params"
    37  )
    38  
    39  // Backend wraps all methods required for mining.
    40  type Backend interface {
    41  	BlockChain() *core.BlockChain
    42  	TxPool() *core.TxPool
    43  	ChainDb() ethdb.Database
    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  	AllowedFutureBlockTime uint64         // Max time (in seconds) from current time allowed for blocks, before they're considered future blocks
    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  
    68  	canStart    int32 // can start indicates whether we can start the mining operation
    69  	shouldStart int32 // should start indicates whether we should start after sync
    70  }
    71  
    72  func New(eth Backend, config *Config, chainConfig *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, isLocalBlock func(block *types.Block) bool) *Miner {
    73  	miner := &Miner{
    74  		eth:      eth,
    75  		mux:      mux,
    76  		engine:   engine,
    77  		exitCh:   make(chan struct{}),
    78  		worker:   newWorker(config, chainConfig, engine, eth, mux, isLocalBlock),
    79  		canStart: 1,
    80  	}
    81  	go miner.update()
    82  
    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 (self *Miner) update() {
    91  	events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
    92  	defer events.Unsubscribe()
    93  
    94  	for {
    95  		select {
    96  		case ev := <-events.Chan():
    97  			if ev == nil {
    98  				return
    99  			}
   100  			switch ev.Data.(type) {
   101  			case downloader.StartEvent:
   102  				atomic.StoreInt32(&self.canStart, 0)
   103  				if self.Mining() {
   104  					self.Stop()
   105  					atomic.StoreInt32(&self.shouldStart, 1)
   106  					log.Info("Mining aborted due to sync")
   107  				}
   108  			case downloader.DoneEvent, downloader.FailedEvent:
   109  				shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
   110  
   111  				atomic.StoreInt32(&self.canStart, 1)
   112  				atomic.StoreInt32(&self.shouldStart, 0)
   113  				if shouldStart {
   114  					self.Start(self.coinbase)
   115  				}
   116  				// stop immediately and ignore all further pending events
   117  				return
   118  			}
   119  		case <-self.exitCh:
   120  			return
   121  		}
   122  	}
   123  }
   124  
   125  func (self *Miner) Start(coinbase common.Address) {
   126  	atomic.StoreInt32(&self.shouldStart, 1)
   127  	self.SetEtherbase(coinbase)
   128  
   129  	if atomic.LoadInt32(&self.canStart) == 0 {
   130  		log.Info("Network syncing, will start miner afterwards")
   131  		return
   132  	}
   133  	self.worker.start()
   134  }
   135  
   136  func (self *Miner) Stop() {
   137  	self.worker.stop()
   138  	atomic.StoreInt32(&self.shouldStart, 0)
   139  }
   140  
   141  func (self *Miner) Close() {
   142  	self.worker.close()
   143  	close(self.exitCh)
   144  }
   145  
   146  func (self *Miner) Mining() bool {
   147  	return self.worker.isRunning()
   148  }
   149  
   150  func (self *Miner) HashRate() uint64 {
   151  	if pow, ok := self.engine.(consensus.PoW); ok {
   152  		return uint64(pow.Hashrate())
   153  	}
   154  	return 0
   155  }
   156  
   157  func (self *Miner) SetExtra(extra []byte) error {
   158  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   159  		return fmt.Errorf("Extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   160  	}
   161  	self.worker.setExtra(extra)
   162  	return nil
   163  }
   164  
   165  // SetRecommitInterval sets the interval for sealing work resubmitting.
   166  func (self *Miner) SetRecommitInterval(interval time.Duration) {
   167  	self.worker.setRecommitInterval(interval)
   168  }
   169  
   170  // Pending returns the currently pending block and associated state.
   171  func (self *Miner) Pending() (*types.Block, *state.StateDB, *state.StateDB) {
   172  	return self.worker.pending()
   173  }
   174  
   175  // PendingBlock returns the currently pending block.
   176  //
   177  // Note, to access both the pending block and the pending state
   178  // simultaneously, please use Pending(), as the pending state can
   179  // change between multiple method calls
   180  func (self *Miner) PendingBlock() *types.Block {
   181  	return self.worker.pendingBlock()
   182  }
   183  
   184  func (self *Miner) SetEtherbase(addr common.Address) {
   185  	self.coinbase = addr
   186  	self.worker.setEtherbase(addr)
   187  }