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