github.com/bamzi/go-ethereum@v1.6.7-0.20170704111104-138f26c93af1/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  
    49  	worker *worker
    50  
    51  	coinbase common.Address
    52  	mining   int32
    53  	eth      Backend
    54  	engine   consensus.Engine
    55  
    56  	canStart    int32 // can start indicates whether we can start the mining operation
    57  	shouldStart int32 // should start indicates whether we should start after sync
    58  }
    59  
    60  func New(eth Backend, config *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine) *Miner {
    61  	miner := &Miner{
    62  		eth:      eth,
    63  		mux:      mux,
    64  		engine:   engine,
    65  		worker:   newWorker(config, engine, common.Address{}, eth, mux),
    66  		canStart: 1,
    67  	}
    68  	miner.Register(NewCpuAgent(eth.BlockChain(), engine))
    69  	go miner.update()
    70  
    71  	return miner
    72  }
    73  
    74  // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
    75  // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
    76  // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
    77  // and halt your mining operation for as long as the DOS continues.
    78  func (self *Miner) update() {
    79  	events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
    80  out:
    81  	for ev := range events.Chan() {
    82  		switch ev.Data.(type) {
    83  		case downloader.StartEvent:
    84  			atomic.StoreInt32(&self.canStart, 0)
    85  			if self.Mining() {
    86  				self.Stop()
    87  				atomic.StoreInt32(&self.shouldStart, 1)
    88  				log.Info("Mining aborted due to sync")
    89  			}
    90  		case downloader.DoneEvent, downloader.FailedEvent:
    91  			shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
    92  
    93  			atomic.StoreInt32(&self.canStart, 1)
    94  			atomic.StoreInt32(&self.shouldStart, 0)
    95  			if shouldStart {
    96  				self.Start(self.coinbase)
    97  			}
    98  			// unsubscribe. we're only interested in this event once
    99  			events.Unsubscribe()
   100  			// stop immediately and ignore all further pending events
   101  			break out
   102  		}
   103  	}
   104  }
   105  
   106  func (self *Miner) Start(coinbase common.Address) {
   107  	atomic.StoreInt32(&self.shouldStart, 1)
   108  	self.worker.setEtherbase(coinbase)
   109  	self.coinbase = coinbase
   110  
   111  	if atomic.LoadInt32(&self.canStart) == 0 {
   112  		log.Info("Network syncing, will start miner afterwards")
   113  		return
   114  	}
   115  	atomic.StoreInt32(&self.mining, 1)
   116  
   117  	log.Info("Starting mining operation")
   118  	self.worker.start()
   119  	self.worker.commitNewWork()
   120  }
   121  
   122  func (self *Miner) Stop() {
   123  	self.worker.stop()
   124  	atomic.StoreInt32(&self.mining, 0)
   125  	atomic.StoreInt32(&self.shouldStart, 0)
   126  }
   127  
   128  func (self *Miner) Register(agent Agent) {
   129  	if self.Mining() {
   130  		agent.Start()
   131  	}
   132  	self.worker.register(agent)
   133  }
   134  
   135  func (self *Miner) Unregister(agent Agent) {
   136  	self.worker.unregister(agent)
   137  }
   138  
   139  func (self *Miner) Mining() bool {
   140  	return atomic.LoadInt32(&self.mining) > 0
   141  }
   142  
   143  func (self *Miner) HashRate() (tot int64) {
   144  	if pow, ok := self.engine.(consensus.PoW); ok {
   145  		tot += int64(pow.Hashrate())
   146  	}
   147  	// do we care this might race? is it worth we're rewriting some
   148  	// aspects of the worker/locking up agents so we can get an accurate
   149  	// hashrate?
   150  	for agent := range self.worker.agents {
   151  		if _, ok := agent.(*CpuAgent); !ok {
   152  			tot += agent.GetHashRate()
   153  		}
   154  	}
   155  	return
   156  }
   157  
   158  func (self *Miner) SetExtra(extra []byte) error {
   159  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   160  		return fmt.Errorf("Extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   161  	}
   162  	self.worker.setExtra(extra)
   163  	return nil
   164  }
   165  
   166  // Pending returns the currently pending block and associated state.
   167  func (self *Miner) Pending() (*types.Block, *state.StateDB) {
   168  	return self.worker.pending()
   169  }
   170  
   171  // PendingBlock returns the currently pending block.
   172  //
   173  // Note, to access both the pending block and the pending state
   174  // simultaneously, please use Pending(), as the pending state can
   175  // change between multiple method calls
   176  func (self *Miner) PendingBlock() *types.Block {
   177  	return self.worker.pendingBlock()
   178  }
   179  
   180  func (self *Miner) SetEtherbase(addr common.Address) {
   181  	self.coinbase = addr
   182  	self.worker.setEtherbase(addr)
   183  }