sealer.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. "context"
  20. crand "crypto/rand"
  21. "encoding/json"
  22. "errors"
  23. "math"
  24. "math/big"
  25. "math/rand"
  26. "net/http"
  27. "runtime"
  28. "sync"
  29. "time"
  30. "github.com/ethereum/go-ethereum/common"
  31. "github.com/ethereum/go-ethereum/common/hexutil"
  32. "github.com/ethereum/go-ethereum/consensus"
  33. "github.com/ethereum/go-ethereum/core/types"
  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.ChainHeaderReader, 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. ethash.config.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.remote != nil {
  82. ethash.remote.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. ethash.config.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. ethash.config.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. powBuffer = new(big.Int)
  138. )
  139. logger := ethash.config.Log.New("miner", id)
  140. logger.Trace("Started ethash search for new nonces", "seed", seed)
  141. search:
  142. for {
  143. select {
  144. case <-abort:
  145. // Mining terminated, update stats and abort
  146. logger.Trace("Ethash nonce search aborted", "attempts", nonce-seed)
  147. ethash.hashrate.Mark(attempts)
  148. break search
  149. default:
  150. // We don't have to update hash rate on every nonce, so update after after 2^X nonces
  151. attempts++
  152. if (attempts % (1 << 15)) == 0 {
  153. ethash.hashrate.Mark(attempts)
  154. attempts = 0
  155. }
  156. // Compute the PoW value of this nonce
  157. digest, result := hashimotoFull(dataset.dataset, hash, nonce)
  158. if powBuffer.SetBytes(result).Cmp(target) <= 0 {
  159. // Correct nonce found, create a new header with it
  160. header = types.CopyHeader(header)
  161. header.Nonce = types.EncodeNonce(nonce)
  162. header.MixDigest = common.BytesToHash(digest)
  163. // Seal and return a block (if still needed)
  164. select {
  165. case found <- block.WithSeal(header):
  166. logger.Trace("Ethash nonce found and reported", "attempts", nonce-seed, "nonce", nonce)
  167. case <-abort:
  168. logger.Trace("Ethash nonce found but discarded", "attempts", nonce-seed, "nonce", nonce)
  169. }
  170. break search
  171. }
  172. nonce++
  173. }
  174. }
  175. // Datasets are unmapped in a finalizer. Ensure that the dataset stays live
  176. // during sealing so it's not unmapped while being read.
  177. runtime.KeepAlive(dataset)
  178. }
  179. // This is the timeout for HTTP requests to notify external miners.
  180. const remoteSealerTimeout = 1 * time.Second
  181. type remoteSealer struct {
  182. works map[common.Hash]*types.Block
  183. rates map[common.Hash]hashrate
  184. currentBlock *types.Block
  185. currentWork [4]string
  186. notifyCtx context.Context
  187. cancelNotify context.CancelFunc // cancels all notification requests
  188. reqWG sync.WaitGroup // tracks notification request goroutines
  189. ethash *Ethash
  190. noverify bool
  191. notifyURLs []string
  192. results chan<- *types.Block
  193. workCh chan *sealTask // Notification channel to push new work and relative result channel to remote sealer
  194. fetchWorkCh chan *sealWork // Channel used for remote sealer to fetch mining work
  195. submitWorkCh chan *mineResult // Channel used for remote sealer to submit their mining result
  196. fetchRateCh chan chan uint64 // Channel used to gather submitted hash rate for local or remote sealer.
  197. submitRateCh chan *hashrate // Channel used for remote sealer to submit their mining hashrate
  198. requestExit chan struct{}
  199. exitCh chan struct{}
  200. }
  201. // sealTask wraps a seal block with relative result channel for remote sealer thread.
  202. type sealTask struct {
  203. block *types.Block
  204. results chan<- *types.Block
  205. }
  206. // mineResult wraps the pow solution parameters for the specified block.
  207. type mineResult struct {
  208. nonce types.BlockNonce
  209. mixDigest common.Hash
  210. hash common.Hash
  211. errc chan error
  212. }
  213. // hashrate wraps the hash rate submitted by the remote sealer.
  214. type hashrate struct {
  215. id common.Hash
  216. ping time.Time
  217. rate uint64
  218. done chan struct{}
  219. }
  220. // sealWork wraps a seal work package for remote sealer.
  221. type sealWork struct {
  222. errc chan error
  223. res chan [4]string
  224. }
  225. func startRemoteSealer(ethash *Ethash, urls []string, noverify bool) *remoteSealer {
  226. ctx, cancel := context.WithCancel(context.Background())
  227. s := &remoteSealer{
  228. ethash: ethash,
  229. noverify: noverify,
  230. notifyURLs: urls,
  231. notifyCtx: ctx,
  232. cancelNotify: cancel,
  233. works: make(map[common.Hash]*types.Block),
  234. rates: make(map[common.Hash]hashrate),
  235. workCh: make(chan *sealTask),
  236. fetchWorkCh: make(chan *sealWork),
  237. submitWorkCh: make(chan *mineResult),
  238. fetchRateCh: make(chan chan uint64),
  239. submitRateCh: make(chan *hashrate),
  240. requestExit: make(chan struct{}),
  241. exitCh: make(chan struct{}),
  242. }
  243. go s.loop()
  244. return s
  245. }
  246. func (s *remoteSealer) loop() {
  247. defer func() {
  248. s.ethash.config.Log.Trace("Ethash remote sealer is exiting")
  249. s.cancelNotify()
  250. s.reqWG.Wait()
  251. close(s.exitCh)
  252. }()
  253. ticker := time.NewTicker(5 * time.Second)
  254. defer ticker.Stop()
  255. for {
  256. select {
  257. case work := <-s.workCh:
  258. // Update current work with new received block.
  259. // Note same work can be past twice, happens when changing CPU threads.
  260. s.results = work.results
  261. s.makeWork(work.block)
  262. s.notifyWork()
  263. case work := <-s.fetchWorkCh:
  264. // Return current mining work to remote miner.
  265. if s.currentBlock == nil {
  266. work.errc <- errNoMiningWork
  267. } else {
  268. work.res <- s.currentWork
  269. }
  270. case result := <-s.submitWorkCh:
  271. // Verify submitted PoW solution based on maintained mining blocks.
  272. if s.submitWork(result.nonce, result.mixDigest, result.hash) {
  273. result.errc <- nil
  274. } else {
  275. result.errc <- errInvalidSealResult
  276. }
  277. case result := <-s.submitRateCh:
  278. // Trace remote sealer's hash rate by submitted value.
  279. s.rates[result.id] = hashrate{rate: result.rate, ping: time.Now()}
  280. close(result.done)
  281. case req := <-s.fetchRateCh:
  282. // Gather all hash rate submitted by remote sealer.
  283. var total uint64
  284. for _, rate := range s.rates {
  285. // this could overflow
  286. total += rate.rate
  287. }
  288. req <- total
  289. case <-ticker.C:
  290. // Clear stale submitted hash rate.
  291. for id, rate := range s.rates {
  292. if time.Since(rate.ping) > 10*time.Second {
  293. delete(s.rates, id)
  294. }
  295. }
  296. // Clear stale pending blocks
  297. if s.currentBlock != nil {
  298. for hash, block := range s.works {
  299. if block.NumberU64()+staleThreshold <= s.currentBlock.NumberU64() {
  300. delete(s.works, hash)
  301. }
  302. }
  303. }
  304. case <-s.requestExit:
  305. return
  306. }
  307. }
  308. }
  309. // makeWork creates a work package for external miner.
  310. //
  311. // The work package consists of 3 strings:
  312. // result[0], 32 bytes hex encoded current block header pow-hash
  313. // result[1], 32 bytes hex encoded seed hash used for DAG
  314. // result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
  315. // result[3], hex encoded block number
  316. func (s *remoteSealer) makeWork(block *types.Block) {
  317. hash := s.ethash.SealHash(block.Header())
  318. s.currentWork[0] = hash.Hex()
  319. s.currentWork[1] = common.BytesToHash(SeedHash(block.NumberU64())).Hex()
  320. s.currentWork[2] = common.BytesToHash(new(big.Int).Div(two256, block.Difficulty()).Bytes()).Hex()
  321. s.currentWork[3] = hexutil.EncodeBig(block.Number())
  322. // Trace the seal work fetched by remote sealer.
  323. s.currentBlock = block
  324. s.works[hash] = block
  325. }
  326. // notifyWork notifies all the specified mining endpoints of the availability of
  327. // new work to be processed.
  328. func (s *remoteSealer) notifyWork() {
  329. work := s.currentWork
  330. // Encode the JSON payload of the notification. When NotifyFull is set,
  331. // this is the complete block header, otherwise it is a JSON array.
  332. var blob []byte
  333. if s.ethash.config.NotifyFull {
  334. blob, _ = json.Marshal(s.currentBlock.Header())
  335. } else {
  336. blob, _ = json.Marshal(work)
  337. }
  338. s.reqWG.Add(len(s.notifyURLs))
  339. for _, url := range s.notifyURLs {
  340. go s.sendNotification(s.notifyCtx, url, blob, work)
  341. }
  342. }
  343. func (s *remoteSealer) sendNotification(ctx context.Context, url string, json []byte, work [4]string) {
  344. defer s.reqWG.Done()
  345. req, err := http.NewRequest("POST", url, bytes.NewReader(json))
  346. if err != nil {
  347. s.ethash.config.Log.Warn("Can't create remote miner notification", "err", err)
  348. return
  349. }
  350. ctx, cancel := context.WithTimeout(ctx, remoteSealerTimeout)
  351. defer cancel()
  352. req = req.WithContext(ctx)
  353. req.Header.Set("Content-Type", "application/json")
  354. resp, err := http.DefaultClient.Do(req)
  355. if err != nil {
  356. s.ethash.config.Log.Warn("Failed to notify remote miner", "err", err)
  357. } else {
  358. s.ethash.config.Log.Trace("Notified remote miner", "miner", url, "hash", work[0], "target", work[2])
  359. resp.Body.Close()
  360. }
  361. }
  362. // submitWork verifies the submitted pow solution, returning
  363. // whether the solution was accepted or not (not can be both a bad pow as well as
  364. // any other error, like no pending work or stale mining result).
  365. func (s *remoteSealer) submitWork(nonce types.BlockNonce, mixDigest common.Hash, sealhash common.Hash) bool {
  366. if s.currentBlock == nil {
  367. s.ethash.config.Log.Error("Pending work without block", "sealhash", sealhash)
  368. return false
  369. }
  370. // Make sure the work submitted is present
  371. block := s.works[sealhash]
  372. if block == nil {
  373. s.ethash.config.Log.Warn("Work submitted but none pending", "sealhash", sealhash, "curnumber", s.currentBlock.NumberU64())
  374. return false
  375. }
  376. // Verify the correctness of submitted result.
  377. header := block.Header()
  378. header.Nonce = nonce
  379. header.MixDigest = mixDigest
  380. start := time.Now()
  381. if !s.noverify {
  382. if err := s.ethash.verifySeal(nil, header, true); err != nil {
  383. s.ethash.config.Log.Warn("Invalid proof-of-work submitted", "sealhash", sealhash, "elapsed", common.PrettyDuration(time.Since(start)), "err", err)
  384. return false
  385. }
  386. }
  387. // Make sure the result channel is assigned.
  388. if s.results == nil {
  389. s.ethash.config.Log.Warn("Ethash result channel is empty, submitted mining result is rejected")
  390. return false
  391. }
  392. s.ethash.config.Log.Trace("Verified correct proof-of-work", "sealhash", sealhash, "elapsed", common.PrettyDuration(time.Since(start)))
  393. // Solutions seems to be valid, return to the miner and notify acceptance.
  394. solution := block.WithSeal(header)
  395. // The submitted solution is within the scope of acceptance.
  396. if solution.NumberU64()+staleThreshold > s.currentBlock.NumberU64() {
  397. select {
  398. case s.results <- solution:
  399. s.ethash.config.Log.Debug("Work submitted is acceptable", "number", solution.NumberU64(), "sealhash", sealhash, "hash", solution.Hash())
  400. return true
  401. default:
  402. s.ethash.config.Log.Warn("Sealing result is not read by miner", "mode", "remote", "sealhash", sealhash)
  403. return false
  404. }
  405. }
  406. // The submitted block is too old to accept, drop it.
  407. s.ethash.config.Log.Warn("Work submitted is too old", "number", solution.NumberU64(), "sealhash", sealhash, "hash", solution.Hash())
  408. return false
  409. }