gitee.com/liu-zhao234568/cntest@v1.0.0/miner/miner.go (about)

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