github.com/xfond/eth-implementation@v1.8.9-0.20180514135602-f6bc65fc6811/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.SetEtherbase(coinbase)
   109  
   110  	if atomic.LoadInt32(&self.canStart) == 0 {
   111  		log.Info("Network syncing, will start miner afterwards")
   112  		return
   113  	}
   114  	atomic.StoreInt32(&self.mining, 1)
   115  
   116  	log.Info("Starting mining operation")
   117  	self.worker.start()
   118  	self.worker.commitNewWork()
   119  }
   120  
   121  func (self *Miner) Stop() {
   122  	self.worker.stop()
   123  	atomic.StoreInt32(&self.mining, 0)
   124  	atomic.StoreInt32(&self.shouldStart, 0)
   125  }
   126  
   127  func (self *Miner) Register(agent Agent) {
   128  	if self.Mining() {
   129  		agent.Start()
   130  	}
   131  	self.worker.register(agent)
   132  }
   133  
   134  func (self *Miner) Unregister(agent Agent) {
   135  	self.worker.unregister(agent)
   136  }
   137  
   138  func (self *Miner) Mining() bool {
   139  	return atomic.LoadInt32(&self.mining) > 0
   140  }
   141  
   142  func (self *Miner) HashRate() (tot int64) {
   143  	if pow, ok := self.engine.(consensus.PoW); ok {
   144  		tot += int64(pow.Hashrate())
   145  	}
   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  		if _, ok := agent.(*CpuAgent); !ok {
   151  			tot += agent.GetHashRate()
   152  		}
   153  	}
   154  	return
   155  }
   156  
   157  func (self *Miner) SetExtra(extra []byte) error {
   158  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   159  		return fmt.Errorf("Extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   160  	}
   161  	self.worker.setExtra(extra)
   162  	return nil
   163  }
   164  
   165  // Pending returns the currently pending block and associated state.
   166  func (self *Miner) Pending() (*types.Block, *state.StateDB) {
   167  	return self.worker.pending()
   168  }
   169  
   170  // PendingBlock returns the currently pending block.
   171  //
   172  // Note, to access both the pending block and the pending state
   173  // simultaneously, please use Pending(), as the pending state can
   174  // change between multiple method calls
   175  func (self *Miner) PendingBlock() *types.Block {
   176  	return self.worker.pendingBlock()
   177  }
   178  
   179  func (self *Miner) SetEtherbase(addr common.Address) {
   180  	self.coinbase = addr
   181  	self.worker.setEtherbase(addr)
   182  }