miner.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. // Package miner implements Ethereum block creation and mining.
  17. package miner
  18. import (
  19. "fmt"
  20. "math/big"
  21. "sync/atomic"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. "github.com/ethereum/go-ethereum/common/hexutil"
  25. "github.com/ethereum/go-ethereum/consensus"
  26. "github.com/ethereum/go-ethereum/core"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/eth/downloader"
  30. "github.com/ethereum/go-ethereum/event"
  31. "github.com/ethereum/go-ethereum/log"
  32. "github.com/ethereum/go-ethereum/params"
  33. )
  34. // Backend wraps all methods required for mining.
  35. type Backend interface {
  36. BlockChain() *core.BlockChain
  37. TxPool() *core.TxPool
  38. }
  39. // Config is the configuration parameters of mining.
  40. type Config struct {
  41. Etherbase common.Address `toml:",omitempty"` // Public address for block mining rewards (default = first account)
  42. Notify []string `toml:",omitempty"` // HTTP URL list to be notified of new work packages(only useful in ethash).
  43. ExtraData hexutil.Bytes `toml:",omitempty"` // Block extra data set by the miner
  44. DelayLeftOver time.Duration // Time for broadcast block
  45. GasFloor uint64 // Target gas floor for mined blocks.
  46. GasCeil uint64 // Target gas ceiling for mined blocks.
  47. GasPrice *big.Int // Minimum gas price for mining a transaction
  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. // Miner creates blocks and searches for proof-of-work values.
  52. type Miner struct {
  53. mux *event.TypeMux
  54. worker *worker
  55. coinbase common.Address
  56. eth Backend
  57. engine consensus.Engine
  58. exitCh chan struct{}
  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. func New(eth Backend, config *Config, chainConfig *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, isLocalBlock func(block *types.Block) bool) *Miner {
  63. miner := &Miner{
  64. eth: eth,
  65. mux: mux,
  66. engine: engine,
  67. exitCh: make(chan struct{}),
  68. worker: newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, false),
  69. canStart: 1,
  70. }
  71. go miner.update()
  72. return miner
  73. }
  74. // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
  75. // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
  76. // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
  77. // and halt your mining operation for as long as the DOS continues.
  78. func (miner *Miner) update() {
  79. events := miner.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
  80. defer events.Unsubscribe()
  81. for {
  82. select {
  83. case ev := <-events.Chan():
  84. if ev == nil {
  85. return
  86. }
  87. switch ev.Data.(type) {
  88. case downloader.StartEvent:
  89. atomic.StoreInt32(&miner.canStart, 0)
  90. if miner.Mining() {
  91. miner.Stop()
  92. atomic.StoreInt32(&miner.shouldStart, 1)
  93. log.Info("Mining aborted due to sync")
  94. }
  95. case downloader.DoneEvent, downloader.FailedEvent:
  96. shouldStart := atomic.LoadInt32(&miner.shouldStart) == 1
  97. atomic.StoreInt32(&miner.canStart, 1)
  98. atomic.StoreInt32(&miner.shouldStart, 0)
  99. if shouldStart {
  100. miner.Start(miner.coinbase)
  101. }
  102. // stop immediately and ignore all further pending events
  103. return
  104. }
  105. case <-miner.exitCh:
  106. return
  107. }
  108. }
  109. }
  110. func (miner *Miner) Start(coinbase common.Address) {
  111. atomic.StoreInt32(&miner.shouldStart, 1)
  112. miner.SetEtherbase(coinbase)
  113. if atomic.LoadInt32(&miner.canStart) == 0 {
  114. log.Info("Network syncing, will start miner afterwards")
  115. return
  116. }
  117. miner.worker.start()
  118. }
  119. func (miner *Miner) Stop() {
  120. miner.worker.stop()
  121. atomic.StoreInt32(&miner.shouldStart, 0)
  122. }
  123. func (miner *Miner) Close() {
  124. miner.worker.close()
  125. close(miner.exitCh)
  126. }
  127. func (miner *Miner) Mining() bool {
  128. return miner.worker.isRunning()
  129. }
  130. func (miner *Miner) HashRate() uint64 {
  131. if pow, ok := miner.engine.(consensus.PoW); ok {
  132. return uint64(pow.Hashrate())
  133. }
  134. return 0
  135. }
  136. func (miner *Miner) SetExtra(extra []byte) error {
  137. if uint64(len(extra)) > params.MaximumExtraDataSize {
  138. return fmt.Errorf("extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
  139. }
  140. miner.worker.setExtra(extra)
  141. return nil
  142. }
  143. // SetRecommitInterval sets the interval for sealing work resubmitting.
  144. func (miner *Miner) SetRecommitInterval(interval time.Duration) {
  145. miner.worker.setRecommitInterval(interval)
  146. }
  147. // Pending returns the currently pending block and associated state.
  148. func (miner *Miner) Pending() (*types.Block, *state.StateDB) {
  149. if miner.worker.isRunning() {
  150. return miner.worker.pending()
  151. } else {
  152. // fallback to latest block
  153. block := miner.worker.chain.CurrentBlock()
  154. if block == nil {
  155. return nil, nil
  156. }
  157. stateDb, err := miner.worker.chain.StateAt(block.Root())
  158. if err != nil {
  159. return nil, nil
  160. }
  161. return block, stateDb
  162. }
  163. }
  164. // PendingBlock returns the currently pending block.
  165. //
  166. // Note, to access both the pending block and the pending state
  167. // simultaneously, please use Pending(), as the pending state can
  168. // change between multiple method calls
  169. func (miner *Miner) PendingBlock() *types.Block {
  170. if miner.worker.isRunning() {
  171. return miner.worker.pendingBlock()
  172. } else {
  173. // fallback to latest block
  174. return miner.worker.chain.CurrentBlock()
  175. }
  176. }
  177. func (miner *Miner) SetEtherbase(addr common.Address) {
  178. miner.coinbase = addr
  179. miner.worker.setEtherbase(addr)
  180. }
  181. // SubscribePendingLogs starts delivering logs from pending transactions
  182. // to the given channel.
  183. func (self *Miner) SubscribePendingLogs(ch chan<- []*types.Log) event.Subscription {
  184. return self.worker.pendingLogsFeed.Subscribe(ch)
  185. }