miner.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. 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. startCh chan common.Address
  60. stopCh chan struct{}
  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. startCh: make(chan common.Address),
  69. stopCh: make(chan struct{}),
  70. worker: newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, false),
  71. }
  72. go miner.update()
  73. return miner
  74. }
  75. // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
  76. // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
  77. // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
  78. // and halt your mining operation for as long as the DOS continues.
  79. func (miner *Miner) update() {
  80. events := miner.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
  81. defer func() {
  82. if !events.Closed() {
  83. events.Unsubscribe()
  84. }
  85. }()
  86. shouldStart := false
  87. canStart := true
  88. dlEventCh := events.Chan()
  89. for {
  90. select {
  91. case ev := <-dlEventCh:
  92. if ev == nil {
  93. // Unsubscription done, stop listening
  94. dlEventCh = nil
  95. continue
  96. }
  97. switch ev.Data.(type) {
  98. case downloader.StartEvent:
  99. wasMining := miner.Mining()
  100. miner.worker.stop()
  101. canStart = false
  102. if wasMining {
  103. // Resume mining after sync was finished
  104. shouldStart = true
  105. log.Info("Mining aborted due to sync")
  106. }
  107. case downloader.FailedEvent:
  108. canStart = true
  109. if shouldStart {
  110. miner.SetEtherbase(miner.coinbase)
  111. miner.worker.start()
  112. }
  113. case downloader.DoneEvent:
  114. canStart = true
  115. if shouldStart {
  116. miner.SetEtherbase(miner.coinbase)
  117. miner.worker.start()
  118. }
  119. // Stop reacting to downloader events
  120. events.Unsubscribe()
  121. }
  122. case addr := <-miner.startCh:
  123. miner.SetEtherbase(addr)
  124. if canStart {
  125. miner.worker.start()
  126. }
  127. shouldStart = true
  128. case <-miner.stopCh:
  129. shouldStart = false
  130. miner.worker.stop()
  131. case <-miner.exitCh:
  132. miner.worker.close()
  133. return
  134. }
  135. }
  136. }
  137. func (miner *Miner) Start(coinbase common.Address) {
  138. miner.startCh <- coinbase
  139. }
  140. func (miner *Miner) Stop() {
  141. miner.stopCh <- struct{}{}
  142. }
  143. func (miner *Miner) Close() {
  144. close(miner.exitCh)
  145. }
  146. func (miner *Miner) Mining() bool {
  147. return miner.worker.isRunning()
  148. }
  149. func (miner *Miner) Hashrate() uint64 {
  150. if pow, ok := miner.engine.(consensus.PoW); ok {
  151. return uint64(pow.Hashrate())
  152. }
  153. return 0
  154. }
  155. func (miner *Miner) SetExtra(extra []byte) error {
  156. if uint64(len(extra)) > params.MaximumExtraDataSize {
  157. return fmt.Errorf("extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
  158. }
  159. miner.worker.setExtra(extra)
  160. return nil
  161. }
  162. // SetRecommitInterval sets the interval for sealing work resubmitting.
  163. func (miner *Miner) SetRecommitInterval(interval time.Duration) {
  164. miner.worker.setRecommitInterval(interval)
  165. }
  166. // Pending returns the currently pending block and associated state.
  167. func (miner *Miner) Pending() (*types.Block, *state.StateDB) {
  168. if miner.worker.isRunning() {
  169. pendingBlock, pendingState := miner.worker.pending()
  170. if pendingState != nil && pendingBlock != nil {
  171. return pendingBlock, pendingState
  172. }
  173. }
  174. // fallback to latest block
  175. block := miner.worker.chain.CurrentBlock()
  176. if block == nil {
  177. return nil, nil
  178. }
  179. stateDb, err := miner.worker.chain.StateAt(block.Root())
  180. if err != nil {
  181. return nil, nil
  182. }
  183. return block, stateDb
  184. }
  185. // PendingBlock returns the currently pending block.
  186. //
  187. // Note, to access both the pending block and the pending state
  188. // simultaneously, please use Pending(), as the pending state can
  189. // change between multiple method calls
  190. func (miner *Miner) PendingBlock() *types.Block {
  191. if miner.worker.isRunning() {
  192. pendingBlock := miner.worker.pendingBlock()
  193. if pendingBlock != nil {
  194. return pendingBlock
  195. }
  196. }
  197. // fallback to latest block
  198. return miner.worker.chain.CurrentBlock()
  199. }
  200. func (miner *Miner) SetEtherbase(addr common.Address) {
  201. miner.coinbase = addr
  202. miner.worker.setEtherbase(addr)
  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. // DisablePreseal turns off the preseal mining feature. It's necessary for some
  212. // fake consensus engine which can seal blocks instantaneously.
  213. // Note this function shouldn't be exposed to API, it's unnecessary for users
  214. // (miners) to actually know the underlying detail. It's only for outside project
  215. // which uses this library.
  216. func (miner *Miner) DisablePreseal() {
  217. miner.worker.disablePreseal()
  218. }
  219. // SubscribePendingLogs starts delivering logs from pending transactions
  220. // to the given channel.
  221. func (miner *Miner) SubscribePendingLogs(ch chan<- []*types.Log) event.Subscription {
  222. return miner.worker.pendingLogsFeed.Subscribe(ch)
  223. }