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