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