ethash.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 pow
  17. import (
  18. "bufio"
  19. "bytes"
  20. "errors"
  21. "fmt"
  22. "io/ioutil"
  23. "math"
  24. "math/big"
  25. "math/rand"
  26. "os"
  27. "path/filepath"
  28. "sync"
  29. "time"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/common/hexutil"
  32. "github.com/ethereum/go-ethereum/log"
  33. metrics "github.com/rcrowley/go-metrics"
  34. )
  35. var (
  36. ErrNonceOutOfRange = errors.New("nonce out of range")
  37. ErrInvalidDifficulty = errors.New("non-positive difficulty")
  38. ErrInvalidMixDigest = errors.New("invalid mix digest")
  39. ErrInvalidPoW = errors.New("pow difficulty invalid")
  40. )
  41. var (
  42. // maxUint256 is a big integer representing 2^256-1
  43. maxUint256 = new(big.Int).Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
  44. // sharedEthash is a full instance that can be shared between multiple users.
  45. sharedEthash = NewFullEthash("", 3, 0, "", 1, 0)
  46. // algorithmRevision is the data structure version used for file naming.
  47. algorithmRevision = 23
  48. // dumpMagic is a dataset dump header to sanity check a data dump.
  49. dumpMagic = hexutil.MustDecode("0xfee1deadbaddcafe")
  50. )
  51. // cache wraps an ethash cache with some metadata to allow easier concurrent use.
  52. type cache struct {
  53. epoch uint64 // Epoch for which this cache is relevant
  54. cache []uint32 // The actual cache data content
  55. used time.Time // Timestamp of the last use for smarter eviction
  56. once sync.Once // Ensures the cache is generated only once
  57. lock sync.Mutex // Ensures thread safety for updating the usage time
  58. }
  59. // generate ensures that the cache content is generated before use.
  60. func (c *cache) generate(dir string, limit int, test bool) {
  61. c.once.Do(func() {
  62. // If we have a testing cache, generate and return
  63. if test {
  64. rawCache := generateCache(1024, seedHash(c.epoch*epochLength+1))
  65. c.cache = prepare(1024, bytes.NewReader(rawCache))
  66. return
  67. }
  68. // Full cache generation is needed, check cache dir for existing data
  69. size := cacheSize(c.epoch*epochLength + 1)
  70. seed := seedHash(c.epoch*epochLength + 1)
  71. path := filepath.Join(dir, fmt.Sprintf("cache-R%d-%x", algorithmRevision, seed))
  72. logger := log.New("seed", hexutil.Bytes(seed))
  73. if dir != "" {
  74. dump, err := os.Open(path)
  75. if err == nil {
  76. logger.Info("Loading ethash cache from disk")
  77. start := time.Now()
  78. c.cache = prepare(size, bufio.NewReader(dump))
  79. logger.Info("Loaded ethash cache from disk", "elapsed", common.PrettyDuration(time.Since(start)))
  80. dump.Close()
  81. return
  82. }
  83. }
  84. // No previous disk cache was available, generate on the fly
  85. rawCache := generateCache(size, seed)
  86. c.cache = prepare(size, bytes.NewReader(rawCache))
  87. // If a cache directory is given, attempt to serialize for next time
  88. if dir != "" {
  89. // Store the ethash cache to disk
  90. start := time.Now()
  91. if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
  92. logger.Error("Failed to create ethash cache dir", "err", err)
  93. } else if err := ioutil.WriteFile(path, rawCache, os.ModePerm); err != nil {
  94. logger.Error("Failed to write ethash cache to disk", "err", err)
  95. } else {
  96. logger.Info("Stored ethash cache to disk", "elapsed", common.PrettyDuration(time.Since(start)))
  97. }
  98. // Iterate over all previous instances and delete old ones
  99. for ep := int(c.epoch) - limit; ep >= 0; ep-- {
  100. seed := seedHash(uint64(ep)*epochLength + 1)
  101. path := filepath.Join(dir, fmt.Sprintf("cache-R%d-%x", algorithmRevision, seed))
  102. os.Remove(path)
  103. }
  104. }
  105. })
  106. }
  107. // dataset wraps an ethash dataset with some metadata to allow easier concurrent use.
  108. type dataset struct {
  109. epoch uint64 // Epoch for which this cache is relevant
  110. dataset []uint32 // The actual cache data content
  111. used time.Time // Timestamp of the last use for smarter eviction
  112. once sync.Once // Ensures the cache is generated only once
  113. lock sync.Mutex // Ensures thread safety for updating the usage time
  114. }
  115. // generate ensures that the dataset content is generated before use.
  116. func (d *dataset) generate(dir string, limit int, test bool, discard bool) {
  117. d.once.Do(func() {
  118. // If we have a testing dataset, generate and return
  119. if test {
  120. rawCache := generateCache(1024, seedHash(d.epoch*epochLength+1))
  121. intCache := prepare(1024, bytes.NewReader(rawCache))
  122. rawDataset := generateDataset(32*1024, intCache)
  123. d.dataset = prepare(32*1024, bytes.NewReader(rawDataset))
  124. return
  125. }
  126. // Full dataset generation is needed, check dataset dir for existing data
  127. csize := cacheSize(d.epoch*epochLength + 1)
  128. dsize := datasetSize(d.epoch*epochLength + 1)
  129. seed := seedHash(d.epoch*epochLength + 1)
  130. path := filepath.Join(dir, fmt.Sprintf("full-R%d-%x", algorithmRevision, seed))
  131. logger := log.New("seed", hexutil.Bytes(seed))
  132. if dir != "" {
  133. dump, err := os.Open(path)
  134. if err == nil {
  135. if !discard {
  136. logger.Info("Loading ethash DAG from disk")
  137. start := time.Now()
  138. d.dataset = prepare(dsize, bufio.NewReader(dump))
  139. logger.Info("Loaded ethash DAG from disk", "elapsed", common.PrettyDuration(time.Since(start)))
  140. }
  141. dump.Close()
  142. return
  143. }
  144. }
  145. // No previous disk dataset was available, generate on the fly
  146. rawCache := generateCache(csize, seed)
  147. intCache := prepare(csize, bytes.NewReader(rawCache))
  148. rawDataset := generateDataset(dsize, intCache)
  149. if !discard {
  150. d.dataset = prepare(dsize, bytes.NewReader(rawDataset))
  151. }
  152. // If a dataset directory is given, attempt to serialize for next time
  153. if dir != "" {
  154. // Store the ethash dataset to disk
  155. start := time.Now()
  156. if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
  157. logger.Error("Failed to create ethash DAG dir", "err", err)
  158. } else if err := ioutil.WriteFile(path, rawDataset, os.ModePerm); err != nil {
  159. logger.Error("Failed to write ethash DAG to disk", "err", err)
  160. } else {
  161. logger.Info("Stored ethash DAG to disk", "elapsed", common.PrettyDuration(time.Since(start)))
  162. }
  163. // Iterate over all previous instances and delete old ones
  164. for ep := int(d.epoch) - limit; ep >= 0; ep-- {
  165. seed := seedHash(uint64(ep)*epochLength + 1)
  166. path := filepath.Join(dir, fmt.Sprintf("full-R%d-%x", algorithmRevision, seed))
  167. os.Remove(path)
  168. }
  169. }
  170. })
  171. }
  172. // MakeCache generates a new ethash cache and optionally stores it to disk.
  173. func MakeCache(block uint64, dir string) {
  174. c := cache{epoch: block/epochLength + 1}
  175. c.generate(dir, math.MaxInt32, false)
  176. }
  177. // MakeDataset generates a new ethash dataset and optionally stores it to disk.
  178. func MakeDataset(block uint64, dir string) {
  179. d := dataset{epoch: block/epochLength + 1}
  180. d.generate(dir, math.MaxInt32, false, true)
  181. }
  182. // Ethash is a PoW data struture implementing the ethash algorithm.
  183. type Ethash struct {
  184. cachedir string // Data directory to store the verification caches
  185. cachesinmem int // Number of caches to keep in memory
  186. cachesondisk int // Number of caches to keep on disk
  187. dagdir string // Data directory to store full mining datasets
  188. dagsinmem int // Number of mining datasets to keep in memory
  189. dagsondisk int // Number of mining datasets to keep on disk
  190. caches map[uint64]*cache // In memory caches to avoid regenerating too often
  191. fcache *cache // Pre-generated cache for the estimated future epoch
  192. datasets map[uint64]*dataset // In memory datasets to avoid regenerating too often
  193. fdataset *dataset // Pre-generated dataset for the estimated future epoch
  194. lock sync.Mutex // Ensures thread safety for the in-memory caches
  195. hashrate metrics.Meter // Meter tracking the average hashrate
  196. tester bool // Flag whether to use a smaller test dataset
  197. }
  198. // NewFullEthash creates a full sized ethash PoW scheme.
  199. func NewFullEthash(cachedir string, cachesinmem, cachesondisk int, dagdir string, dagsinmem, dagsondisk int) PoW {
  200. if cachesinmem <= 0 {
  201. log.Warn("One ethash cache must alwast be in memory", "requested", cachesinmem)
  202. cachesinmem = 1
  203. }
  204. if cachedir != "" && cachesondisk > 0 {
  205. log.Info("Disk storage enabled for ethash caches", "dir", cachedir, "count", cachesondisk)
  206. }
  207. if dagdir != "" && dagsondisk > 0 {
  208. log.Info("Disk storage enabled for ethash DAGs", "dir", dagdir, "count", dagsondisk)
  209. }
  210. return &Ethash{
  211. cachedir: cachedir,
  212. cachesinmem: cachesinmem,
  213. cachesondisk: cachesondisk,
  214. dagdir: dagdir,
  215. dagsinmem: dagsinmem,
  216. dagsondisk: dagsondisk,
  217. caches: make(map[uint64]*cache),
  218. datasets: make(map[uint64]*dataset),
  219. hashrate: metrics.NewMeter(),
  220. }
  221. }
  222. // NewTestEthash creates a small sized ethash PoW scheme useful only for testing
  223. // purposes.
  224. func NewTestEthash() PoW {
  225. return &Ethash{
  226. cachesinmem: 1,
  227. caches: make(map[uint64]*cache),
  228. datasets: make(map[uint64]*dataset),
  229. tester: true,
  230. hashrate: metrics.NewMeter(),
  231. }
  232. }
  233. // NewSharedEthash creates a full sized ethash PoW shared between all requesters
  234. // running in the same process.
  235. func NewSharedEthash() PoW {
  236. return sharedEthash
  237. }
  238. // Verify implements PoW, checking whether the given block satisfies the PoW
  239. // difficulty requirements.
  240. func (ethash *Ethash) Verify(block Block) error {
  241. // Sanity check that the block number is below the lookup table size (60M blocks)
  242. number := block.NumberU64()
  243. if number/epochLength >= uint64(len(cacheSizes)) {
  244. // Go < 1.7 cannot calculate new cache/dataset sizes (no fast prime check)
  245. return ErrNonceOutOfRange
  246. }
  247. // Ensure that we have a valid difficulty for the block
  248. difficulty := block.Difficulty()
  249. if difficulty.Sign() <= 0 {
  250. return ErrInvalidDifficulty
  251. }
  252. // Recompute the digest and PoW value and verify against the block
  253. cache := ethash.cache(number)
  254. size := datasetSize(number)
  255. if ethash.tester {
  256. size = 32 * 1024
  257. }
  258. digest, result := hashimotoLight(size, cache, block.HashNoNonce().Bytes(), block.Nonce())
  259. if !bytes.Equal(block.MixDigest().Bytes(), digest) {
  260. return ErrInvalidMixDigest
  261. }
  262. target := new(big.Int).Div(maxUint256, difficulty)
  263. if new(big.Int).SetBytes(result).Cmp(target) > 0 {
  264. return ErrInvalidPoW
  265. }
  266. return nil
  267. }
  268. // cache tries to retrieve a verification cache for the specified block number
  269. // by first checking against a list of in-memory caches, then against caches
  270. // stored on disk, and finally generating one if none can be found.
  271. func (ethash *Ethash) cache(block uint64) []uint32 {
  272. epoch := block / epochLength
  273. // If we have a PoW for that epoch, use that
  274. ethash.lock.Lock()
  275. current, future := ethash.caches[epoch], (*cache)(nil)
  276. if current == nil {
  277. // No in-memory cache, evict the oldest if the cache limit was reached
  278. for len(ethash.caches) >= ethash.cachesinmem {
  279. var evict *cache
  280. for _, cache := range ethash.caches {
  281. if evict == nil || evict.used.After(cache.used) {
  282. evict = cache
  283. }
  284. }
  285. delete(ethash.caches, evict.epoch)
  286. log.Debug("Evicted ethash cache", "epoch", evict.epoch, "used", evict.used)
  287. }
  288. // If we have the new cache pre-generated, use that, otherwise create a new one
  289. if ethash.fcache != nil && ethash.fcache.epoch == epoch {
  290. log.Debug("Using pre-generated cache", "epoch", epoch)
  291. current, ethash.fcache = ethash.fcache, nil
  292. } else {
  293. log.Debug("Requiring new ethash cache", "epoch", epoch)
  294. current = &cache{epoch: epoch}
  295. }
  296. ethash.caches[epoch] = current
  297. // If we just used up the future cache, or need a refresh, regenerate
  298. if ethash.fcache == nil || ethash.fcache.epoch <= epoch {
  299. log.Debug("Requiring new future ethash cache", "epoch", epoch+1)
  300. future = &cache{epoch: epoch + 1}
  301. ethash.fcache = future
  302. }
  303. }
  304. current.used = time.Now()
  305. ethash.lock.Unlock()
  306. // Wait for generation finish, bump the timestamp and finalize the cache
  307. current.generate(ethash.cachedir, ethash.cachesondisk, ethash.tester)
  308. current.lock.Lock()
  309. current.used = time.Now()
  310. current.lock.Unlock()
  311. // If we exhausted the future cache, now's a good time to regenerate it
  312. if future != nil {
  313. go future.generate(ethash.cachedir, ethash.cachesondisk, ethash.tester)
  314. }
  315. return current.cache
  316. }
  317. // Search implements PoW, attempting to find a nonce that satisfies the block's
  318. // difficulty requirements.
  319. func (ethash *Ethash) Search(block Block, stop <-chan struct{}) (uint64, []byte) {
  320. // Extract some data from the block
  321. var (
  322. hash = block.HashNoNonce().Bytes()
  323. diff = block.Difficulty()
  324. target = new(big.Int).Div(maxUint256, diff)
  325. )
  326. // Retrieve the mining dataset
  327. dataset, size := ethash.dataset(block.NumberU64()), datasetSize(block.NumberU64())
  328. // Start generating random nonces until we abort or find a good one
  329. var (
  330. attempts int64
  331. rand = rand.New(rand.NewSource(time.Now().UnixNano()))
  332. nonce = uint64(rand.Int63())
  333. )
  334. for {
  335. select {
  336. case <-stop:
  337. // Mining terminated, update stats and abort
  338. ethash.hashrate.Mark(attempts)
  339. return 0, nil
  340. default:
  341. // We don't have to update hash rate on every nonce, so update after after 2^X nonces
  342. attempts++
  343. if (attempts % (1 << 15)) == 0 {
  344. ethash.hashrate.Mark(attempts)
  345. attempts = 0
  346. }
  347. // Compute the PoW value of this nonce
  348. digest, result := hashimotoFull(size, dataset, hash, nonce)
  349. if new(big.Int).SetBytes(result).Cmp(target) <= 0 {
  350. return nonce, digest
  351. }
  352. nonce++
  353. }
  354. }
  355. }
  356. // dataset tries to retrieve a mining dataset for the specified block number
  357. // by first checking against a list of in-memory datasets, then against DAGs
  358. // stored on disk, and finally generating one if none can be found.
  359. func (ethash *Ethash) dataset(block uint64) []uint32 {
  360. epoch := block / epochLength
  361. // If we have a PoW for that epoch, use that
  362. ethash.lock.Lock()
  363. current, future := ethash.datasets[epoch], (*dataset)(nil)
  364. if current == nil {
  365. // No in-memory dataset, evict the oldest if the dataset limit was reached
  366. for len(ethash.datasets) >= ethash.dagsinmem {
  367. var evict *dataset
  368. for _, dataset := range ethash.datasets {
  369. if evict == nil || evict.used.After(dataset.used) {
  370. evict = dataset
  371. }
  372. }
  373. delete(ethash.datasets, evict.epoch)
  374. log.Debug("Evicted ethash dataset", "epoch", evict.epoch, "used", evict.used)
  375. }
  376. // If we have the new cache pre-generated, use that, otherwise create a new one
  377. if ethash.fdataset != nil && ethash.fdataset.epoch == epoch {
  378. log.Debug("Using pre-generated dataset", "epoch", epoch)
  379. current = &dataset{epoch: ethash.fdataset.epoch} // Reload from disk
  380. ethash.fdataset = nil
  381. } else {
  382. log.Debug("Requiring new ethash dataset", "epoch", epoch)
  383. current = &dataset{epoch: epoch}
  384. }
  385. ethash.datasets[epoch] = current
  386. // If we just used up the future dataset, or need a refresh, regenerate
  387. if ethash.fdataset == nil || ethash.fdataset.epoch <= epoch {
  388. log.Debug("Requiring new future ethash dataset", "epoch", epoch+1)
  389. future = &dataset{epoch: epoch + 1}
  390. ethash.fdataset = future
  391. }
  392. }
  393. current.used = time.Now()
  394. ethash.lock.Unlock()
  395. // Wait for generation finish, bump the timestamp and finalize the cache
  396. current.generate(ethash.dagdir, ethash.dagsondisk, ethash.tester, false)
  397. current.lock.Lock()
  398. current.used = time.Now()
  399. current.lock.Unlock()
  400. // If we exhausted the future dataset, now's a good time to regenerate it
  401. if future != nil {
  402. go future.generate(ethash.dagdir, ethash.dagsondisk, ethash.tester, true) // Discard results from memorys
  403. }
  404. return current.dataset
  405. }
  406. // Hashrate implements PoW, returning the measured rate of the search invocations
  407. // per second over the last minute.
  408. func (ethash *Ethash) Hashrate() float64 {
  409. return ethash.hashrate.Rate1()
  410. }
  411. // EthashSeedHash is the seed to use for generating a vrification cache and the
  412. // mining dataset.
  413. func EthashSeedHash(block uint64) []byte {
  414. return seedHash(block)
  415. }