worker.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  1. // Copyright 2015 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 miner
  17. import (
  18. "bytes"
  19. "errors"
  20. "math/big"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. mapset "github.com/deckarep/golang-set"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/consensus"
  27. "github.com/ethereum/go-ethereum/consensus/misc"
  28. "github.com/ethereum/go-ethereum/consensus/parlia"
  29. "github.com/ethereum/go-ethereum/core"
  30. "github.com/ethereum/go-ethereum/core/state"
  31. "github.com/ethereum/go-ethereum/core/systemcontracts"
  32. "github.com/ethereum/go-ethereum/core/types"
  33. "github.com/ethereum/go-ethereum/event"
  34. "github.com/ethereum/go-ethereum/log"
  35. "github.com/ethereum/go-ethereum/metrics"
  36. "github.com/ethereum/go-ethereum/params"
  37. "github.com/ethereum/go-ethereum/trie"
  38. )
  39. const (
  40. // resultQueueSize is the size of channel listening to sealing result.
  41. resultQueueSize = 10
  42. // txChanSize is the size of channel listening to NewTxsEvent.
  43. // The number is referenced from the size of tx pool.
  44. txChanSize = 4096
  45. // chainHeadChanSize is the size of channel listening to ChainHeadEvent.
  46. chainHeadChanSize = 10
  47. // chainSideChanSize is the size of channel listening to ChainSideEvent.
  48. chainSideChanSize = 10
  49. // resubmitAdjustChanSize is the size of resubmitting interval adjustment channel.
  50. resubmitAdjustChanSize = 10
  51. // miningLogAtDepth is the number of confirmations before logging successful mining.
  52. miningLogAtDepth = 11
  53. // minRecommitInterval is the minimal time interval to recreate the mining block with
  54. // any newly arrived transactions.
  55. minRecommitInterval = 1 * time.Second
  56. // maxRecommitInterval is the maximum time interval to recreate the mining block with
  57. // any newly arrived transactions.
  58. maxRecommitInterval = 15 * time.Second
  59. // intervalAdjustRatio is the impact a single interval adjustment has on sealing work
  60. // resubmitting interval.
  61. intervalAdjustRatio = 0.1
  62. // intervalAdjustBias is applied during the new resubmit interval calculation in favor of
  63. // increasing upper limit or decreasing lower limit so that the limit can be reachable.
  64. intervalAdjustBias = 200 * 1000.0 * 1000.0
  65. // staleThreshold is the maximum depth of the acceptable stale block.
  66. staleThreshold = 11
  67. )
  68. var (
  69. commitTxsTimer = metrics.NewRegisteredTimer("worker/committxs", nil)
  70. )
  71. // environment is the worker's current environment and holds all of the current state information.
  72. type environment struct {
  73. signer types.Signer
  74. state *state.StateDB // apply state changes here
  75. ancestors mapset.Set // ancestor set (used for checking uncle parent validity)
  76. family mapset.Set // family set (used for checking uncle invalidity)
  77. uncles mapset.Set // uncle set
  78. tcount int // tx count in cycle
  79. gasPool *core.GasPool // available gas used to pack transactions
  80. header *types.Header
  81. txs []*types.Transaction
  82. receipts []*types.Receipt
  83. }
  84. // task contains all information for consensus engine sealing and result submitting.
  85. type task struct {
  86. receipts []*types.Receipt
  87. state *state.StateDB
  88. block *types.Block
  89. createdAt time.Time
  90. }
  91. const (
  92. commitInterruptNone int32 = iota
  93. commitInterruptNewHead
  94. commitInterruptResubmit
  95. )
  96. // newWorkReq represents a request for new sealing work submitting with relative interrupt notifier.
  97. type newWorkReq struct {
  98. interrupt *int32
  99. noempty bool
  100. timestamp int64
  101. }
  102. // intervalAdjust represents a resubmitting interval adjustment.
  103. type intervalAdjust struct {
  104. ratio float64
  105. inc bool
  106. }
  107. // worker is the main object which takes care of submitting new work to consensus engine
  108. // and gathering the sealing result.
  109. type worker struct {
  110. config *Config
  111. chainConfig *params.ChainConfig
  112. engine consensus.Engine
  113. eth Backend
  114. chain *core.BlockChain
  115. // Feeds
  116. pendingLogsFeed event.Feed
  117. // Subscriptions
  118. mux *event.TypeMux
  119. txsCh chan core.NewTxsEvent
  120. txsSub event.Subscription
  121. chainHeadCh chan core.ChainHeadEvent
  122. chainHeadSub event.Subscription
  123. chainSideCh chan core.ChainSideEvent
  124. chainSideSub event.Subscription
  125. // Channels
  126. newWorkCh chan *newWorkReq
  127. taskCh chan *task
  128. resultCh chan *types.Block
  129. startCh chan struct{}
  130. exitCh chan struct{}
  131. resubmitIntervalCh chan time.Duration
  132. resubmitAdjustCh chan *intervalAdjust
  133. current *environment // An environment for current running cycle.
  134. localUncles map[common.Hash]*types.Block // A set of side blocks generated locally as the possible uncle blocks.
  135. remoteUncles map[common.Hash]*types.Block // A set of side blocks as the possible uncle blocks.
  136. unconfirmed *unconfirmedBlocks // A set of locally mined blocks pending canonicalness confirmations.
  137. mu sync.RWMutex // The lock used to protect the coinbase and extra fields
  138. coinbase common.Address
  139. extra []byte
  140. pendingMu sync.RWMutex
  141. pendingTasks map[common.Hash]*task
  142. snapshotMu sync.RWMutex // The lock used to protect the block snapshot and state snapshot
  143. snapshotBlock *types.Block
  144. snapshotState *state.StateDB
  145. // atomic status counters
  146. running int32 // The indicator whether the consensus engine is running or not.
  147. newTxs int32 // New arrival transaction count since last sealing work submitting.
  148. // noempty is the flag used to control whether the feature of pre-seal empty
  149. // block is enabled. The default value is false(pre-seal is enabled by default).
  150. // But in some special scenario the consensus engine will seal blocks instantaneously,
  151. // in this case this feature will add all empty blocks into canonical chain
  152. // non-stop and no real transaction will be included.
  153. noempty uint32
  154. // External functions
  155. isLocalBlock func(block *types.Block) bool // Function used to determine whether the specified block is mined by local miner.
  156. // Test hooks
  157. newTaskHook func(*task) // Method to call upon receiving a new sealing task.
  158. skipSealHook func(*task) bool // Method to decide whether skipping the sealing.
  159. fullTaskHook func() // Method to call before pushing the full sealing task.
  160. resubmitHook func(time.Duration, time.Duration) // Method to call upon updating resubmitting interval.
  161. }
  162. func newWorker(config *Config, chainConfig *params.ChainConfig, engine consensus.Engine, eth Backend, mux *event.TypeMux, isLocalBlock func(*types.Block) bool, init bool) *worker {
  163. worker := &worker{
  164. config: config,
  165. chainConfig: chainConfig,
  166. engine: engine,
  167. eth: eth,
  168. mux: mux,
  169. chain: eth.BlockChain(),
  170. isLocalBlock: isLocalBlock,
  171. localUncles: make(map[common.Hash]*types.Block),
  172. remoteUncles: make(map[common.Hash]*types.Block),
  173. unconfirmed: newUnconfirmedBlocks(eth.BlockChain(), miningLogAtDepth),
  174. pendingTasks: make(map[common.Hash]*task),
  175. txsCh: make(chan core.NewTxsEvent, txChanSize),
  176. chainHeadCh: make(chan core.ChainHeadEvent, chainHeadChanSize),
  177. chainSideCh: make(chan core.ChainSideEvent, chainSideChanSize),
  178. newWorkCh: make(chan *newWorkReq),
  179. taskCh: make(chan *task),
  180. resultCh: make(chan *types.Block, resultQueueSize),
  181. exitCh: make(chan struct{}),
  182. startCh: make(chan struct{}, 1),
  183. resubmitIntervalCh: make(chan time.Duration),
  184. resubmitAdjustCh: make(chan *intervalAdjust, resubmitAdjustChanSize),
  185. }
  186. // Subscribe NewTxsEvent for tx pool
  187. worker.txsSub = eth.TxPool().SubscribeNewTxsEvent(worker.txsCh)
  188. // Subscribe events for blockchain
  189. worker.chainHeadSub = eth.BlockChain().SubscribeChainHeadEvent(worker.chainHeadCh)
  190. worker.chainSideSub = eth.BlockChain().SubscribeChainSideEvent(worker.chainSideCh)
  191. // Sanitize recommit interval if the user-specified one is too short.
  192. recommit := worker.config.Recommit
  193. if recommit < minRecommitInterval {
  194. log.Warn("Sanitizing miner recommit interval", "provided", recommit, "updated", minRecommitInterval)
  195. recommit = minRecommitInterval
  196. }
  197. go worker.mainLoop()
  198. go worker.newWorkLoop(recommit)
  199. go worker.resultLoop()
  200. go worker.taskLoop()
  201. // Submit first work to initialize pending state.
  202. if init {
  203. worker.startCh <- struct{}{}
  204. }
  205. return worker
  206. }
  207. // setEtherbase sets the etherbase used to initialize the block coinbase field.
  208. func (w *worker) setEtherbase(addr common.Address) {
  209. w.mu.Lock()
  210. defer w.mu.Unlock()
  211. w.coinbase = addr
  212. }
  213. // setExtra sets the content used to initialize the block extra field.
  214. func (w *worker) setExtra(extra []byte) {
  215. w.mu.Lock()
  216. defer w.mu.Unlock()
  217. w.extra = extra
  218. }
  219. // setRecommitInterval updates the interval for miner sealing work recommitting.
  220. func (w *worker) setRecommitInterval(interval time.Duration) {
  221. w.resubmitIntervalCh <- interval
  222. }
  223. // disablePreseal disables pre-sealing mining feature
  224. func (w *worker) disablePreseal() {
  225. atomic.StoreUint32(&w.noempty, 1)
  226. }
  227. // enablePreseal enables pre-sealing mining feature
  228. func (w *worker) enablePreseal() {
  229. atomic.StoreUint32(&w.noempty, 0)
  230. }
  231. // pending returns the pending state and corresponding block.
  232. func (w *worker) pending() (*types.Block, *state.StateDB) {
  233. // return a snapshot to avoid contention on currentMu mutex
  234. w.snapshotMu.RLock()
  235. defer w.snapshotMu.RUnlock()
  236. if w.snapshotState == nil {
  237. return nil, nil
  238. }
  239. return w.snapshotBlock, w.snapshotState.Copy()
  240. }
  241. // pendingBlock returns pending block.
  242. func (w *worker) pendingBlock() *types.Block {
  243. // return a snapshot to avoid contention on currentMu mutex
  244. w.snapshotMu.RLock()
  245. defer w.snapshotMu.RUnlock()
  246. return w.snapshotBlock
  247. }
  248. // start sets the running status as 1 and triggers new work submitting.
  249. func (w *worker) start() {
  250. atomic.StoreInt32(&w.running, 1)
  251. w.startCh <- struct{}{}
  252. }
  253. // stop sets the running status as 0.
  254. func (w *worker) stop() {
  255. atomic.StoreInt32(&w.running, 0)
  256. }
  257. // isRunning returns an indicator whether worker is running or not.
  258. func (w *worker) isRunning() bool {
  259. return atomic.LoadInt32(&w.running) == 1
  260. }
  261. // close terminates all background threads maintained by the worker.
  262. // Note the worker does not support being closed multiple times.
  263. func (w *worker) close() {
  264. if w.current != nil && w.current.state != nil {
  265. w.current.state.StopPrefetcher()
  266. }
  267. atomic.StoreInt32(&w.running, 0)
  268. close(w.exitCh)
  269. }
  270. // recalcRecommit recalculates the resubmitting interval upon feedback.
  271. func recalcRecommit(minRecommit, prev time.Duration, target float64, inc bool) time.Duration {
  272. var (
  273. prevF = float64(prev.Nanoseconds())
  274. next float64
  275. )
  276. if inc {
  277. next = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target+intervalAdjustBias)
  278. max := float64(maxRecommitInterval.Nanoseconds())
  279. if next > max {
  280. next = max
  281. }
  282. } else {
  283. next = prevF*(1-intervalAdjustRatio) + intervalAdjustRatio*(target-intervalAdjustBias)
  284. min := float64(minRecommit.Nanoseconds())
  285. if next < min {
  286. next = min
  287. }
  288. }
  289. return time.Duration(int64(next))
  290. }
  291. // newWorkLoop is a standalone goroutine to submit new mining work upon received events.
  292. func (w *worker) newWorkLoop(recommit time.Duration) {
  293. var (
  294. interrupt *int32
  295. minRecommit = recommit // minimal resubmit interval specified by user.
  296. timestamp int64 // timestamp for each round of mining.
  297. )
  298. timer := time.NewTimer(0)
  299. defer timer.Stop()
  300. <-timer.C // discard the initial tick
  301. // commit aborts in-flight transaction execution with given signal and resubmits a new one.
  302. commit := func(noempty bool, s int32) {
  303. if interrupt != nil {
  304. atomic.StoreInt32(interrupt, s)
  305. }
  306. interrupt = new(int32)
  307. select {
  308. case w.newWorkCh <- &newWorkReq{interrupt: interrupt, noempty: noempty, timestamp: timestamp}:
  309. case <-w.exitCh:
  310. return
  311. }
  312. timer.Reset(recommit)
  313. atomic.StoreInt32(&w.newTxs, 0)
  314. }
  315. // clearPending cleans the stale pending tasks.
  316. clearPending := func(number uint64) {
  317. w.pendingMu.Lock()
  318. for h, t := range w.pendingTasks {
  319. if t.block.NumberU64()+staleThreshold <= number {
  320. delete(w.pendingTasks, h)
  321. }
  322. }
  323. w.pendingMu.Unlock()
  324. }
  325. for {
  326. select {
  327. case <-w.startCh:
  328. clearPending(w.chain.CurrentBlock().NumberU64())
  329. timestamp = time.Now().Unix()
  330. commit(true, commitInterruptNewHead)
  331. case head := <-w.chainHeadCh:
  332. if !w.isRunning() {
  333. continue
  334. }
  335. clearPending(head.Block.NumberU64())
  336. timestamp = time.Now().Unix()
  337. commit(true, commitInterruptNewHead)
  338. case <-timer.C:
  339. // If mining is running resubmit a new work cycle periodically to pull in
  340. // higher priced transactions. Disable this overhead for pending blocks.
  341. if w.isRunning() && ((w.chainConfig.Ethash != nil) || (w.chainConfig.Clique != nil &&
  342. w.chainConfig.Clique.Period > 0) || (w.chainConfig.Parlia != nil && w.chainConfig.Parlia.Period > 0)) {
  343. // Short circuit if no new transaction arrives.
  344. if atomic.LoadInt32(&w.newTxs) == 0 {
  345. timer.Reset(recommit)
  346. continue
  347. }
  348. commit(true, commitInterruptResubmit)
  349. }
  350. case interval := <-w.resubmitIntervalCh:
  351. // Adjust resubmit interval explicitly by user.
  352. if interval < minRecommitInterval {
  353. log.Warn("Sanitizing miner recommit interval", "provided", interval, "updated", minRecommitInterval)
  354. interval = minRecommitInterval
  355. }
  356. log.Info("Miner recommit interval update", "from", minRecommit, "to", interval)
  357. minRecommit, recommit = interval, interval
  358. if w.resubmitHook != nil {
  359. w.resubmitHook(minRecommit, recommit)
  360. }
  361. case adjust := <-w.resubmitAdjustCh:
  362. // Adjust resubmit interval by feedback.
  363. if adjust.inc {
  364. before := recommit
  365. target := float64(recommit.Nanoseconds()) / adjust.ratio
  366. recommit = recalcRecommit(minRecommit, recommit, target, true)
  367. log.Trace("Increase miner recommit interval", "from", before, "to", recommit)
  368. } else {
  369. before := recommit
  370. recommit = recalcRecommit(minRecommit, recommit, float64(minRecommit.Nanoseconds()), false)
  371. log.Trace("Decrease miner recommit interval", "from", before, "to", recommit)
  372. }
  373. if w.resubmitHook != nil {
  374. w.resubmitHook(minRecommit, recommit)
  375. }
  376. case <-w.exitCh:
  377. return
  378. }
  379. }
  380. }
  381. // mainLoop is a standalone goroutine to regenerate the sealing task based on the received event.
  382. func (w *worker) mainLoop() {
  383. defer w.txsSub.Unsubscribe()
  384. defer w.chainHeadSub.Unsubscribe()
  385. defer w.chainSideSub.Unsubscribe()
  386. for {
  387. select {
  388. case req := <-w.newWorkCh:
  389. w.commitNewWork(req.interrupt, req.noempty, req.timestamp)
  390. case ev := <-w.chainSideCh:
  391. // Short circuit for duplicate side blocks
  392. if _, ok := w.engine.(*parlia.Parlia); ok {
  393. continue
  394. }
  395. if _, exist := w.localUncles[ev.Block.Hash()]; exist {
  396. continue
  397. }
  398. if _, exist := w.remoteUncles[ev.Block.Hash()]; exist {
  399. continue
  400. }
  401. // Add side block to possible uncle block set depending on the author.
  402. if w.isLocalBlock != nil && w.isLocalBlock(ev.Block) {
  403. w.localUncles[ev.Block.Hash()] = ev.Block
  404. } else {
  405. w.remoteUncles[ev.Block.Hash()] = ev.Block
  406. }
  407. // If our mining block contains less than 2 uncle blocks,
  408. // add the new uncle block if valid and regenerate a mining block.
  409. if w.isRunning() && w.current != nil && w.current.uncles.Cardinality() < 2 {
  410. start := time.Now()
  411. if err := w.commitUncle(w.current, ev.Block.Header()); err == nil {
  412. var uncles []*types.Header
  413. w.commit(uncles, nil, false, start)
  414. }
  415. }
  416. case ev := <-w.txsCh:
  417. // Apply transactions to the pending state if we're not mining.
  418. //
  419. // Note all transactions received may not be continuous with transactions
  420. // already included in the current mining block. These transactions will
  421. // be automatically eliminated.
  422. if !w.isRunning() && w.current != nil {
  423. // If block is already full, abort
  424. if gp := w.current.gasPool; gp != nil && gp.Gas() < params.TxGas {
  425. continue
  426. }
  427. w.mu.RLock()
  428. coinbase := w.coinbase
  429. w.mu.RUnlock()
  430. txs := make(map[common.Address]types.Transactions)
  431. for _, tx := range ev.Txs {
  432. acc, _ := types.Sender(w.current.signer, tx)
  433. txs[acc] = append(txs[acc], tx)
  434. }
  435. txset := types.NewTransactionsByPriceAndNonce(w.current.signer, txs)
  436. tcount := w.current.tcount
  437. w.commitTransactions(txset, coinbase, nil)
  438. // Only update the snapshot if any new transactons were added
  439. // to the pending block
  440. if tcount != w.current.tcount {
  441. w.updateSnapshot()
  442. }
  443. } else {
  444. // Special case, if the consensus engine is 0 period clique(dev mode),
  445. // submit mining work here since all empty submission will be rejected
  446. // by clique. Of course the advance sealing(empty submission) is disabled.
  447. if (w.chainConfig.Clique != nil && w.chainConfig.Clique.Period == 0) ||
  448. (w.chainConfig.Parlia != nil && w.chainConfig.Parlia.Period == 0) {
  449. w.commitNewWork(nil, true, time.Now().Unix())
  450. }
  451. }
  452. atomic.AddInt32(&w.newTxs, int32(len(ev.Txs)))
  453. // System stopped
  454. case <-w.exitCh:
  455. return
  456. case <-w.txsSub.Err():
  457. return
  458. case <-w.chainHeadSub.Err():
  459. return
  460. case <-w.chainSideSub.Err():
  461. return
  462. }
  463. }
  464. }
  465. // taskLoop is a standalone goroutine to fetch sealing task from the generator and
  466. // push them to consensus engine.
  467. func (w *worker) taskLoop() {
  468. var (
  469. stopCh chan struct{}
  470. prev common.Hash
  471. )
  472. // interrupt aborts the in-flight sealing task.
  473. interrupt := func() {
  474. if stopCh != nil {
  475. close(stopCh)
  476. stopCh = nil
  477. }
  478. }
  479. for {
  480. select {
  481. case task := <-w.taskCh:
  482. if w.newTaskHook != nil {
  483. w.newTaskHook(task)
  484. }
  485. // Reject duplicate sealing work due to resubmitting.
  486. sealHash := w.engine.SealHash(task.block.Header())
  487. if sealHash == prev {
  488. continue
  489. }
  490. // Interrupt previous sealing operation
  491. interrupt()
  492. stopCh, prev = make(chan struct{}), sealHash
  493. if w.skipSealHook != nil && w.skipSealHook(task) {
  494. continue
  495. }
  496. w.pendingMu.Lock()
  497. w.pendingTasks[sealHash] = task
  498. w.pendingMu.Unlock()
  499. if err := w.engine.Seal(w.chain, task.block, w.resultCh, stopCh); err != nil {
  500. log.Warn("Block sealing failed", "err", err)
  501. }
  502. case <-w.exitCh:
  503. interrupt()
  504. return
  505. }
  506. }
  507. }
  508. // resultLoop is a standalone goroutine to handle sealing result submitting
  509. // and flush relative data to the database.
  510. func (w *worker) resultLoop() {
  511. for {
  512. select {
  513. case block := <-w.resultCh:
  514. // Short circuit when receiving empty result.
  515. if block == nil {
  516. continue
  517. }
  518. // Short circuit when receiving duplicate result caused by resubmitting.
  519. if w.chain.HasBlock(block.Hash(), block.NumberU64()) {
  520. continue
  521. }
  522. var (
  523. sealhash = w.engine.SealHash(block.Header())
  524. hash = block.Hash()
  525. )
  526. w.pendingMu.RLock()
  527. task, exist := w.pendingTasks[sealhash]
  528. w.pendingMu.RUnlock()
  529. if !exist {
  530. log.Error("Block found but no relative pending task", "number", block.Number(), "sealhash", sealhash, "hash", hash)
  531. continue
  532. }
  533. // Different block could share same sealhash, deep copy here to prevent write-write conflict.
  534. var (
  535. receipts = make([]*types.Receipt, len(task.receipts))
  536. logs []*types.Log
  537. )
  538. for i, receipt := range task.receipts {
  539. // add block location fields
  540. receipt.BlockHash = hash
  541. receipt.BlockNumber = block.Number()
  542. receipt.TransactionIndex = uint(i)
  543. receipts[i] = new(types.Receipt)
  544. *receipts[i] = *receipt
  545. // Update the block hash in all logs since it is now available and not when the
  546. // receipt/log of individual transactions were created.
  547. for _, log := range receipt.Logs {
  548. log.BlockHash = hash
  549. }
  550. logs = append(logs, receipt.Logs...)
  551. }
  552. // Commit block and state to database.
  553. _, err := w.chain.WriteBlockWithState(block, receipts, logs, task.state, true)
  554. if err != nil {
  555. log.Error("Failed writing block to chain", "err", err)
  556. continue
  557. }
  558. log.Info("Successfully sealed new block", "number", block.Number(), "sealhash", sealhash, "hash", hash,
  559. "elapsed", common.PrettyDuration(time.Since(task.createdAt)))
  560. // Broadcast the block and announce chain insertion event
  561. w.mux.Post(core.NewMinedBlockEvent{Block: block})
  562. // Insert the block into the set of pending ones to resultLoop for confirmations
  563. w.unconfirmed.Insert(block.NumberU64(), block.Hash())
  564. case <-w.exitCh:
  565. return
  566. }
  567. }
  568. }
  569. // makeCurrent creates a new environment for the current cycle.
  570. func (w *worker) makeCurrent(parent *types.Block, header *types.Header) error {
  571. // Retrieve the parent state to execute on top and start a prefetcher for
  572. // the miner to speed block sealing up a bit
  573. state, err := w.chain.StateAt(parent.Root())
  574. if err != nil {
  575. return err
  576. }
  577. state.StartPrefetcher("miner")
  578. env := &environment{
  579. signer: types.MakeSigner(w.chainConfig, header.Number),
  580. state: state,
  581. ancestors: mapset.NewSet(),
  582. family: mapset.NewSet(),
  583. uncles: mapset.NewSet(),
  584. header: header,
  585. }
  586. // Keep track of transactions which return errors so they can be removed
  587. env.tcount = 0
  588. // Swap out the old work with the new one, terminating any leftover prefetcher
  589. // processes in the mean time and starting a new one.
  590. if w.current != nil && w.current.state != nil {
  591. w.current.state.StopPrefetcher()
  592. }
  593. w.current = env
  594. return nil
  595. }
  596. // commitUncle adds the given block to uncle block set, returns error if failed to add.
  597. func (w *worker) commitUncle(env *environment, uncle *types.Header) error {
  598. hash := uncle.Hash()
  599. if env.uncles.Contains(hash) {
  600. return errors.New("uncle not unique")
  601. }
  602. if env.header.ParentHash == uncle.ParentHash {
  603. return errors.New("uncle is sibling")
  604. }
  605. if !env.ancestors.Contains(uncle.ParentHash) {
  606. return errors.New("uncle's parent unknown")
  607. }
  608. if env.family.Contains(hash) {
  609. return errors.New("uncle already included")
  610. }
  611. env.uncles.Add(uncle.Hash())
  612. return nil
  613. }
  614. // updateSnapshot updates pending snapshot block and state.
  615. // Note this function assumes the current variable is thread safe.
  616. func (w *worker) updateSnapshot() {
  617. w.snapshotMu.Lock()
  618. defer w.snapshotMu.Unlock()
  619. var uncles []*types.Header
  620. w.current.uncles.Each(func(item interface{}) bool {
  621. hash, ok := item.(common.Hash)
  622. if !ok {
  623. return false
  624. }
  625. uncle, exist := w.localUncles[hash]
  626. if !exist {
  627. uncle, exist = w.remoteUncles[hash]
  628. }
  629. if !exist {
  630. return false
  631. }
  632. uncles = append(uncles, uncle.Header())
  633. return false
  634. })
  635. w.snapshotBlock = types.NewBlock(
  636. w.current.header,
  637. w.current.txs,
  638. uncles,
  639. w.current.receipts,
  640. trie.NewStackTrie(nil),
  641. )
  642. w.snapshotState = w.current.state.Copy()
  643. }
  644. func (w *worker) commitTransaction(tx *types.Transaction, coinbase common.Address) ([]*types.Log, error) {
  645. snap := w.current.state.Snapshot()
  646. receipt, err := core.ApplyTransaction(w.chainConfig, w.chain, &coinbase, w.current.gasPool, w.current.state, w.current.header, tx, &w.current.header.GasUsed, *w.chain.GetVMConfig())
  647. if err != nil {
  648. w.current.state.RevertToSnapshot(snap)
  649. return nil, err
  650. }
  651. w.current.txs = append(w.current.txs, tx)
  652. w.current.receipts = append(w.current.receipts, receipt)
  653. return receipt.Logs, nil
  654. }
  655. func (w *worker) commitTransactions(txs *types.TransactionsByPriceAndNonce, coinbase common.Address, interrupt *int32) bool {
  656. // Short circuit if current is nil
  657. if w.current == nil {
  658. return true
  659. }
  660. if w.current.gasPool == nil {
  661. w.current.gasPool = new(core.GasPool).AddGas(w.current.header.GasLimit)
  662. w.current.gasPool.SubGas(params.SystemTxsGas)
  663. }
  664. var coalescedLogs []*types.Log
  665. var stopTimer *time.Timer
  666. delay := w.engine.Delay(w.chain, w.current.header)
  667. if delay != nil {
  668. stopTimer = time.NewTimer(*delay - w.config.DelayLeftOver)
  669. log.Debug("Time left for mining work", "left", (*delay - w.config.DelayLeftOver).String(), "leftover", w.config.DelayLeftOver)
  670. defer stopTimer.Stop()
  671. }
  672. LOOP:
  673. for {
  674. // In the following three cases, we will interrupt the execution of the transaction.
  675. // (1) new head block event arrival, the interrupt signal is 1
  676. // (2) worker start or restart, the interrupt signal is 1
  677. // (3) worker recreate the mining block with any newly arrived transactions, the interrupt signal is 2.
  678. // For the first two cases, the semi-finished work will be discarded.
  679. // For the third case, the semi-finished work will be submitted to the consensus engine.
  680. if interrupt != nil && atomic.LoadInt32(interrupt) != commitInterruptNone {
  681. // Notify resubmit loop to increase resubmitting interval due to too frequent commits.
  682. if atomic.LoadInt32(interrupt) == commitInterruptResubmit {
  683. ratio := float64(w.current.header.GasLimit-w.current.gasPool.Gas()) / float64(w.current.header.GasLimit)
  684. if ratio < 0.1 {
  685. ratio = 0.1
  686. }
  687. w.resubmitAdjustCh <- &intervalAdjust{
  688. ratio: ratio,
  689. inc: true,
  690. }
  691. }
  692. return atomic.LoadInt32(interrupt) == commitInterruptNewHead
  693. }
  694. // If we don't have enough gas for any further transactions then we're done
  695. if w.current.gasPool.Gas() < params.TxGas {
  696. log.Trace("Not enough gas for further transactions", "have", w.current.gasPool, "want", params.TxGas)
  697. break
  698. }
  699. if stopTimer != nil {
  700. select {
  701. case <-stopTimer.C:
  702. log.Info("Not enough time for further transactions", "txs", len(w.current.txs))
  703. break LOOP
  704. default:
  705. }
  706. }
  707. // Retrieve the next transaction and abort if all done
  708. tx := txs.Peek()
  709. if tx == nil {
  710. break
  711. }
  712. // Error may be ignored here. The error has already been checked
  713. // during transaction acceptance is the transaction pool.
  714. //
  715. // We use the eip155 signer regardless of the current hf.
  716. //from, _ := types.Sender(w.current.signer, tx)
  717. // Check whether the tx is replay protected. If we're not in the EIP155 hf
  718. // phase, start ignoring the sender until we do.
  719. if tx.Protected() && !w.chainConfig.IsEIP155(w.current.header.Number) {
  720. //log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", w.chainConfig.EIP155Block)
  721. txs.Pop()
  722. continue
  723. }
  724. // Start executing the transaction
  725. w.current.state.Prepare(tx.Hash(), common.Hash{}, w.current.tcount)
  726. logs, err := w.commitTransaction(tx, coinbase)
  727. switch {
  728. case errors.Is(err, core.ErrGasLimitReached):
  729. // Pop the current out-of-gas transaction without shifting in the next from the account
  730. //log.Trace("Gas limit exceeded for current block", "sender", from)
  731. txs.Pop()
  732. case errors.Is(err, core.ErrNonceTooLow):
  733. // New head notification data race between the transaction pool and miner, shift
  734. //log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
  735. txs.Shift()
  736. case errors.Is(err, core.ErrNonceTooHigh):
  737. // Reorg notification data race between the transaction pool and miner, skip account =
  738. //log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce())
  739. txs.Pop()
  740. case errors.Is(err, nil):
  741. // Everything ok, collect the logs and shift in the next transaction from the same account
  742. coalescedLogs = append(coalescedLogs, logs...)
  743. w.current.tcount++
  744. txs.Shift()
  745. case errors.Is(err, core.ErrTxTypeNotSupported):
  746. // Pop the unsupported transaction without shifting in the next from the account
  747. //log.Trace("Skipping unsupported transaction type", "sender", from, "type", tx.Type())
  748. txs.Pop()
  749. default:
  750. // Strange error, discard the transaction and get the next in line (note, the
  751. // nonce-too-high clause will prevent us from executing in vain).
  752. //log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
  753. txs.Shift()
  754. }
  755. }
  756. if !w.isRunning() && len(coalescedLogs) > 0 {
  757. // We don't push the pendingLogsEvent while we are mining. The reason is that
  758. // when we are mining, the worker will regenerate a mining block every 3 seconds.
  759. // In order to avoid pushing the repeated pendingLog, we disable the pending log pushing.
  760. // make a copy, the state caches the logs and these logs get "upgraded" from pending to mined
  761. // logs by filling in the block hash when the block was mined by the local miner. This can
  762. // cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed.
  763. cpy := make([]*types.Log, len(coalescedLogs))
  764. for i, l := range coalescedLogs {
  765. cpy[i] = new(types.Log)
  766. *cpy[i] = *l
  767. }
  768. w.pendingLogsFeed.Send(cpy)
  769. }
  770. // Notify resubmit loop to decrease resubmitting interval if current interval is larger
  771. // than the user-specified one.
  772. if interrupt != nil {
  773. w.resubmitAdjustCh <- &intervalAdjust{inc: false}
  774. }
  775. return false
  776. }
  777. // commitNewWork generates several new sealing tasks based on the parent block.
  778. func (w *worker) commitNewWork(interrupt *int32, noempty bool, timestamp int64) {
  779. w.mu.RLock()
  780. defer w.mu.RUnlock()
  781. tstart := time.Now()
  782. parent := w.chain.CurrentBlock()
  783. if parent.Time() >= uint64(timestamp) {
  784. timestamp = int64(parent.Time() + 1)
  785. }
  786. num := parent.Number()
  787. header := &types.Header{
  788. ParentHash: parent.Hash(),
  789. Number: num.Add(num, common.Big1),
  790. GasLimit: core.CalcGasLimit(parent, w.config.GasFloor, w.config.GasCeil),
  791. Extra: w.extra,
  792. Time: uint64(timestamp),
  793. }
  794. // Only set the coinbase if our consensus engine is running (avoid spurious block rewards)
  795. if w.isRunning() {
  796. if w.coinbase == (common.Address{}) {
  797. log.Error("Refusing to mine without etherbase")
  798. return
  799. }
  800. header.Coinbase = w.coinbase
  801. }
  802. if err := w.engine.Prepare(w.chain, header); err != nil {
  803. log.Error("Failed to prepare header for mining", "err", err)
  804. return
  805. }
  806. // If we are care about TheDAO hard-fork check whether to override the extra-data or not
  807. if daoBlock := w.chainConfig.DAOForkBlock; daoBlock != nil {
  808. // Check whether the block is among the fork extra-override range
  809. limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
  810. if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
  811. // Depending whether we support or oppose the fork, override differently
  812. if w.chainConfig.DAOForkSupport {
  813. header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
  814. } else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
  815. header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
  816. }
  817. }
  818. }
  819. // Could potentially happen if starting to mine in an odd state.
  820. err := w.makeCurrent(parent, header)
  821. if err != nil {
  822. log.Error("Failed to create mining context", "err", err)
  823. return
  824. }
  825. // Create the current work task and check any fork transitions needed
  826. env := w.current
  827. if w.chainConfig.DAOForkSupport && w.chainConfig.DAOForkBlock != nil && w.chainConfig.DAOForkBlock.Cmp(header.Number) == 0 {
  828. misc.ApplyDAOHardFork(env.state)
  829. }
  830. systemcontracts.UpgradeBuildInSystemContract(w.chainConfig, header.Number, env.state)
  831. // Accumulate the uncles for the current block
  832. uncles := make([]*types.Header, 0)
  833. // Create an empty block based on temporary copied state for
  834. // sealing in advance without waiting block execution finished.
  835. if !noempty && atomic.LoadUint32(&w.noempty) == 0 {
  836. w.commit(uncles, nil, false, tstart)
  837. }
  838. // Fill the block with all available pending transactions.
  839. pending, err := w.eth.TxPool().Pending()
  840. if err != nil {
  841. log.Error("Failed to fetch pending transactions", "err", err)
  842. }
  843. // Short circuit if there is no available pending transactions
  844. if len(pending) != 0 {
  845. start := time.Now()
  846. // Split the pending transactions into locals and remotes
  847. localTxs, remoteTxs := make(map[common.Address]types.Transactions), pending
  848. for _, account := range w.eth.TxPool().Locals() {
  849. if txs := remoteTxs[account]; len(txs) > 0 {
  850. delete(remoteTxs, account)
  851. localTxs[account] = txs
  852. }
  853. }
  854. if len(localTxs) > 0 {
  855. txs := types.NewTransactionsByPriceAndNonce(w.current.signer, localTxs)
  856. if w.commitTransactions(txs, w.coinbase, interrupt) {
  857. return
  858. }
  859. }
  860. if len(remoteTxs) > 0 {
  861. txs := types.NewTransactionsByPriceAndNonce(w.current.signer, remoteTxs)
  862. if w.commitTransactions(txs, w.coinbase, interrupt) {
  863. return
  864. }
  865. }
  866. commitTxsTimer.UpdateSince(start)
  867. log.Info("Gas pool", "height", header.Number.String(), "pool", w.current.gasPool.String())
  868. }
  869. w.commit(uncles, w.fullTaskHook, false, tstart)
  870. }
  871. // commit runs any post-transaction state modifications, assembles the final block
  872. // and commits new work if consensus engine is running.
  873. func (w *worker) commit(uncles []*types.Header, interval func(), update bool, start time.Time) error {
  874. s := w.current.state
  875. block, receipts, err := w.engine.FinalizeAndAssemble(w.chain, types.CopyHeader(w.current.header), s, w.current.txs, uncles, w.current.receipts)
  876. if err != nil {
  877. return err
  878. }
  879. if w.isRunning() {
  880. if interval != nil {
  881. interval()
  882. }
  883. select {
  884. case w.taskCh <- &task{receipts: receipts, state: s, block: block, createdAt: time.Now()}:
  885. w.unconfirmed.Shift(block.NumberU64() - 1)
  886. log.Info("Commit new mining work", "number", block.Number(), "sealhash", w.engine.SealHash(block.Header()),
  887. "uncles", len(uncles), "txs", w.current.tcount,
  888. "gas", block.GasUsed(),
  889. "elapsed", common.PrettyDuration(time.Since(start)))
  890. case <-w.exitCh:
  891. log.Info("Worker has exited")
  892. }
  893. }
  894. if update {
  895. w.updateSnapshot()
  896. }
  897. return nil
  898. }
  899. // copyReceipts makes a deep copy of the given receipts.
  900. func copyReceipts(receipts []*types.Receipt) []*types.Receipt {
  901. result := make([]*types.Receipt, len(receipts))
  902. for i, l := range receipts {
  903. cpy := *l
  904. result[i] = &cpy
  905. }
  906. return result
  907. }
  908. // postSideBlock fires a side chain event, only use it for testing.
  909. func (w *worker) postSideBlock(event core.ChainSideEvent) {
  910. select {
  911. case w.chainSideCh <- event:
  912. case <-w.exitCh:
  913. }
  914. }
  915. // totalFees computes total consumed fees in ETH. Block transactions and receipts have to have the same order.
  916. func totalFees(block *types.Block, receipts []*types.Receipt) *big.Float {
  917. feesWei := new(big.Int)
  918. for i, tx := range block.Transactions() {
  919. feesWei.Add(feesWei, new(big.Int).Mul(new(big.Int).SetUint64(receipts[i].GasUsed), tx.GasPrice()))
  920. }
  921. return new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(params.Ether)))
  922. }