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