github.com/daefrom/go-dae@v1.0.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/daefrom/go-dae/common"
    27  	"github.com/daefrom/go-dae/common/hexutil"
    28  	"github.com/daefrom/go-dae/consensus"
    29  	"github.com/daefrom/go-dae/core"
    30  	"github.com/daefrom/go-dae/core/state"
    31  	"github.com/daefrom/go-dae/core/types"
    32  	"github.com/daefrom/go-dae/eth/downloader"
    33  	"github.com/daefrom/go-dae/event"
    34  	"github.com/daefrom/go-dae/log"
    35  	"github.com/daefrom/go-dae/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  	GasFloor   uint64         // Target gas floor for mined blocks.
    52  	GasCeil    uint64         // Target gas ceiling for mined blocks.
    53  	GasPrice   *big.Int       // Minimum gas price for mining a transaction
    54  	Recommit   time.Duration  // The time interval for miner to re-create mining work.
    55  	Noverify   bool           // Disable remote mining solution verification(only useful in ethash).
    56  }
    57  
    58  // Miner creates blocks and searches for proof-of-work values.
    59  type Miner struct {
    60  	mux      *event.TypeMux
    61  	worker   *worker
    62  	coinbase common.Address
    63  	eth      Backend
    64  	engine   consensus.Engine
    65  	exitCh   chan struct{}
    66  	startCh  chan common.Address
    67  	stopCh   chan struct{}
    68  
    69  	wg sync.WaitGroup
    70  }
    71  
    72  func New(eth Backend, config *Config, chainConfig *params.ChainConfig, mux *event.TypeMux, engine consensus.Engine, isLocalBlock func(header *types.Header) bool) *Miner {
    73  	miner := &Miner{
    74  		eth:     eth,
    75  		mux:     mux,
    76  		engine:  engine,
    77  		exitCh:  make(chan struct{}),
    78  		startCh: make(chan common.Address),
    79  		stopCh:  make(chan struct{}),
    80  		worker:  newWorker(config, chainConfig, engine, eth, mux, isLocalBlock, true),
    81  	}
    82  	miner.wg.Add(1)
    83  	go miner.update()
    84  	return miner
    85  }
    86  
    87  // update keeps track of the downloader events. Please be aware that this is a one shot type of update loop.
    88  // It's entered once and as soon as `Done` or `Failed` has been broadcasted the events are unregistered and
    89  // the loop is exited. This to prevent a major security vuln where external parties can DOS you with blocks
    90  // and halt your mining operation for as long as the DOS continues.
    91  func (miner *Miner) update() {
    92  	defer miner.wg.Done()
    93  
    94  	events := miner.mux.Subscribe(downloader.StartEvent{}, downloader.DoneEvent{}, downloader.FailedEvent{})
    95  	defer func() {
    96  		if !events.Closed() {
    97  			events.Unsubscribe()
    98  		}
    99  	}()
   100  
   101  	shouldStart := false
   102  	canStart := true
   103  	dlEventCh := events.Chan()
   104  	for {
   105  		select {
   106  		case ev := <-dlEventCh:
   107  			if ev == nil {
   108  				// Unsubscription done, stop listening
   109  				dlEventCh = nil
   110  				continue
   111  			}
   112  			switch ev.Data.(type) {
   113  			case downloader.StartEvent:
   114  				wasMining := miner.Mining()
   115  				miner.worker.stop()
   116  				canStart = false
   117  				if wasMining {
   118  					// Resume mining after sync was finished
   119  					shouldStart = true
   120  					log.Info("Mining aborted due to sync")
   121  				}
   122  			case downloader.FailedEvent:
   123  				canStart = true
   124  				if shouldStart {
   125  					miner.SetEtherbase(miner.coinbase)
   126  					miner.worker.start()
   127  				}
   128  			case downloader.DoneEvent:
   129  				canStart = true
   130  				if shouldStart {
   131  					miner.SetEtherbase(miner.coinbase)
   132  					miner.worker.start()
   133  				}
   134  				// Stop reacting to downloader events
   135  				events.Unsubscribe()
   136  			}
   137  		case addr := <-miner.startCh:
   138  			miner.SetEtherbase(addr)
   139  			if canStart {
   140  				miner.worker.start()
   141  			}
   142  			shouldStart = true
   143  		case <-miner.stopCh:
   144  			shouldStart = false
   145  			miner.worker.stop()
   146  		case <-miner.exitCh:
   147  			miner.worker.close()
   148  			return
   149  		}
   150  	}
   151  }
   152  
   153  func (miner *Miner) Start(coinbase common.Address) {
   154  	miner.startCh <- coinbase
   155  }
   156  
   157  func (miner *Miner) Stop() {
   158  	miner.stopCh <- struct{}{}
   159  }
   160  
   161  func (miner *Miner) Close() {
   162  	close(miner.exitCh)
   163  	miner.wg.Wait()
   164  }
   165  
   166  func (miner *Miner) Mining() bool {
   167  	return miner.worker.isRunning()
   168  }
   169  
   170  func (miner *Miner) Hashrate() uint64 {
   171  	if pow, ok := miner.engine.(consensus.PoW); ok {
   172  		return uint64(pow.Hashrate())
   173  	}
   174  	return 0
   175  }
   176  
   177  func (miner *Miner) SetExtra(extra []byte) error {
   178  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   179  		return fmt.Errorf("extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   180  	}
   181  	miner.worker.setExtra(extra)
   182  	return nil
   183  }
   184  
   185  // SetRecommitInterval sets the interval for sealing work resubmitting.
   186  func (miner *Miner) SetRecommitInterval(interval time.Duration) {
   187  	miner.worker.setRecommitInterval(interval)
   188  }
   189  
   190  // Pending returns the currently pending block and associated state.
   191  func (miner *Miner) Pending() (*types.Block, *state.StateDB) {
   192  	return miner.worker.pending()
   193  }
   194  
   195  // PendingBlock returns the currently pending block.
   196  //
   197  // Note, to access both the pending block and the pending state
   198  // simultaneously, please use Pending(), as the pending state can
   199  // change between multiple method calls
   200  func (miner *Miner) PendingBlock() *types.Block {
   201  	return miner.worker.pendingBlock()
   202  }
   203  
   204  // PendingBlockAndReceipts returns the currently pending block and corresponding receipts.
   205  func (miner *Miner) PendingBlockAndReceipts() (*types.Block, types.Receipts) {
   206  	return miner.worker.pendingBlockAndReceipts()
   207  }
   208  
   209  func (miner *Miner) SetEtherbase(addr common.Address) {
   210  	miner.coinbase = addr
   211  	miner.worker.setEtherbase(addr)
   212  }
   213  
   214  // SetGasCeil sets the gaslimit to strive for when mining blocks post 1559.
   215  // For pre-1559 blocks, it sets the ceiling.
   216  func (miner *Miner) SetGasCeil(ceil uint64) {
   217  	miner.worker.setGasCeil(ceil)
   218  }
   219  
   220  // EnablePreseal turns on the preseal mining feature. It's enabled by default.
   221  // Note this function shouldn't be exposed to API, it's unnecessary for users
   222  // (miners) to actually know the underlying detail. It's only for outside project
   223  // which uses this library.
   224  func (miner *Miner) EnablePreseal() {
   225  	miner.worker.enablePreseal()
   226  }
   227  
   228  // DisablePreseal turns off the preseal mining feature. It's necessary for some
   229  // fake consensus engine which can seal blocks instantaneously.
   230  // Note this function shouldn't be exposed to API, it's unnecessary for users
   231  // (miners) to actually know the underlying detail. It's only for outside project
   232  // which uses this library.
   233  func (miner *Miner) DisablePreseal() {
   234  	miner.worker.disablePreseal()
   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  // GetSealingBlockAsync requests to generate a sealing block according to the
   244  // given parameters. Regardless of whether the generation is successful or not,
   245  // there is always a result that will be returned through the result channel.
   246  // The difference is that if the execution fails, the returned result is nil
   247  // and the concrete error is dropped silently.
   248  func (miner *Miner) GetSealingBlockAsync(parent common.Hash, timestamp uint64, coinbase common.Address, random common.Hash, noTxs bool) (chan *types.Block, error) {
   249  	resCh, _, err := miner.worker.getSealingBlock(parent, timestamp, coinbase, random, noTxs)
   250  	if err != nil {
   251  		return nil, err
   252  	}
   253  	return resCh, nil
   254  }
   255  
   256  // GetSealingBlockSync creates a sealing block according to the given parameters.
   257  // If the generation is failed or the underlying work is already closed, an error
   258  // will be returned.
   259  func (miner *Miner) GetSealingBlockSync(parent common.Hash, timestamp uint64, coinbase common.Address, random common.Hash, noTxs bool) (*types.Block, error) {
   260  	resCh, errCh, err := miner.worker.getSealingBlock(parent, timestamp, coinbase, random, noTxs)
   261  	if err != nil {
   262  		return nil, err
   263  	}
   264  	return <-resCh, <-errCh
   265  }