miner.go 7.0 KB

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