github.com/daragao/go-ethereum@v1.8.14-0.20180809141559-45eaef243198/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  
    24  	"github.com/ethereum/go-ethereum/accounts"
    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/ethdb"
    32  	"github.com/ethereum/go-ethereum/event"
    33  	"github.com/ethereum/go-ethereum/log"
    34  	"github.com/ethereum/go-ethereum/params"
    35  )
    36  
    37  // Backend wraps all methods required for mining.
    38  type Backend interface {
    39  	AccountManager() *accounts.Manager
    40  	BlockChain() *core.BlockChain
    41  	TxPool() *core.TxPool
    42  	ChainDb() ethdb.Database
    43  }
    44  
    45  // Miner creates blocks and searches for proof-of-work values.
    46  type Miner struct {
    47  	mux      *event.TypeMux
    48  	worker   *worker
    49  	coinbase common.Address
    50  	eth      Backend
    51  	engine   consensus.Engine
    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) *Miner {
    58  	miner := &Miner{
    59  		eth:      eth,
    60  		mux:      mux,
    61  		engine:   engine,
    62  		worker:   newWorker(config, engine, eth, mux),
    63  		canStart: 1,
    64  	}
    65  	miner.Register(NewCpuAgent(eth.BlockChain(), engine))
    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  out:
    78  	for ev := range events.Chan() {
    79  		switch ev.Data.(type) {
    80  		case downloader.StartEvent:
    81  			atomic.StoreInt32(&self.canStart, 0)
    82  			if self.Mining() {
    83  				self.Stop()
    84  				atomic.StoreInt32(&self.shouldStart, 1)
    85  				log.Info("Mining aborted due to sync")
    86  			}
    87  		case downloader.DoneEvent, downloader.FailedEvent:
    88  			shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
    89  
    90  			atomic.StoreInt32(&self.canStart, 1)
    91  			atomic.StoreInt32(&self.shouldStart, 0)
    92  			if shouldStart {
    93  				self.Start(self.coinbase)
    94  			}
    95  			// unsubscribe. we're only interested in this event once
    96  			events.Unsubscribe()
    97  			// stop immediately and ignore all further pending events
    98  			break out
    99  		}
   100  	}
   101  }
   102  
   103  func (self *Miner) Start(coinbase common.Address) {
   104  	atomic.StoreInt32(&self.shouldStart, 1)
   105  	self.SetEtherbase(coinbase)
   106  
   107  	if atomic.LoadInt32(&self.canStart) == 0 {
   108  		log.Info("Network syncing, will start miner afterwards")
   109  		return
   110  	}
   111  	self.worker.start()
   112  	self.worker.commitNewWork()
   113  }
   114  
   115  func (self *Miner) Stop() {
   116  	self.worker.stop()
   117  	atomic.StoreInt32(&self.shouldStart, 0)
   118  }
   119  
   120  func (self *Miner) Register(agent Agent) {
   121  	self.worker.register(agent)
   122  }
   123  
   124  func (self *Miner) Unregister(agent Agent) {
   125  	self.worker.unregister(agent)
   126  }
   127  
   128  func (self *Miner) Mining() bool {
   129  	return self.worker.isRunning()
   130  }
   131  
   132  func (self *Miner) HashRate() uint64 {
   133  	if pow, ok := self.engine.(consensus.PoW); ok {
   134  		return uint64(pow.Hashrate())
   135  	}
   136  	return 0
   137  }
   138  
   139  func (self *Miner) SetExtra(extra []byte) error {
   140  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   141  		return fmt.Errorf("Extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   142  	}
   143  	self.worker.setExtra(extra)
   144  	return nil
   145  }
   146  
   147  // Pending returns the currently pending block and associated state.
   148  func (self *Miner) Pending() (*types.Block, *state.StateDB) {
   149  	return self.worker.pending()
   150  }
   151  
   152  // PendingBlock returns the currently pending block.
   153  //
   154  // Note, to access both the pending block and the pending state
   155  // simultaneously, please use Pending(), as the pending state can
   156  // change between multiple method calls
   157  func (self *Miner) PendingBlock() *types.Block {
   158  	return self.worker.pendingBlock()
   159  }
   160  
   161  func (self *Miner) SetEtherbase(addr common.Address) {
   162  	self.coinbase = addr
   163  	self.worker.setEtherbase(addr)
   164  }