miner.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/hexutil"
  24. "github.com/ethereum/go-ethereum/consensus"
  25. "github.com/ethereum/go-ethereum/core"
  26. "github.com/ethereum/go-ethereum/core/state"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. "github.com/ethereum/go-ethereum/eth/downloader"
  29. "github.com/ethereum/go-ethereum/event"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/params"
  32. )
  33. // Backend wraps all methods required for mining.
  34. type Backend interface {
  35. BlockChain() *core.BlockChain
  36. TxPool() *core.TxPool
  37. }
  38. // Config is the configuration parameters of mining.
  39. type Config struct {
  40. Etherbase common.Address `toml:",omitempty"` // Public address for block mining rewards (default = first account)
  41. Notify []string `toml:",omitempty"` // HTTP URL list to be notified of new work packages (only useful in ethash).
  42. NotifyFull bool `toml:",omitempty"` // Notify with pending block headers instead of work packages
  43. ExtraData hexutil.Bytes `toml:",omitempty"` // Block extra data set by the miner
  44. GasFloor uint64 // Target gas floor for mined blocks.
  45. GasCeil uint64 // Target gas ceiling for mined blocks.
  46. GasPrice *big.Int // Minimum gas price for mining a transaction
  47. Recommit time.Duration // The time interval for miner to re-create mining work.
  48. Noverify bool // Disable remote mining solution verification(only useful in ethash).
  49. }
  50. // Miner creates blocks and searches for proof-of-work values.
  51. type Miner struct {
  52. mux *event.TypeMux
  53. worker *worker
  54. coinbase common.Address
  55. eth Backend
  56. engine consensus.Engine
  57. exitCh chan struct{}
  58. startCh chan common.Address
  59. stopCh chan struct{}
  60. }
  61. func New(eth Backend, config *Config, chainConfig *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, isLocalBlock func(block *types.Block) bool) *Miner {
  62. miner := &Miner{
  63. eth: eth,
  64. mux: mux,
  65. engine: engine,
  66. exitCh: make(chan struct{}),
  67. startCh: make(chan common.Address),
  68. stopCh: make(chan struct{}),
  69. worker: newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, true),
  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 func() {
  81. if !events.Closed() {
  82. events.Unsubscribe()
  83. }
  84. }()
  85. shouldStart := false
  86. canStart := true
  87. dlEventCh := events.Chan()
  88. for {
  89. select {
  90. case ev := <-dlEventCh:
  91. if ev == nil {
  92. // Unsubscription done, stop listening
  93. dlEventCh = nil
  94. continue
  95. }
  96. switch ev.Data.(type) {
  97. case downloader.StartEvent:
  98. wasMining := miner.Mining()
  99. miner.worker.stop()
  100. canStart = false
  101. if wasMining {
  102. // Resume mining after sync was finished
  103. shouldStart = true
  104. log.Info("Mining aborted due to sync")
  105. }
  106. case downloader.FailedEvent:
  107. canStart = true
  108. if shouldStart {
  109. miner.SetEtherbase(miner.coinbase)
  110. miner.worker.start()
  111. }
  112. case downloader.DoneEvent:
  113. canStart = true
  114. if shouldStart {
  115. miner.SetEtherbase(miner.coinbase)
  116. miner.worker.start()
  117. }
  118. // Stop reacting to downloader events
  119. events.Unsubscribe()
  120. }
  121. case addr := <-miner.startCh:
  122. miner.SetEtherbase(addr)
  123. if canStart {
  124. miner.worker.start()
  125. }
  126. shouldStart = true
  127. case <-miner.stopCh:
  128. shouldStart = false
  129. miner.worker.stop()
  130. case <-miner.exitCh:
  131. miner.worker.close()
  132. return
  133. }
  134. }
  135. }
  136. func (miner *Miner) Start(coinbase common.Address) {
  137. miner.startCh <- coinbase
  138. }
  139. func (miner *Miner) Stop() {
  140. miner.stopCh <- struct{}{}
  141. }
  142. func (miner *Miner) Close() {
  143. close(miner.exitCh)
  144. }
  145. func (miner *Miner) Mining() bool {
  146. return miner.worker.isRunning()
  147. }
  148. func (miner *Miner) Hashrate() uint64 {
  149. if pow, ok := miner.engine.(consensus.PoW); ok {
  150. return uint64(pow.Hashrate())
  151. }
  152. return 0
  153. }
  154. func (miner *Miner) SetExtra(extra []byte) error {
  155. if uint64(len(extra)) > params.MaximumExtraDataSize {
  156. return fmt.Errorf("extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
  157. }
  158. miner.worker.setExtra(extra)
  159. return nil
  160. }
  161. // SetRecommitInterval sets the interval for sealing work resubmitting.
  162. func (miner *Miner) SetRecommitInterval(interval time.Duration) {
  163. miner.worker.setRecommitInterval(interval)
  164. }
  165. // Pending returns the currently pending block and associated state.
  166. func (miner *Miner) Pending() (*types.Block, *state.StateDB) {
  167. return miner.worker.pending()
  168. }
  169. // PendingBlock returns the currently pending block.
  170. //
  171. // Note, to access both the pending block and the pending state
  172. // simultaneously, please use Pending(), as the pending state can
  173. // change between multiple method calls
  174. func (miner *Miner) PendingBlock() *types.Block {
  175. return miner.worker.pendingBlock()
  176. }
  177. func (miner *Miner) SetEtherbase(addr common.Address) {
  178. miner.coinbase = addr
  179. miner.worker.setEtherbase(addr)
  180. }
  181. // EnablePreseal turns on the preseal mining feature. It's enabled by default.
  182. // Note this function shouldn't be exposed to API, it's unnecessary for users
  183. // (miners) to actually know the underlying detail. It's only for outside project
  184. // which uses this library.
  185. func (miner *Miner) EnablePreseal() {
  186. miner.worker.enablePreseal()
  187. }
  188. // DisablePreseal turns off the preseal mining feature. It's necessary for some
  189. // fake consensus engine which can seal blocks instantaneously.
  190. // Note this function shouldn't be exposed to API, it's unnecessary for users
  191. // (miners) to actually know the underlying detail. It's only for outside project
  192. // which uses this library.
  193. func (miner *Miner) DisablePreseal() {
  194. miner.worker.disablePreseal()
  195. }
  196. // SubscribePendingLogs starts delivering logs from pending transactions
  197. // to the given channel.
  198. func (miner *Miner) SubscribePendingLogs(ch chan<- []*types.Log) event.Subscription {
  199. return miner.worker.pendingLogsFeed.Subscribe(ch)
  200. }