github.com/phillinzzz/newBsc@v1.1.6/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 "time" 24 25 "github.com/phillinzzz/newBsc/common" 26 "github.com/phillinzzz/newBsc/common/hexutil" 27 "github.com/phillinzzz/newBsc/consensus" 28 "github.com/phillinzzz/newBsc/core" 29 "github.com/phillinzzz/newBsc/core/state" 30 "github.com/phillinzzz/newBsc/core/types" 31 "github.com/phillinzzz/newBsc/eth/downloader" 32 "github.com/phillinzzz/newBsc/event" 33 "github.com/phillinzzz/newBsc/log" 34 "github.com/phillinzzz/newBsc/params" 35 ) 36 37 // Backend wraps all methods required for mining. 38 type Backend interface { 39 BlockChain() *core.BlockChain 40 TxPool() *core.TxPool 41 } 42 43 // Config is the configuration parameters of mining. 44 type Config struct { 45 Etherbase common.Address `toml:",omitempty"` // Public address for block mining rewards (default = first account) 46 Notify []string `toml:",omitempty"` // HTTP URL list to be notified of new work packages (only useful in ethash). 47 NotifyFull bool `toml:",omitempty"` // Notify with pending block headers instead of work packages 48 ExtraData hexutil.Bytes `toml:",omitempty"` // Block extra data set by the miner 49 DelayLeftOver time.Duration // Time for broadcast block 50 GasFloor uint64 // Target gas floor for mined blocks. 51 GasCeil uint64 // Target gas ceiling for mined blocks. 52 GasPrice *big.Int // Minimum gas price for mining a transaction 53 Recommit time.Duration // The time interval for miner to re-create mining work. 54 Noverify bool // Disable remote mining solution verification(only useful in ethash). 55 } 56 57 // Miner creates blocks and searches for proof-of-work values. 58 type Miner struct { 59 mux *event.TypeMux 60 worker *worker 61 coinbase common.Address 62 eth Backend 63 engine consensus.Engine 64 exitCh chan struct{} 65 startCh chan common.Address 66 stopCh chan struct{} 67 } 68 69 func New(eth Backend, config *Config, chainConfig *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, isLocalBlock func(block *types.Block) bool) *Miner { 70 miner := &Miner{ 71 eth: eth, 72 mux: mux, 73 engine: engine, 74 exitCh: make(chan struct{}), 75 startCh: make(chan common.Address), 76 stopCh: make(chan struct{}), 77 worker: newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, false), 78 } 79 go miner.update() 80 81 return miner 82 } 83 84 // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop. 85 // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and 86 // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks 87 // and halt your mining operation for as long as the DOS continues. 88 func (miner *Miner) update() { 89 events := miner.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{}) 90 defer func() { 91 if !events.Closed() { 92 events.Unsubscribe() 93 } 94 }() 95 96 shouldStart := false 97 canStart := true 98 dlEventCh := events.Chan() 99 for { 100 select { 101 case ev := <-dlEventCh: 102 if ev == nil { 103 // Unsubscription done, stop listening 104 dlEventCh = nil 105 continue 106 } 107 switch ev.Data.(type) { 108 case downloader.StartEvent: 109 wasMining := miner.Mining() 110 miner.worker.stop() 111 canStart = false 112 if wasMining { 113 // Resume mining after sync was finished 114 shouldStart = true 115 log.Info("Mining aborted due to sync") 116 } 117 case downloader.FailedEvent: 118 canStart = true 119 if shouldStart { 120 miner.SetEtherbase(miner.coinbase) 121 miner.worker.start() 122 } 123 case downloader.DoneEvent: 124 canStart = true 125 if shouldStart { 126 miner.SetEtherbase(miner.coinbase) 127 miner.worker.start() 128 } 129 // Stop reacting to downloader events 130 events.Unsubscribe() 131 } 132 case addr := <-miner.startCh: 133 miner.SetEtherbase(addr) 134 if canStart { 135 miner.worker.start() 136 } 137 shouldStart = true 138 case <-miner.stopCh: 139 shouldStart = false 140 miner.worker.stop() 141 case <-miner.exitCh: 142 miner.worker.close() 143 return 144 } 145 } 146 } 147 148 func (miner *Miner) Start(coinbase common.Address) { 149 miner.startCh <- coinbase 150 } 151 152 func (miner *Miner) Stop() { 153 miner.stopCh <- struct{}{} 154 } 155 156 func (miner *Miner) Close() { 157 close(miner.exitCh) 158 } 159 160 func (miner *Miner) Mining() bool { 161 return miner.worker.isRunning() 162 } 163 164 func (miner *Miner) Hashrate() uint64 { 165 if pow, ok := miner.engine.(consensus.PoW); ok { 166 return uint64(pow.Hashrate()) 167 } 168 return 0 169 } 170 171 func (miner *Miner) SetExtra(extra []byte) error { 172 if uint64(len(extra)) > params.MaximumExtraDataSize { 173 return fmt.Errorf("extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize) 174 } 175 miner.worker.setExtra(extra) 176 return nil 177 } 178 179 // SetRecommitInterval sets the interval for sealing work resubmitting. 180 func (miner *Miner) SetRecommitInterval(interval time.Duration) { 181 miner.worker.setRecommitInterval(interval) 182 } 183 184 // Pending returns the currently pending block and associated state. 185 func (miner *Miner) Pending() (*types.Block, *state.StateDB) { 186 if miner.worker.isRunning() { 187 pendingBlock, pendingState := miner.worker.pending() 188 if pendingState != nil && pendingBlock != nil { 189 return pendingBlock, pendingState 190 } 191 } 192 // fallback to latest block 193 block := miner.worker.chain.CurrentBlock() 194 if block == nil { 195 return nil, nil 196 } 197 stateDb, err := miner.worker.chain.StateAt(block.Root()) 198 if err != nil { 199 return nil, nil 200 } 201 return block, stateDb 202 } 203 204 // PendingBlock returns the currently pending block. 205 // 206 // Note, to access both the pending block and the pending state 207 // simultaneously, please use Pending(), as the pending state can 208 // change between multiple method calls 209 func (miner *Miner) PendingBlock() *types.Block { 210 if miner.worker.isRunning() { 211 pendingBlock := miner.worker.pendingBlock() 212 if pendingBlock != nil { 213 return pendingBlock 214 } 215 } 216 // fallback to latest block 217 return miner.worker.chain.CurrentBlock() 218 } 219 220 func (miner *Miner) SetEtherbase(addr common.Address) { 221 miner.coinbase = addr 222 miner.worker.setEtherbase(addr) 223 } 224 225 // EnablePreseal turns on the preseal mining feature. It's enabled by default. 226 // Note this function shouldn't be exposed to API, it's unnecessary for users 227 // (miners) to actually know the underlying detail. It's only for outside project 228 // which uses this library. 229 func (miner *Miner) EnablePreseal() { 230 miner.worker.enablePreseal() 231 } 232 233 // DisablePreseal turns off the preseal mining feature. It's necessary for some 234 // fake consensus engine which can seal blocks instantaneously. 235 // Note this function shouldn't be exposed to API, it's unnecessary for users 236 // (miners) to actually know the underlying detail. It's only for outside project 237 // which uses this library. 238 func (miner *Miner) DisablePreseal() { 239 miner.worker.disablePreseal() 240 } 241 242 // SubscribePendingLogs starts delivering logs from pending transactions 243 // to the given channel. 244 func (miner *Miner) SubscribePendingLogs(ch chan<- []*types.Log) event.Subscription { 245 return miner.worker.pendingLogsFeed.Subscribe(ch) 246 }