github.com/avence12/go-ethereum@v1.5.10-0.20170320123548-1dfd65f6d047/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  
    25  	"github.com/ethereum/go-ethereum/accounts"
    26  	"github.com/ethereum/go-ethereum/common"
    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  	"github.com/ethereum/go-ethereum/pow"
    36  )
    37  
    38  // Backend wraps all methods required for mining.
    39  type Backend interface {
    40  	AccountManager() *accounts.Manager
    41  	BlockChain() *core.BlockChain
    42  	TxPool() *core.TxPool
    43  	ChainDb() ethdb.Database
    44  }
    45  
    46  // Miner creates blocks and searches for proof-of-work values.
    47  type Miner struct {
    48  	mux *event.TypeMux
    49  
    50  	worker *worker
    51  
    52  	threads  int
    53  	coinbase common.Address
    54  	mining   int32
    55  	eth      Backend
    56  	pow      pow.PoW
    57  
    58  	canStart    int32 // can start indicates whether we can start the mining operation
    59  	shouldStart int32 // should start indicates whether we should start after sync
    60  }
    61  
    62  func New(eth Backend, config *params.ChainConfig, mux *event.TypeMux, pow pow.PoW) *Miner {
    63  	miner := &Miner{
    64  		eth:      eth,
    65  		mux:      mux,
    66  		pow:      pow,
    67  		worker:   newWorker(config, common.Address{}, eth, mux),
    68  		canStart: 1,
    69  	}
    70  	go miner.update()
    71  
    72  	return miner
    73  }
    74  
    75  // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
    76  // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
    77  // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
    78  // and halt your mining operation for as long as the DOS continues.
    79  func (self *Miner) update() {
    80  	events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
    81  out:
    82  	for ev := range events.Chan() {
    83  		switch ev.Data.(type) {
    84  		case downloader.StartEvent:
    85  			atomic.StoreInt32(&self.canStart, 0)
    86  			if self.Mining() {
    87  				self.Stop()
    88  				atomic.StoreInt32(&self.shouldStart, 1)
    89  				log.Info(fmt.Sprint("Mining operation aborted due to sync operation"))
    90  			}
    91  		case downloader.DoneEvent, downloader.FailedEvent:
    92  			shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
    93  
    94  			atomic.StoreInt32(&self.canStart, 1)
    95  			atomic.StoreInt32(&self.shouldStart, 0)
    96  			if shouldStart {
    97  				self.Start(self.coinbase, self.threads)
    98  			}
    99  			// unsubscribe. we're only interested in this event once
   100  			events.Unsubscribe()
   101  			// stop immediately and ignore all further pending events
   102  			break out
   103  		}
   104  	}
   105  }
   106  
   107  func (m *Miner) GasPrice() *big.Int {
   108  	return new(big.Int).Set(m.worker.gasPrice)
   109  }
   110  
   111  func (m *Miner) SetGasPrice(price *big.Int) {
   112  	// FIXME block tests set a nil gas price. Quick dirty fix
   113  	if price == nil {
   114  		return
   115  	}
   116  	m.worker.setGasPrice(price)
   117  }
   118  
   119  func (self *Miner) Start(coinbase common.Address, threads int) {
   120  	atomic.StoreInt32(&self.shouldStart, 1)
   121  	self.worker.setEtherbase(coinbase)
   122  	self.coinbase = coinbase
   123  	self.threads = threads
   124  
   125  	if atomic.LoadInt32(&self.canStart) == 0 {
   126  		log.Info(fmt.Sprint("Can not start mining operation due to network sync (starts when finished)"))
   127  		return
   128  	}
   129  	atomic.StoreInt32(&self.mining, 1)
   130  
   131  	for i := 0; i < threads; i++ {
   132  		self.worker.register(NewCpuAgent(i, self.pow))
   133  	}
   134  
   135  	log.Info(fmt.Sprintf("Starting mining operation (CPU=%d TOT=%d)\n", threads, len(self.worker.agents)))
   136  	self.worker.start()
   137  	self.worker.commitNewWork()
   138  }
   139  
   140  func (self *Miner) Stop() {
   141  	self.worker.stop()
   142  	atomic.StoreInt32(&self.mining, 0)
   143  	atomic.StoreInt32(&self.shouldStart, 0)
   144  }
   145  
   146  func (self *Miner) Register(agent Agent) {
   147  	if self.Mining() {
   148  		agent.Start()
   149  	}
   150  	self.worker.register(agent)
   151  }
   152  
   153  func (self *Miner) Unregister(agent Agent) {
   154  	self.worker.unregister(agent)
   155  }
   156  
   157  func (self *Miner) Mining() bool {
   158  	return atomic.LoadInt32(&self.mining) > 0
   159  }
   160  
   161  func (self *Miner) HashRate() (tot int64) {
   162  	tot += int64(self.pow.Hashrate())
   163  	// do we care this might race? is it worth we're rewriting some
   164  	// aspects of the worker/locking up agents so we can get an accurate
   165  	// hashrate?
   166  	for agent := range self.worker.agents {
   167  		if _, ok := agent.(*CpuAgent); !ok {
   168  			tot += agent.GetHashRate()
   169  		}
   170  	}
   171  	return
   172  }
   173  
   174  func (self *Miner) SetExtra(extra []byte) error {
   175  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   176  		return fmt.Errorf("Extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   177  	}
   178  	self.worker.setExtra(extra)
   179  	return nil
   180  }
   181  
   182  // Pending returns the currently pending block and associated state.
   183  func (self *Miner) Pending() (*types.Block, *state.StateDB) {
   184  	return self.worker.pending()
   185  }
   186  
   187  // PendingBlock returns the currently pending block.
   188  //
   189  // Note, to access both the pending block and the pending state
   190  // simultaneously, please use Pending(), as the pending state can
   191  // change between multiple method calls
   192  func (self *Miner) PendingBlock() *types.Block {
   193  	return self.worker.pendingBlock()
   194  }
   195  
   196  func (self *Miner) SetEtherbase(addr common.Address) {
   197  	self.coinbase = addr
   198  	self.worker.setEtherbase(addr)
   199  }