github.com/divan/go-ethereum@v1.8.14-0.20180820134928-1de9ada4016d/consensus/ethash/ethash.go (about)

     1  // Copyright 2017 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 ethash implements the ethash proof-of-work consensus engine.
    18  package ethash
    19  
    20  import (
    21  	"errors"
    22  	"fmt"
    23  	"math"
    24  	"math/big"
    25  	"math/rand"
    26  	"os"
    27  	"path/filepath"
    28  	"reflect"
    29  	"runtime"
    30  	"strconv"
    31  	"sync"
    32  	"sync/atomic"
    33  	"time"
    34  	"unsafe"
    35  
    36  	mmap "github.com/edsrzf/mmap-go"
    37  	"github.com/ethereum/go-ethereum/common"
    38  	"github.com/ethereum/go-ethereum/consensus"
    39  	"github.com/ethereum/go-ethereum/core/types"
    40  	"github.com/ethereum/go-ethereum/log"
    41  	"github.com/ethereum/go-ethereum/metrics"
    42  	"github.com/ethereum/go-ethereum/rpc"
    43  	"github.com/hashicorp/golang-lru/simplelru"
    44  )
    45  
    46  var ErrInvalidDumpMagic = errors.New("invalid dump magic")
    47  
    48  var (
    49  	// two256 is a big integer representing 2^256
    50  	two256 = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
    51  
    52  	// sharedEthash is a full instance that can be shared between multiple users.
    53  	sharedEthash = New(Config{"", 3, 0, "", 1, 0, ModeNormal}, nil)
    54  
    55  	// algorithmRevision is the data structure version used for file naming.
    56  	algorithmRevision = 23
    57  
    58  	// dumpMagic is a dataset dump header to sanity check a data dump.
    59  	dumpMagic = []uint32{0xbaddcafe, 0xfee1dead}
    60  )
    61  
    62  // isLittleEndian returns whether the local system is running in little or big
    63  // endian byte order.
    64  func isLittleEndian() bool {
    65  	n := uint32(0x01020304)
    66  	return *(*byte)(unsafe.Pointer(&n)) == 0x04
    67  }
    68  
    69  // memoryMap tries to memory map a file of uint32s for read only access.
    70  func memoryMap(path string) (*os.File, mmap.MMap, []uint32, error) {
    71  	file, err := os.OpenFile(path, os.O_RDONLY, 0644)
    72  	if err != nil {
    73  		return nil, nil, nil, err
    74  	}
    75  	mem, buffer, err := memoryMapFile(file, false)
    76  	if err != nil {
    77  		file.Close()
    78  		return nil, nil, nil, err
    79  	}
    80  	for i, magic := range dumpMagic {
    81  		if buffer[i] != magic {
    82  			mem.Unmap()
    83  			file.Close()
    84  			return nil, nil, nil, ErrInvalidDumpMagic
    85  		}
    86  	}
    87  	return file, mem, buffer[len(dumpMagic):], err
    88  }
    89  
    90  // memoryMapFile tries to memory map an already opened file descriptor.
    91  func memoryMapFile(file *os.File, write bool) (mmap.MMap, []uint32, error) {
    92  	// Try to memory map the file
    93  	flag := mmap.RDONLY
    94  	if write {
    95  		flag = mmap.RDWR
    96  	}
    97  	mem, err := mmap.Map(file, flag, 0)
    98  	if err != nil {
    99  		return nil, nil, err
   100  	}
   101  	// Yay, we managed to memory map the file, here be dragons
   102  	header := *(*reflect.SliceHeader)(unsafe.Pointer(&mem))
   103  	header.Len /= 4
   104  	header.Cap /= 4
   105  
   106  	return mem, *(*[]uint32)(unsafe.Pointer(&header)), nil
   107  }
   108  
   109  // memoryMapAndGenerate tries to memory map a temporary file of uint32s for write
   110  // access, fill it with the data from a generator and then move it into the final
   111  // path requested.
   112  func memoryMapAndGenerate(path string, size uint64, generator func(buffer []uint32)) (*os.File, mmap.MMap, []uint32, error) {
   113  	// Ensure the data folder exists
   114  	if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
   115  		return nil, nil, nil, err
   116  	}
   117  	// Create a huge temporary empty file to fill with data
   118  	temp := path + "." + strconv.Itoa(rand.Int())
   119  
   120  	dump, err := os.Create(temp)
   121  	if err != nil {
   122  		return nil, nil, nil, err
   123  	}
   124  	if err = dump.Truncate(int64(len(dumpMagic))*4 + int64(size)); err != nil {
   125  		return nil, nil, nil, err
   126  	}
   127  	// Memory map the file for writing and fill it with the generator
   128  	mem, buffer, err := memoryMapFile(dump, true)
   129  	if err != nil {
   130  		dump.Close()
   131  		return nil, nil, nil, err
   132  	}
   133  	copy(buffer, dumpMagic)
   134  
   135  	data := buffer[len(dumpMagic):]
   136  	generator(data)
   137  
   138  	if err := mem.Unmap(); err != nil {
   139  		return nil, nil, nil, err
   140  	}
   141  	if err := dump.Close(); err != nil {
   142  		return nil, nil, nil, err
   143  	}
   144  	if err := os.Rename(temp, path); err != nil {
   145  		return nil, nil, nil, err
   146  	}
   147  	return memoryMap(path)
   148  }
   149  
   150  // lru tracks caches or datasets by their last use time, keeping at most N of them.
   151  type lru struct {
   152  	what string
   153  	new  func(epoch uint64) interface{}
   154  	mu   sync.Mutex
   155  	// Items are kept in a LRU cache, but there is a special case:
   156  	// We always keep an item for (highest seen epoch) + 1 as the 'future item'.
   157  	cache      *simplelru.LRU
   158  	future     uint64
   159  	futureItem interface{}
   160  }
   161  
   162  // newlru create a new least-recently-used cache for either the verification caches
   163  // or the mining datasets.
   164  func newlru(what string, maxItems int, new func(epoch uint64) interface{}) *lru {
   165  	if maxItems <= 0 {
   166  		maxItems = 1
   167  	}
   168  	cache, _ := simplelru.NewLRU(maxItems, func(key, value interface{}) {
   169  		log.Trace("Evicted ethash "+what, "epoch", key)
   170  	})
   171  	return &lru{what: what, new: new, cache: cache}
   172  }
   173  
   174  // get retrieves or creates an item for the given epoch. The first return value is always
   175  // non-nil. The second return value is non-nil if lru thinks that an item will be useful in
   176  // the near future.
   177  func (lru *lru) get(epoch uint64) (item, future interface{}) {
   178  	lru.mu.Lock()
   179  	defer lru.mu.Unlock()
   180  
   181  	// Get or create the item for the requested epoch.
   182  	item, ok := lru.cache.Get(epoch)
   183  	if !ok {
   184  		if lru.future > 0 && lru.future == epoch {
   185  			item = lru.futureItem
   186  		} else {
   187  			log.Trace("Requiring new ethash "+lru.what, "epoch", epoch)
   188  			item = lru.new(epoch)
   189  		}
   190  		lru.cache.Add(epoch, item)
   191  	}
   192  	// Update the 'future item' if epoch is larger than previously seen.
   193  	if epoch < maxEpoch-1 && lru.future < epoch+1 {
   194  		log.Trace("Requiring new future ethash "+lru.what, "epoch", epoch+1)
   195  		future = lru.new(epoch + 1)
   196  		lru.future = epoch + 1
   197  		lru.futureItem = future
   198  	}
   199  	return item, future
   200  }
   201  
   202  // cache wraps an ethash cache with some metadata to allow easier concurrent use.
   203  type cache struct {
   204  	epoch uint64    // Epoch for which this cache is relevant
   205  	dump  *os.File  // File descriptor of the memory mapped cache
   206  	mmap  mmap.MMap // Memory map itself to unmap before releasing
   207  	cache []uint32  // The actual cache data content (may be memory mapped)
   208  	once  sync.Once // Ensures the cache is generated only once
   209  }
   210  
   211  // newCache creates a new ethash verification cache and returns it as a plain Go
   212  // interface to be usable in an LRU cache.
   213  func newCache(epoch uint64) interface{} {
   214  	return &cache{epoch: epoch}
   215  }
   216  
   217  // generate ensures that the cache content is generated before use.
   218  func (c *cache) generate(dir string, limit int, test bool) {
   219  	c.once.Do(func() {
   220  		size := cacheSize(c.epoch*epochLength + 1)
   221  		seed := seedHash(c.epoch*epochLength + 1)
   222  		if test {
   223  			size = 1024
   224  		}
   225  		// If we don't store anything on disk, generate and return.
   226  		if dir == "" {
   227  			c.cache = make([]uint32, size/4)
   228  			generateCache(c.cache, c.epoch, seed)
   229  			return
   230  		}
   231  		// Disk storage is needed, this will get fancy
   232  		var endian string
   233  		if !isLittleEndian() {
   234  			endian = ".be"
   235  		}
   236  		path := filepath.Join(dir, fmt.Sprintf("cache-R%d-%x%s", algorithmRevision, seed[:8], endian))
   237  		logger := log.New("epoch", c.epoch)
   238  
   239  		// We're about to mmap the file, ensure that the mapping is cleaned up when the
   240  		// cache becomes unused.
   241  		runtime.SetFinalizer(c, (*cache).finalizer)
   242  
   243  		// Try to load the file from disk and memory map it
   244  		var err error
   245  		c.dump, c.mmap, c.cache, err = memoryMap(path)
   246  		if err == nil {
   247  			logger.Debug("Loaded old ethash cache from disk")
   248  			return
   249  		}
   250  		logger.Debug("Failed to load old ethash cache", "err", err)
   251  
   252  		// No previous cache available, create a new cache file to fill
   253  		c.dump, c.mmap, c.cache, err = memoryMapAndGenerate(path, size, func(buffer []uint32) { generateCache(buffer, c.epoch, seed) })
   254  		if err != nil {
   255  			logger.Error("Failed to generate mapped ethash cache", "err", err)
   256  
   257  			c.cache = make([]uint32, size/4)
   258  			generateCache(c.cache, c.epoch, seed)
   259  		}
   260  		// Iterate over all previous instances and delete old ones
   261  		for ep := int(c.epoch) - limit; ep >= 0; ep-- {
   262  			seed := seedHash(uint64(ep)*epochLength + 1)
   263  			path := filepath.Join(dir, fmt.Sprintf("cache-R%d-%x%s", algorithmRevision, seed[:8], endian))
   264  			os.Remove(path)
   265  		}
   266  	})
   267  }
   268  
   269  // finalizer unmaps the memory and closes the file.
   270  func (c *cache) finalizer() {
   271  	if c.mmap != nil {
   272  		c.mmap.Unmap()
   273  		c.dump.Close()
   274  		c.mmap, c.dump = nil, nil
   275  	}
   276  }
   277  
   278  // dataset wraps an ethash dataset with some metadata to allow easier concurrent use.
   279  type dataset struct {
   280  	epoch   uint64    // Epoch for which this cache is relevant
   281  	dump    *os.File  // File descriptor of the memory mapped cache
   282  	mmap    mmap.MMap // Memory map itself to unmap before releasing
   283  	dataset []uint32  // The actual cache data content
   284  	once    sync.Once // Ensures the cache is generated only once
   285  	done    uint32    // Atomic flag to determine generation status
   286  }
   287  
   288  // newDataset creates a new ethash mining dataset and returns it as a plain Go
   289  // interface to be usable in an LRU cache.
   290  func newDataset(epoch uint64) interface{} {
   291  	return &dataset{epoch: epoch}
   292  }
   293  
   294  // generate ensures that the dataset content is generated before use.
   295  func (d *dataset) generate(dir string, limit int, test bool) {
   296  	d.once.Do(func() {
   297  		// Mark the dataset generated after we're done. This is needed for remote
   298  		defer atomic.StoreUint32(&d.done, 1)
   299  
   300  		csize := cacheSize(d.epoch*epochLength + 1)
   301  		dsize := datasetSize(d.epoch*epochLength + 1)
   302  		seed := seedHash(d.epoch*epochLength + 1)
   303  		if test {
   304  			csize = 1024
   305  			dsize = 32 * 1024
   306  		}
   307  		// If we don't store anything on disk, generate and return
   308  		if dir == "" {
   309  			cache := make([]uint32, csize/4)
   310  			generateCache(cache, d.epoch, seed)
   311  
   312  			d.dataset = make([]uint32, dsize/4)
   313  			generateDataset(d.dataset, d.epoch, cache)
   314  
   315  			return
   316  		}
   317  		// Disk storage is needed, this will get fancy
   318  		var endian string
   319  		if !isLittleEndian() {
   320  			endian = ".be"
   321  		}
   322  		path := filepath.Join(dir, fmt.Sprintf("full-R%d-%x%s", algorithmRevision, seed[:8], endian))
   323  		logger := log.New("epoch", d.epoch)
   324  
   325  		// We're about to mmap the file, ensure that the mapping is cleaned up when the
   326  		// cache becomes unused.
   327  		runtime.SetFinalizer(d, (*dataset).finalizer)
   328  
   329  		// Try to load the file from disk and memory map it
   330  		var err error
   331  		d.dump, d.mmap, d.dataset, err = memoryMap(path)
   332  		if err == nil {
   333  			logger.Debug("Loaded old ethash dataset from disk")
   334  			return
   335  		}
   336  		logger.Debug("Failed to load old ethash dataset", "err", err)
   337  
   338  		// No previous dataset available, create a new dataset file to fill
   339  		cache := make([]uint32, csize/4)
   340  		generateCache(cache, d.epoch, seed)
   341  
   342  		d.dump, d.mmap, d.dataset, err = memoryMapAndGenerate(path, dsize, func(buffer []uint32) { generateDataset(buffer, d.epoch, cache) })
   343  		if err != nil {
   344  			logger.Error("Failed to generate mapped ethash dataset", "err", err)
   345  
   346  			d.dataset = make([]uint32, dsize/2)
   347  			generateDataset(d.dataset, d.epoch, cache)
   348  		}
   349  		// Iterate over all previous instances and delete old ones
   350  		for ep := int(d.epoch) - limit; ep >= 0; ep-- {
   351  			seed := seedHash(uint64(ep)*epochLength + 1)
   352  			path := filepath.Join(dir, fmt.Sprintf("full-R%d-%x%s", algorithmRevision, seed[:8], endian))
   353  			os.Remove(path)
   354  		}
   355  	})
   356  }
   357  
   358  // generated returns whether this particular dataset finished generating already
   359  // or not (it may not have been started at all). This is useful for remote miners
   360  // to default to verification caches instead of blocking on DAG generations.
   361  func (d *dataset) generated() bool {
   362  	return atomic.LoadUint32(&d.done) == 1
   363  }
   364  
   365  // finalizer closes any file handlers and memory maps open.
   366  func (d *dataset) finalizer() {
   367  	if d.mmap != nil {
   368  		d.mmap.Unmap()
   369  		d.dump.Close()
   370  		d.mmap, d.dump = nil, nil
   371  	}
   372  }
   373  
   374  // MakeCache generates a new ethash cache and optionally stores it to disk.
   375  func MakeCache(block uint64, dir string) {
   376  	c := cache{epoch: block / epochLength}
   377  	c.generate(dir, math.MaxInt32, false)
   378  }
   379  
   380  // MakeDataset generates a new ethash dataset and optionally stores it to disk.
   381  func MakeDataset(block uint64, dir string) {
   382  	d := dataset{epoch: block / epochLength}
   383  	d.generate(dir, math.MaxInt32, false)
   384  }
   385  
   386  // Mode defines the type and amount of PoW verification an ethash engine makes.
   387  type Mode uint
   388  
   389  const (
   390  	ModeNormal Mode = iota
   391  	ModeShared
   392  	ModeTest
   393  	ModeFake
   394  	ModeFullFake
   395  )
   396  
   397  // Config are the configuration parameters of the ethash.
   398  type Config struct {
   399  	CacheDir       string
   400  	CachesInMem    int
   401  	CachesOnDisk   int
   402  	DatasetDir     string
   403  	DatasetsInMem  int
   404  	DatasetsOnDisk int
   405  	PowMode        Mode
   406  }
   407  
   408  // mineResult wraps the pow solution parameters for the specified block.
   409  type mineResult struct {
   410  	nonce     types.BlockNonce
   411  	mixDigest common.Hash
   412  	hash      common.Hash
   413  
   414  	errc chan error
   415  }
   416  
   417  // hashrate wraps the hash rate submitted by the remote sealer.
   418  type hashrate struct {
   419  	id   common.Hash
   420  	ping time.Time
   421  	rate uint64
   422  
   423  	done chan struct{}
   424  }
   425  
   426  // sealWork wraps a seal work package for remote sealer.
   427  type sealWork struct {
   428  	errc chan error
   429  	res  chan [3]string
   430  }
   431  
   432  // Ethash is a consensus engine based on proof-of-work implementing the ethash
   433  // algorithm.
   434  type Ethash struct {
   435  	config Config
   436  
   437  	caches   *lru // In memory caches to avoid regenerating too often
   438  	datasets *lru // In memory datasets to avoid regenerating too often
   439  
   440  	// Mining related fields
   441  	rand     *rand.Rand    // Properly seeded random source for nonces
   442  	threads  int           // Number of threads to mine on if mining
   443  	update   chan struct{} // Notification channel to update mining parameters
   444  	hashrate metrics.Meter // Meter tracking the average hashrate
   445  
   446  	// Remote sealer related fields
   447  	workCh       chan *types.Block // Notification channel to push new work to remote sealer
   448  	resultCh     chan *types.Block // Channel used by mining threads to return result
   449  	fetchWorkCh  chan *sealWork    // Channel used for remote sealer to fetch mining work
   450  	submitWorkCh chan *mineResult  // Channel used for remote sealer to submit their mining result
   451  	fetchRateCh  chan chan uint64  // Channel used to gather submitted hash rate for local or remote sealer.
   452  	submitRateCh chan *hashrate    // Channel used for remote sealer to submit their mining hashrate
   453  
   454  	// The fields below are hooks for testing
   455  	shared    *Ethash       // Shared PoW verifier to avoid cache regeneration
   456  	fakeFail  uint64        // Block number which fails PoW check even in fake mode
   457  	fakeDelay time.Duration // Time delay to sleep for before returning from verify
   458  
   459  	lock      sync.Mutex      // Ensures thread safety for the in-memory caches and mining fields
   460  	closeOnce sync.Once       // Ensures exit channel will not be closed twice.
   461  	exitCh    chan chan error // Notification channel to exiting backend threads
   462  }
   463  
   464  // New creates a full sized ethash PoW scheme and starts a background thread for
   465  // remote mining, also optionally notifying a batch of remote services of new work
   466  // packages.
   467  func New(config Config, notify []string) *Ethash {
   468  	if config.CachesInMem <= 0 {
   469  		log.Warn("One ethash cache must always be in memory", "requested", config.CachesInMem)
   470  		config.CachesInMem = 1
   471  	}
   472  	if config.CacheDir != "" && config.CachesOnDisk > 0 {
   473  		log.Info("Disk storage enabled for ethash caches", "dir", config.CacheDir, "count", config.CachesOnDisk)
   474  	}
   475  	if config.DatasetDir != "" && config.DatasetsOnDisk > 0 {
   476  		log.Info("Disk storage enabled for ethash DAGs", "dir", config.DatasetDir, "count", config.DatasetsOnDisk)
   477  	}
   478  	ethash := &Ethash{
   479  		config:       config,
   480  		caches:       newlru("cache", config.CachesInMem, newCache),
   481  		datasets:     newlru("dataset", config.DatasetsInMem, newDataset),
   482  		update:       make(chan struct{}),
   483  		hashrate:     metrics.NewMeter(),
   484  		workCh:       make(chan *types.Block),
   485  		resultCh:     make(chan *types.Block),
   486  		fetchWorkCh:  make(chan *sealWork),
   487  		submitWorkCh: make(chan *mineResult),
   488  		fetchRateCh:  make(chan chan uint64),
   489  		submitRateCh: make(chan *hashrate),
   490  		exitCh:       make(chan chan error),
   491  	}
   492  	go ethash.remote(notify)
   493  	return ethash
   494  }
   495  
   496  // NewTester creates a small sized ethash PoW scheme useful only for testing
   497  // purposes.
   498  func NewTester(notify []string) *Ethash {
   499  	ethash := &Ethash{
   500  		config:       Config{PowMode: ModeTest},
   501  		caches:       newlru("cache", 1, newCache),
   502  		datasets:     newlru("dataset", 1, newDataset),
   503  		update:       make(chan struct{}),
   504  		hashrate:     metrics.NewMeter(),
   505  		workCh:       make(chan *types.Block),
   506  		resultCh:     make(chan *types.Block),
   507  		fetchWorkCh:  make(chan *sealWork),
   508  		submitWorkCh: make(chan *mineResult),
   509  		fetchRateCh:  make(chan chan uint64),
   510  		submitRateCh: make(chan *hashrate),
   511  		exitCh:       make(chan chan error),
   512  	}
   513  	go ethash.remote(notify)
   514  	return ethash
   515  }
   516  
   517  // NewFaker creates a ethash consensus engine with a fake PoW scheme that accepts
   518  // all blocks' seal as valid, though they still have to conform to the Ethereum
   519  // consensus rules.
   520  func NewFaker() *Ethash {
   521  	return &Ethash{
   522  		config: Config{
   523  			PowMode: ModeFake,
   524  		},
   525  	}
   526  }
   527  
   528  // NewFakeFailer creates a ethash consensus engine with a fake PoW scheme that
   529  // accepts all blocks as valid apart from the single one specified, though they
   530  // still have to conform to the Ethereum consensus rules.
   531  func NewFakeFailer(fail uint64) *Ethash {
   532  	return &Ethash{
   533  		config: Config{
   534  			PowMode: ModeFake,
   535  		},
   536  		fakeFail: fail,
   537  	}
   538  }
   539  
   540  // NewFakeDelayer creates a ethash consensus engine with a fake PoW scheme that
   541  // accepts all blocks as valid, but delays verifications by some time, though
   542  // they still have to conform to the Ethereum consensus rules.
   543  func NewFakeDelayer(delay time.Duration) *Ethash {
   544  	return &Ethash{
   545  		config: Config{
   546  			PowMode: ModeFake,
   547  		},
   548  		fakeDelay: delay,
   549  	}
   550  }
   551  
   552  // NewFullFaker creates an ethash consensus engine with a full fake scheme that
   553  // accepts all blocks as valid, without checking any consensus rules whatsoever.
   554  func NewFullFaker() *Ethash {
   555  	return &Ethash{
   556  		config: Config{
   557  			PowMode: ModeFullFake,
   558  		},
   559  	}
   560  }
   561  
   562  // NewShared creates a full sized ethash PoW shared between all requesters running
   563  // in the same process.
   564  func NewShared() *Ethash {
   565  	return &Ethash{shared: sharedEthash}
   566  }
   567  
   568  // Close closes the exit channel to notify all backend threads exiting.
   569  func (ethash *Ethash) Close() error {
   570  	var err error
   571  	ethash.closeOnce.Do(func() {
   572  		// Short circuit if the exit channel is not allocated.
   573  		if ethash.exitCh == nil {
   574  			return
   575  		}
   576  		errc := make(chan error)
   577  		ethash.exitCh <- errc
   578  		err = <-errc
   579  		close(ethash.exitCh)
   580  	})
   581  	return err
   582  }
   583  
   584  // cache tries to retrieve a verification cache for the specified block number
   585  // by first checking against a list of in-memory caches, then against caches
   586  // stored on disk, and finally generating one if none can be found.
   587  func (ethash *Ethash) cache(block uint64) *cache {
   588  	epoch := block / epochLength
   589  	currentI, futureI := ethash.caches.get(epoch)
   590  	current := currentI.(*cache)
   591  
   592  	// Wait for generation finish.
   593  	current.generate(ethash.config.CacheDir, ethash.config.CachesOnDisk, ethash.config.PowMode == ModeTest)
   594  
   595  	// If we need a new future cache, now's a good time to regenerate it.
   596  	if futureI != nil {
   597  		future := futureI.(*cache)
   598  		go future.generate(ethash.config.CacheDir, ethash.config.CachesOnDisk, ethash.config.PowMode == ModeTest)
   599  	}
   600  	return current
   601  }
   602  
   603  // dataset tries to retrieve a mining dataset for the specified block number
   604  // by first checking against a list of in-memory datasets, then against DAGs
   605  // stored on disk, and finally generating one if none can be found.
   606  //
   607  // If async is specified, not only the future but the current DAG is also
   608  // generates on a background thread.
   609  func (ethash *Ethash) dataset(block uint64, async bool) *dataset {
   610  	// Retrieve the requested ethash dataset
   611  	epoch := block / epochLength
   612  	currentI, futureI := ethash.datasets.get(epoch)
   613  	current := currentI.(*dataset)
   614  
   615  	// If async is specified, generate everything in a background thread
   616  	if async && !current.generated() {
   617  		go func() {
   618  			current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.PowMode == ModeTest)
   619  
   620  			if futureI != nil {
   621  				future := futureI.(*dataset)
   622  				future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.PowMode == ModeTest)
   623  			}
   624  		}()
   625  	} else {
   626  		// Either blocking generation was requested, or already done
   627  		current.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.PowMode == ModeTest)
   628  
   629  		if futureI != nil {
   630  			future := futureI.(*dataset)
   631  			go future.generate(ethash.config.DatasetDir, ethash.config.DatasetsOnDisk, ethash.config.PowMode == ModeTest)
   632  		}
   633  	}
   634  	return current
   635  }
   636  
   637  // Threads returns the number of mining threads currently enabled. This doesn't
   638  // necessarily mean that mining is running!
   639  func (ethash *Ethash) Threads() int {
   640  	ethash.lock.Lock()
   641  	defer ethash.lock.Unlock()
   642  
   643  	return ethash.threads
   644  }
   645  
   646  // SetThreads updates the number of mining threads currently enabled. Calling
   647  // this method does not start mining, only sets the thread count. If zero is
   648  // specified, the miner will use all cores of the machine. Setting a thread
   649  // count below zero is allowed and will cause the miner to idle, without any
   650  // work being done.
   651  func (ethash *Ethash) SetThreads(threads int) {
   652  	ethash.lock.Lock()
   653  	defer ethash.lock.Unlock()
   654  
   655  	// If we're running a shared PoW, set the thread count on that instead
   656  	if ethash.shared != nil {
   657  		ethash.shared.SetThreads(threads)
   658  		return
   659  	}
   660  	// Update the threads and ping any running seal to pull in any changes
   661  	ethash.threads = threads
   662  	select {
   663  	case ethash.update <- struct{}{}:
   664  	default:
   665  	}
   666  }
   667  
   668  // Hashrate implements PoW, returning the measured rate of the search invocations
   669  // per second over the last minute.
   670  // Note the returned hashrate includes local hashrate, but also includes the total
   671  // hashrate of all remote miner.
   672  func (ethash *Ethash) Hashrate() float64 {
   673  	// Short circuit if we are run the ethash in normal/test mode.
   674  	if ethash.config.PowMode != ModeNormal && ethash.config.PowMode != ModeTest {
   675  		return ethash.hashrate.Rate1()
   676  	}
   677  	var res = make(chan uint64, 1)
   678  
   679  	select {
   680  	case ethash.fetchRateCh <- res:
   681  	case <-ethash.exitCh:
   682  		// Return local hashrate only if ethash is stopped.
   683  		return ethash.hashrate.Rate1()
   684  	}
   685  
   686  	// Gather total submitted hash rate of remote sealers.
   687  	return ethash.hashrate.Rate1() + float64(<-res)
   688  }
   689  
   690  // APIs implements consensus.Engine, returning the user facing RPC APIs.
   691  func (ethash *Ethash) APIs(chain consensus.ChainReader) []rpc.API {
   692  	// In order to ensure backward compatibility, we exposes ethash RPC APIs
   693  	// to both eth and ethash namespaces.
   694  	return []rpc.API{
   695  		{
   696  			Namespace: "eth",
   697  			Version:   "1.0",
   698  			Service:   &API{ethash},
   699  			Public:    true,
   700  		},
   701  		{
   702  			Namespace: "ethash",
   703  			Version:   "1.0",
   704  			Service:   &API{ethash},
   705  			Public:    true,
   706  		},
   707  	}
   708  }
   709  
   710  // SeedHash is the seed to use for generating a verification cache and the mining
   711  // dataset.
   712  func SeedHash(block uint64) []byte {
   713  	return seedHash(block)
   714  }