sealer.go 14 KB

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