worker.go 34 KB

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