miner.go 7.3 KB

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