github.com/bencicandrej/quorum@v2.2.6-0.20190909091323-878cab86f711+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  	"sync/atomic"
    23  	"time"
    24  
    25  	"github.com/ethereum/go-ethereum/common"
    26  	"github.com/ethereum/go-ethereum/consensus"
    27  	"github.com/ethereum/go-ethereum/core"
    28  	"github.com/ethereum/go-ethereum/core/state"
    29  	"github.com/ethereum/go-ethereum/core/types"
    30  	"github.com/ethereum/go-ethereum/eth/downloader"
    31  	"github.com/ethereum/go-ethereum/event"
    32  	"github.com/ethereum/go-ethereum/log"
    33  	"github.com/ethereum/go-ethereum/params"
    34  	"github.com/ethereum/go-ethereum/ethdb"
    35  )
    36  
    37  // Backend wraps all methods required for mining.
    38  type Backend interface {
    39  	BlockChain() *core.BlockChain
    40  	TxPool() *core.TxPool
    41  	ChainDb() ethdb.Database
    42  }
    43  
    44  // Miner creates blocks and searches for proof-of-work values.
    45  type Miner struct {
    46  	mux      *event.TypeMux
    47  	worker   *worker
    48  	coinbase common.Address
    49  	eth      Backend
    50  	engine   consensus.Engine
    51  	exitCh   chan struct{}
    52  
    53  	canStart    int32 // can start indicates whether we can start the mining operation
    54  	shouldStart int32 // should start indicates whether we should start after sync
    55  }
    56  
    57  func New(eth Backend, config *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, recommit time.Duration, gasFloor, gasCeil uint64, isLocalBlock func(block *types.Block) bool) *Miner {
    58  	miner := &Miner{
    59  		eth:      eth,
    60  		mux:      mux,
    61  		engine:   engine,
    62  		exitCh:   make(chan struct{}),
    63  		worker:   newWorker(config, engine, eth, mux, recommit, gasFloor, gasCeil, isLocalBlock),
    64  		canStart: 1,
    65  	}
    66  	go miner.update()
    67  
    68  	return miner
    69  }
    70  
    71  // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
    72  // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
    73  // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
    74  // and halt your mining operation for as long as the DOS continues.
    75  func (self *Miner) update() {
    76  	events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
    77  	defer events.Unsubscribe()
    78  
    79  	for {
    80  		select {
    81  		case ev := <-events.Chan():
    82  			if ev == nil {
    83  				return
    84  			}
    85  			switch ev.Data.(type) {
    86  			case downloader.StartEvent:
    87  				atomic.StoreInt32(&self.canStart, 0)
    88  				if self.Mining() {
    89  					self.Stop()
    90  					atomic.StoreInt32(&self.shouldStart, 1)
    91  					log.Info("Mining aborted due to sync")
    92  				}
    93  			case downloader.DoneEvent, downloader.FailedEvent:
    94  				shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
    95  
    96  				atomic.StoreInt32(&self.canStart, 1)
    97  				atomic.StoreInt32(&self.shouldStart, 0)
    98  				if shouldStart {
    99  					self.Start(self.coinbase)
   100  				}
   101  				// stop immediately and ignore all further pending events
   102  				return
   103  			}
   104  		case <-self.exitCh:
   105  			return
   106  		}
   107  	}
   108  }
   109  
   110  func (self *Miner) Start(coinbase common.Address) {
   111  	atomic.StoreInt32(&self.shouldStart, 1)
   112  	self.SetEtherbase(coinbase)
   113  
   114  	if atomic.LoadInt32(&self.canStart) == 0 {
   115  		log.Info("Network syncing, will start miner afterwards")
   116  		return
   117  	}
   118  	self.worker.start()
   119  }
   120  
   121  func (self *Miner) Stop() {
   122  	self.worker.stop()
   123  	atomic.StoreInt32(&self.shouldStart, 0)
   124  }
   125  
   126  func (self *Miner) Close() {
   127  	self.worker.close()
   128  	close(self.exitCh)
   129  }
   130  
   131  func (self *Miner) Mining() bool {
   132  	return self.worker.isRunning()
   133  }
   134  
   135  func (self *Miner) HashRate() uint64 {
   136  	if pow, ok := self.engine.(consensus.PoW); ok {
   137  		return uint64(pow.Hashrate())
   138  	}
   139  	return 0
   140  }
   141  
   142  func (self *Miner) SetExtra(extra []byte) error {
   143  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   144  		return fmt.Errorf("Extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   145  	}
   146  	self.worker.setExtra(extra)
   147  	return nil
   148  }
   149  
   150  // SetRecommitInterval sets the interval for sealing work resubmitting.
   151  func (self *Miner) SetRecommitInterval(interval time.Duration) {
   152  	self.worker.setRecommitInterval(interval)
   153  }
   154  
   155  // Pending returns the currently pending block and associated state.
   156  func (self *Miner) Pending() (*types.Block, *state.StateDB, *state.StateDB) {
   157  	return self.worker.pending()
   158  }
   159  
   160  // PendingBlock returns the currently pending block.
   161  //
   162  // Note, to access both the pending block and the pending state
   163  // simultaneously, please use Pending(), as the pending state can
   164  // change between multiple method calls
   165  func (self *Miner) PendingBlock() *types.Block {
   166  	return self.worker.pendingBlock()
   167  }
   168  
   169  func (self *Miner) SetEtherbase(addr common.Address) {
   170  	self.coinbase = addr
   171  	self.worker.setEtherbase(addr)
   172  }