github.com/aidoskuneen/adk-node@v0.0.0-20220315131952-2e32567cb7f4/consensus/ethash/ethash.go (about)

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