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