sealer.go 10 KB

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