github.com/jeffallen/go-ethereum@v1.1.4-0.20150910155051-571d3236c49c/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/common"
    26  	"github.com/ethereum/go-ethereum/core"
    27  	"github.com/ethereum/go-ethereum/core/state"
    28  	"github.com/ethereum/go-ethereum/core/types"
    29  	"github.com/ethereum/go-ethereum/eth/downloader"
    30  	"github.com/ethereum/go-ethereum/event"
    31  	"github.com/ethereum/go-ethereum/logger"
    32  	"github.com/ethereum/go-ethereum/logger/glog"
    33  	"github.com/ethereum/go-ethereum/params"
    34  	"github.com/ethereum/go-ethereum/pow"
    35  )
    36  
    37  type Miner struct {
    38  	mux *event.TypeMux
    39  
    40  	worker *worker
    41  
    42  	MinAcceptedGasPrice *big.Int
    43  
    44  	threads  int
    45  	coinbase common.Address
    46  	mining   int32
    47  	eth      core.Backend
    48  	pow      pow.PoW
    49  
    50  	canStart    int32 // can start indicates whether we can start the mining operation
    51  	shouldStart int32 // should start indicates whether we should start after sync
    52  }
    53  
    54  func New(eth core.Backend, mux *event.TypeMux, pow pow.PoW) *Miner {
    55  	miner := &Miner{eth: eth, mux: mux, pow: pow, worker: newWorker(common.Address{}, eth), canStart: 1}
    56  	go miner.update()
    57  
    58  	return miner
    59  }
    60  
    61  // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
    62  // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
    63  // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
    64  // and halt your mining operation for as long as the DOS continues.
    65  func (self *Miner) update() {
    66  	events := self.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
    67  out:
    68  	for ev := range events.Chan() {
    69  		switch ev.(type) {
    70  		case downloader.StartEvent:
    71  			atomic.StoreInt32(&self.canStart, 0)
    72  			if self.Mining() {
    73  				self.Stop()
    74  				atomic.StoreInt32(&self.shouldStart, 1)
    75  				glog.V(logger.Info).Infoln("Mining operation aborted due to sync operation")
    76  			}
    77  		case downloader.DoneEvent, downloader.FailedEvent:
    78  			shouldStart := atomic.LoadInt32(&self.shouldStart) == 1
    79  
    80  			atomic.StoreInt32(&self.canStart, 1)
    81  			atomic.StoreInt32(&self.shouldStart, 0)
    82  			if shouldStart {
    83  				self.Start(self.coinbase, self.threads)
    84  			}
    85  			// unsubscribe. we're only interested in this event once
    86  			events.Unsubscribe()
    87  			// stop immediately and ignore all further pending events
    88  			break out
    89  		}
    90  	}
    91  }
    92  
    93  func (m *Miner) SetGasPrice(price *big.Int) {
    94  	// FIXME block tests set a nil gas price. Quick dirty fix
    95  	if price == nil {
    96  		return
    97  	}
    98  
    99  	m.worker.setGasPrice(price)
   100  }
   101  
   102  func (self *Miner) Start(coinbase common.Address, threads int) {
   103  	atomic.StoreInt32(&self.shouldStart, 1)
   104  	self.threads = threads
   105  	self.worker.coinbase = coinbase
   106  	self.coinbase = coinbase
   107  
   108  	if atomic.LoadInt32(&self.canStart) == 0 {
   109  		glog.V(logger.Info).Infoln("Can not start mining operation due to network sync (starts when finished)")
   110  		return
   111  	}
   112  
   113  	atomic.StoreInt32(&self.mining, 1)
   114  
   115  	for i := 0; i < threads; i++ {
   116  		self.worker.register(NewCpuAgent(i, self.pow))
   117  	}
   118  
   119  	glog.V(logger.Info).Infof("Starting mining operation (CPU=%d TOT=%d)\n", threads, len(self.worker.agents))
   120  
   121  	self.worker.start()
   122  
   123  	self.worker.commitNewWork()
   124  }
   125  
   126  func (self *Miner) Stop() {
   127  	self.worker.stop()
   128  	atomic.StoreInt32(&self.mining, 0)
   129  	atomic.StoreInt32(&self.shouldStart, 0)
   130  }
   131  
   132  func (self *Miner) Register(agent Agent) {
   133  	if self.Mining() {
   134  		agent.Start()
   135  	}
   136  
   137  	self.worker.register(agent)
   138  }
   139  
   140  func (self *Miner) Mining() bool {
   141  	return atomic.LoadInt32(&self.mining) > 0
   142  }
   143  
   144  func (self *Miner) HashRate() (tot int64) {
   145  	tot += self.pow.GetHashrate()
   146  	// do we care this might race? is it worth we're rewriting some
   147  	// aspects of the worker/locking up agents so we can get an accurate
   148  	// hashrate?
   149  	for _, agent := range self.worker.agents {
   150  		tot += agent.GetHashRate()
   151  	}
   152  	return
   153  }
   154  
   155  func (self *Miner) SetExtra(extra []byte) error {
   156  	if uint64(len(extra)) > params.MaximumExtraDataSize.Uint64() {
   157  		return fmt.Errorf("Extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   158  	}
   159  
   160  	self.worker.extra = extra
   161  	return nil
   162  }
   163  
   164  func (self *Miner) PendingState() *state.StateDB {
   165  	return self.worker.pendingState()
   166  }
   167  
   168  func (self *Miner) PendingBlock() *types.Block {
   169  	return self.worker.pendingBlock()
   170  }
   171  
   172  func (self *Miner) SetEtherbase(addr common.Address) {
   173  	self.coinbase = addr
   174  	self.worker.setEtherbase(addr)
   175  }