github.com/calmw/ethereum@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/calmw/ethereum/common"
    27  	"github.com/calmw/ethereum/common/hexutil"
    28  	"github.com/calmw/ethereum/consensus"
    29  	"github.com/calmw/ethereum/core"
    30  	"github.com/calmw/ethereum/core/state"
    31  	"github.com/calmw/ethereum/core/txpool"
    32  	"github.com/calmw/ethereum/core/types"
    33  	"github.com/calmw/ethereum/eth/downloader"
    34  	"github.com/calmw/ethereum/event"
    35  	"github.com/calmw/ethereum/log"
    36  	"github.com/calmw/ethereum/params"
    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  			case downloader.FailedEvent:
   135  				canStart = true
   136  				if shouldStart {
   137  					miner.worker.start()
   138  				}
   139  			case downloader.DoneEvent:
   140  				canStart = true
   141  				if shouldStart {
   142  					miner.worker.start()
   143  				}
   144  				// Stop reacting to downloader events
   145  				events.Unsubscribe()
   146  			}
   147  		case <-miner.startCh:
   148  			if canStart {
   149  				miner.worker.start()
   150  			}
   151  			shouldStart = true
   152  		case <-miner.stopCh:
   153  			shouldStart = false
   154  			miner.worker.stop()
   155  		case <-miner.exitCh:
   156  			miner.worker.close()
   157  			return
   158  		}
   159  	}
   160  }
   161  
   162  func (miner *Miner) Start() {
   163  	miner.startCh <- struct{}{}
   164  }
   165  
   166  func (miner *Miner) Stop() {
   167  	miner.stopCh <- struct{}{}
   168  }
   169  
   170  func (miner *Miner) Close() {
   171  	close(miner.exitCh)
   172  	miner.wg.Wait()
   173  }
   174  
   175  func (miner *Miner) Mining() bool {
   176  	return miner.worker.isRunning()
   177  }
   178  
   179  func (miner *Miner) Hashrate() uint64 {
   180  	if pow, ok := miner.engine.(consensus.PoW); ok {
   181  		return uint64(pow.Hashrate())
   182  	}
   183  	return 0
   184  }
   185  
   186  func (miner *Miner) SetExtra(extra []byte) error {
   187  	if uint64(len(extra)) > params.MaximumExtraDataSize {
   188  		return fmt.Errorf("extra exceeds max length. %d > %v", len(extra), params.MaximumExtraDataSize)
   189  	}
   190  	miner.worker.setExtra(extra)
   191  	return nil
   192  }
   193  
   194  // SetRecommitInterval sets the interval for sealing work resubmitting.
   195  func (miner *Miner) SetRecommitInterval(interval time.Duration) {
   196  	miner.worker.setRecommitInterval(interval)
   197  }
   198  
   199  // Pending returns the currently pending block and associated state.
   200  func (miner *Miner) Pending() (*types.Block, *state.StateDB) {
   201  	return miner.worker.pending()
   202  }
   203  
   204  // PendingBlock returns the currently pending block.
   205  //
   206  // Note, to access both the pending block and the pending state
   207  // simultaneously, please use Pending(), as the pending state can
   208  // change between multiple method calls
   209  func (miner *Miner) PendingBlock() *types.Block {
   210  	return miner.worker.pendingBlock()
   211  }
   212  
   213  // PendingBlockAndReceipts returns the currently pending block and corresponding receipts.
   214  func (miner *Miner) PendingBlockAndReceipts() (*types.Block, types.Receipts) {
   215  	return miner.worker.pendingBlockAndReceipts()
   216  }
   217  
   218  func (miner *Miner) SetEtherbase(addr common.Address) {
   219  	miner.worker.setEtherbase(addr)
   220  }
   221  
   222  // SetGasCeil sets the gaslimit to strive for when mining blocks post 1559.
   223  // For pre-1559 blocks, it sets the ceiling.
   224  func (miner *Miner) SetGasCeil(ceil uint64) {
   225  	miner.worker.setGasCeil(ceil)
   226  }
   227  
   228  // EnablePreseal turns on the preseal mining feature. It's enabled by default.
   229  // Note this function shouldn't be exposed to API, it's unnecessary for users
   230  // (miners) to actually know the underlying detail. It's only for outside project
   231  // which uses this library.
   232  func (miner *Miner) EnablePreseal() {
   233  	miner.worker.enablePreseal()
   234  }
   235  
   236  // DisablePreseal turns off the preseal mining feature. It's necessary for some
   237  // fake consensus engine which can seal blocks instantaneously.
   238  // Note this function shouldn't be exposed to API, it's unnecessary for users
   239  // (miners) to actually know the underlying detail. It's only for outside project
   240  // which uses this library.
   241  func (miner *Miner) DisablePreseal() {
   242  	miner.worker.disablePreseal()
   243  }
   244  
   245  // SubscribePendingLogs starts delivering logs from pending transactions
   246  // to the given channel.
   247  func (miner *Miner) SubscribePendingLogs(ch chan<- []*types.Log) event.Subscription {
   248  	return miner.worker.pendingLogsFeed.Subscribe(ch)
   249  }
   250  
   251  // BuildPayload builds the payload according to the provided parameters.
   252  func (miner *Miner) BuildPayload(args *BuildPayloadArgs) (*Payload, error) {
   253  	return miner.worker.buildPayload(args)
   254  }