sealer.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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
  17. import (
  18. crand "crypto/rand"
  19. "math"
  20. "math/big"
  21. "math/rand"
  22. "runtime"
  23. "sync"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/consensus"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/log"
  28. )
  29. // Seal implements consensus.Engine, attempting to find a nonce that satisfies
  30. // the block's difficulty requirements.
  31. func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
  32. // If we're running a fake PoW, simply return a 0 nonce immediately
  33. if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
  34. header := block.Header()
  35. header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{}
  36. return block.WithSeal(header), nil
  37. }
  38. // If we're running a shared PoW, delegate sealing to it
  39. if ethash.shared != nil {
  40. return ethash.shared.Seal(chain, block, stop)
  41. }
  42. // Create a runner and the multiple search threads it directs
  43. abort := make(chan struct{})
  44. found := make(chan *types.Block)
  45. ethash.lock.Lock()
  46. threads := ethash.threads
  47. if ethash.rand == nil {
  48. seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
  49. if err != nil {
  50. ethash.lock.Unlock()
  51. return nil, err
  52. }
  53. ethash.rand = rand.New(rand.NewSource(seed.Int64()))
  54. }
  55. ethash.lock.Unlock()
  56. if threads == 0 {
  57. threads = runtime.NumCPU()
  58. }
  59. if threads < 0 {
  60. threads = 0 // Allows disabling local mining without extra logic around local/remote
  61. }
  62. var pend sync.WaitGroup
  63. for i := 0; i < threads; i++ {
  64. pend.Add(1)
  65. go func(id int, nonce uint64) {
  66. defer pend.Done()
  67. ethash.mine(block, id, nonce, abort, found)
  68. }(i, uint64(ethash.rand.Int63()))
  69. }
  70. // Wait until sealing is terminated or a nonce is found
  71. var result *types.Block
  72. select {
  73. case <-stop:
  74. // Outside abort, stop all miner threads
  75. close(abort)
  76. case result = <-found:
  77. // One of the threads found a block, abort all others
  78. close(abort)
  79. case <-ethash.update:
  80. // Thread count was changed on user request, restart
  81. close(abort)
  82. pend.Wait()
  83. return ethash.Seal(chain, block, stop)
  84. }
  85. // Wait for all miners to terminate and return the block
  86. pend.Wait()
  87. return result, nil
  88. }
  89. // mine is the actual proof-of-work miner that searches for a nonce starting from
  90. // seed that results in correct final block difficulty.
  91. func (ethash *Ethash) mine(block *types.Block, id int, seed uint64, abort chan struct{}, found chan *types.Block) {
  92. // Extract some data from the header
  93. var (
  94. header = block.Header()
  95. hash = header.HashNoNonce().Bytes()
  96. target = new(big.Int).Div(maxUint256, header.Difficulty)
  97. number = header.Number.Uint64()
  98. dataset = ethash.dataset(number)
  99. )
  100. // Start generating random nonces until we abort or find a good one
  101. var (
  102. attempts = int64(0)
  103. nonce = seed
  104. )
  105. logger := log.New("miner", id)
  106. logger.Trace("Started ethash search for new nonces", "seed", seed)
  107. search:
  108. for {
  109. select {
  110. case <-abort:
  111. // Mining terminated, update stats and abort
  112. logger.Trace("Ethash nonce search aborted", "attempts", nonce-seed)
  113. ethash.hashrate.Mark(attempts)
  114. break search
  115. default:
  116. // We don't have to update hash rate on every nonce, so update after after 2^X nonces
  117. attempts++
  118. if (attempts % (1 << 15)) == 0 {
  119. ethash.hashrate.Mark(attempts)
  120. attempts = 0
  121. }
  122. // Compute the PoW value of this nonce
  123. digest, result := hashimotoFull(dataset.dataset, hash, nonce)
  124. if new(big.Int).SetBytes(result).Cmp(target) <= 0 {
  125. // Correct nonce found, create a new header with it
  126. header = types.CopyHeader(header)
  127. header.Nonce = types.EncodeNonce(nonce)
  128. header.MixDigest = common.BytesToHash(digest)
  129. // Seal and return a block (if still needed)
  130. select {
  131. case found <- block.WithSeal(header):
  132. logger.Trace("Ethash nonce found and reported", "attempts", nonce-seed, "nonce", nonce)
  133. case <-abort:
  134. logger.Trace("Ethash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
  135. }
  136. break search
  137. }
  138. nonce++
  139. }
  140. }
  141. // Datasets are unmapped in a finalizer. Ensure that the dataset stays live
  142. // during sealing so it's not unmapped while being read.
  143. runtime.KeepAlive(dataset)
  144. }