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