sealer.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. "errors"
  20. "math"
  21. "math/big"
  22. "math/rand"
  23. "runtime"
  24. "sync"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/consensus"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/log"
  30. )
  31. var (
  32. errNoMiningWork = errors.New("no mining work available yet")
  33. errInvalidSealResult = errors.New("invalid or stale proof-of-work solution")
  34. )
  35. // Seal implements consensus.Engine, attempting to find a nonce that satisfies
  36. // the block's difficulty requirements.
  37. func (ethash *Ethash) Seal(chain consensus.ChainReader, block *types.Block, stop <-chan struct{}) (*types.Block, error) {
  38. // If we're running a fake PoW, simply return a 0 nonce immediately
  39. if ethash.config.PowMode == ModeFake || ethash.config.PowMode == ModeFullFake {
  40. header := block.Header()
  41. header.Nonce, header.MixDigest = types.BlockNonce{}, common.Hash{}
  42. return block.WithSeal(header), nil
  43. }
  44. // If we're running a shared PoW, delegate sealing to it
  45. if ethash.shared != nil {
  46. return ethash.shared.Seal(chain, block, stop)
  47. }
  48. // Create a runner and the multiple search threads it directs
  49. abort := make(chan struct{})
  50. ethash.lock.Lock()
  51. threads := ethash.threads
  52. if ethash.rand == nil {
  53. seed, err := crand.Int(crand.Reader, big.NewInt(math.MaxInt64))
  54. if err != nil {
  55. ethash.lock.Unlock()
  56. return nil, err
  57. }
  58. ethash.rand = rand.New(rand.NewSource(seed.Int64()))
  59. }
  60. ethash.lock.Unlock()
  61. if threads == 0 {
  62. threads = runtime.NumCPU()
  63. }
  64. if threads < 0 {
  65. threads = 0 // Allows disabling local mining without extra logic around local/remote
  66. }
  67. // Push new work to remote sealer
  68. if ethash.workCh != nil {
  69. ethash.workCh <- block
  70. }
  71. var pend sync.WaitGroup
  72. for i := 0; i < threads; i++ {
  73. pend.Add(1)
  74. go func(id int, nonce uint64) {
  75. defer pend.Done()
  76. ethash.mine(block, id, nonce, abort, ethash.resultCh)
  77. }(i, uint64(ethash.rand.Int63()))
  78. }
  79. // Wait until sealing is terminated or a nonce is found
  80. var result *types.Block
  81. select {
  82. case <-stop:
  83. // Outside abort, stop all miner threads
  84. close(abort)
  85. case result = <-ethash.resultCh:
  86. // One of the threads found a block, abort all others
  87. close(abort)
  88. case <-ethash.update:
  89. // Thread count was changed on user request, restart
  90. close(abort)
  91. pend.Wait()
  92. return ethash.Seal(chain, block, stop)
  93. }
  94. // Wait for all miners to terminate and return the block
  95. pend.Wait()
  96. return result, nil
  97. }
  98. // mine is the actual proof-of-work miner that searches for a nonce starting from
  99. // seed that results in correct final block difficulty.
  100. func (ethash *Ethash) mine(block *types.Block, id int, seed uint64, abort chan struct{}, found chan *types.Block) {
  101. // Extract some data from the header
  102. var (
  103. header = block.Header()
  104. hash = header.HashNoNonce().Bytes()
  105. target = new(big.Int).Div(maxUint256, header.Difficulty)
  106. number = header.Number.Uint64()
  107. dataset = ethash.dataset(number)
  108. )
  109. // Start generating random nonces until we abort or find a good one
  110. var (
  111. attempts = int64(0)
  112. nonce = seed
  113. )
  114. logger := log.New("miner", id)
  115. logger.Trace("Started ethash search for new nonces", "seed", seed)
  116. search:
  117. for {
  118. select {
  119. case <-abort:
  120. // Mining terminated, update stats and abort
  121. logger.Trace("Ethash nonce search aborted", "attempts", nonce-seed)
  122. ethash.hashrate.Mark(attempts)
  123. break search
  124. default:
  125. // We don't have to update hash rate on every nonce, so update after after 2^X nonces
  126. attempts++
  127. if (attempts % (1 << 15)) == 0 {
  128. ethash.hashrate.Mark(attempts)
  129. attempts = 0
  130. }
  131. // Compute the PoW value of this nonce
  132. digest, result := hashimotoFull(dataset.dataset, hash, nonce)
  133. if new(big.Int).SetBytes(result).Cmp(target) <= 0 {
  134. // Correct nonce found, create a new header with it
  135. header = types.CopyHeader(header)
  136. header.Nonce = types.EncodeNonce(nonce)
  137. header.MixDigest = common.BytesToHash(digest)
  138. // Seal and return a block (if still needed)
  139. select {
  140. case found <- block.WithSeal(header):
  141. logger.Trace("Ethash nonce found and reported", "attempts", nonce-seed, "nonce", nonce)
  142. case <-abort:
  143. logger.Trace("Ethash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
  144. }
  145. break search
  146. }
  147. nonce++
  148. }
  149. }
  150. // Datasets are unmapped in a finalizer. Ensure that the dataset stays live
  151. // during sealing so it's not unmapped while being read.
  152. runtime.KeepAlive(dataset)
  153. }
  154. // remote starts a standalone goroutine to handle remote mining related stuff.
  155. func (ethash *Ethash) remote() {
  156. var (
  157. works = make(map[common.Hash]*types.Block)
  158. rates = make(map[common.Hash]hashrate)
  159. currentWork *types.Block
  160. )
  161. // getWork returns a work package for external miner.
  162. //
  163. // The work package consists of 3 strings:
  164. // result[0], 32 bytes hex encoded current block header pow-hash
  165. // result[1], 32 bytes hex encoded seed hash used for DAG
  166. // result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
  167. getWork := func() ([3]string, error) {
  168. var res [3]string
  169. if currentWork == nil {
  170. return res, errNoMiningWork
  171. }
  172. res[0] = currentWork.HashNoNonce().Hex()
  173. res[1] = common.BytesToHash(SeedHash(currentWork.NumberU64())).Hex()
  174. // Calculate the "target" to be returned to the external sealer.
  175. n := big.NewInt(1)
  176. n.Lsh(n, 255)
  177. n.Div(n, currentWork.Difficulty())
  178. n.Lsh(n, 1)
  179. res[2] = common.BytesToHash(n.Bytes()).Hex()
  180. // Trace the seal work fetched by remote sealer.
  181. works[currentWork.HashNoNonce()] = currentWork
  182. return res, nil
  183. }
  184. // submitWork verifies the submitted pow solution, returning
  185. // whether the solution was accepted or not (not can be both a bad pow as well as
  186. // any other error, like no pending work or stale mining result).
  187. submitWork := func(nonce types.BlockNonce, mixDigest common.Hash, hash common.Hash) bool {
  188. // Make sure the work submitted is present
  189. block := works[hash]
  190. if block == nil {
  191. log.Info("Work submitted but none pending", "hash", hash)
  192. return false
  193. }
  194. // Verify the correctness of submitted result.
  195. header := block.Header()
  196. header.Nonce = nonce
  197. header.MixDigest = mixDigest
  198. if err := ethash.VerifySeal(nil, header); err != nil {
  199. log.Warn("Invalid proof-of-work submitted", "hash", hash, "err", err)
  200. return false
  201. }
  202. // Make sure the result channel is created.
  203. if ethash.resultCh == nil {
  204. log.Warn("Ethash result channel is empty, submitted mining result is rejected")
  205. return false
  206. }
  207. // Solutions seems to be valid, return to the miner and notify acceptance.
  208. select {
  209. case ethash.resultCh <- block.WithSeal(header):
  210. delete(works, hash)
  211. return true
  212. default:
  213. log.Info("Work submitted is stale", "hash", hash)
  214. return false
  215. }
  216. }
  217. ticker := time.NewTicker(5 * time.Second)
  218. defer ticker.Stop()
  219. for {
  220. select {
  221. case block := <-ethash.workCh:
  222. if currentWork != nil && block.ParentHash() != currentWork.ParentHash() {
  223. // Start new round mining, throw out all previous work.
  224. works = make(map[common.Hash]*types.Block)
  225. }
  226. // Update current work with new received block.
  227. // Note same work can be past twice, happens when changing CPU threads.
  228. currentWork = block
  229. case work := <-ethash.fetchWorkCh:
  230. // Return current mining work to remote miner.
  231. miningWork, err := getWork()
  232. if err != nil {
  233. work.errc <- err
  234. } else {
  235. work.res <- miningWork
  236. }
  237. case result := <-ethash.submitWorkCh:
  238. // Verify submitted PoW solution based on maintained mining blocks.
  239. if submitWork(result.nonce, result.mixDigest, result.hash) {
  240. result.errc <- nil
  241. } else {
  242. result.errc <- errInvalidSealResult
  243. }
  244. case result := <-ethash.submitRateCh:
  245. // Trace remote sealer's hash rate by submitted value.
  246. rates[result.id] = hashrate{rate: result.rate, ping: time.Now()}
  247. close(result.done)
  248. case req := <-ethash.fetchRateCh:
  249. // Gather all hash rate submitted by remote sealer.
  250. var total uint64
  251. for _, rate := range rates {
  252. // this could overflow
  253. total += rate.rate
  254. }
  255. req <- total
  256. case <-ticker.C:
  257. // Clear stale submitted hash rate.
  258. for id, rate := range rates {
  259. if time.Since(rate.ping) > 10*time.Second {
  260. delete(rates, id)
  261. }
  262. }
  263. case errc := <-ethash.exitCh:
  264. // Exit remote loop if ethash is closed and return relevant error.
  265. errc <- nil
  266. log.Trace("Ethash remote sealer is exiting")
  267. return
  268. }
  269. }
  270. }