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