sealer.go 12 KB

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