ethash.go 22 KB

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