sealer.go 12 KB

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