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