worker.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. if p, ok := w.engine.(*parlia.Parlia); ok {
  338. signedRecent, err := p.SignRecently(w.chain, head.Block.Header())
  339. if err != nil {
  340. log.Info("Not allowed to propose block", "err", err)
  341. continue
  342. }
  343. if signedRecent {
  344. log.Info("Signed recently, must wait")
  345. continue
  346. }
  347. }
  348. commit(true, commitInterruptNewHead)
  349. case <-timer.C:
  350. // If mining is running resubmit a new work cycle periodically to pull in
  351. // higher priced transactions. Disable this overhead for pending blocks.
  352. if w.isRunning() && ((w.chainConfig.Ethash != nil) || (w.chainConfig.Clique != nil &&
  353. w.chainConfig.Clique.Period > 0) || (w.chainConfig.Parlia != nil && w.chainConfig.Parlia.Period > 0)) {
  354. // Short circuit if no new transaction arrives.
  355. if atomic.LoadInt32(&w.newTxs) == 0 {
  356. timer.Reset(recommit)
  357. continue
  358. }
  359. commit(true, commitInterruptResubmit)
  360. }
  361. case interval := <-w.resubmitIntervalCh:
  362. // Adjust resubmit interval explicitly by user.
  363. if interval < minRecommitInterval {
  364. log.Warn("Sanitizing miner recommit interval", "provided", interval, "updated", minRecommitInterval)
  365. interval = minRecommitInterval
  366. }
  367. log.Info("Miner recommit interval update", "from", minRecommit, "to", interval)
  368. minRecommit, recommit = interval, interval
  369. if w.resubmitHook != nil {
  370. w.resubmitHook(minRecommit, recommit)
  371. }
  372. case adjust := <-w.resubmitAdjustCh:
  373. // Adjust resubmit interval by feedback.
  374. if adjust.inc {
  375. before := recommit
  376. target := float64(recommit.Nanoseconds()) / adjust.ratio
  377. recommit = recalcRecommit(minRecommit, recommit, target, true)
  378. log.Trace("Increase miner recommit interval", "from", before, "to", recommit)
  379. } else {
  380. before := recommit
  381. recommit = recalcRecommit(minRecommit, recommit, float64(minRecommit.Nanoseconds()), false)
  382. log.Trace("Decrease miner recommit interval", "from", before, "to", recommit)
  383. }
  384. if w.resubmitHook != nil {
  385. w.resubmitHook(minRecommit, recommit)
  386. }
  387. case <-w.exitCh:
  388. return
  389. }
  390. }
  391. }
  392. // mainLoop is a standalone goroutine to regenerate the sealing task based on the received event.
  393. func (w *worker) mainLoop() {
  394. defer w.txsSub.Unsubscribe()
  395. defer w.chainHeadSub.Unsubscribe()
  396. defer w.chainSideSub.Unsubscribe()
  397. for {
  398. select {
  399. case req := <-w.newWorkCh:
  400. w.commitNewWork(req.interrupt, req.noempty, req.timestamp)
  401. case ev := <-w.chainSideCh:
  402. // Short circuit for duplicate side blocks
  403. if _, ok := w.engine.(*parlia.Parlia); ok {
  404. continue
  405. }
  406. if _, exist := w.localUncles[ev.Block.Hash()]; exist {
  407. continue
  408. }
  409. if _, exist := w.remoteUncles[ev.Block.Hash()]; exist {
  410. continue
  411. }
  412. // Add side block to possible uncle block set depending on the author.
  413. if w.isLocalBlock != nil && w.isLocalBlock(ev.Block) {
  414. w.localUncles[ev.Block.Hash()] = ev.Block
  415. } else {
  416. w.remoteUncles[ev.Block.Hash()] = ev.Block
  417. }
  418. // If our mining block contains less than 2 uncle blocks,
  419. // add the new uncle block if valid and regenerate a mining block.
  420. if w.isRunning() && w.current != nil && w.current.uncles.Cardinality() < 2 {
  421. start := time.Now()
  422. if err := w.commitUncle(w.current, ev.Block.Header()); err == nil {
  423. var uncles []*types.Header
  424. w.commit(uncles, nil, false, start)
  425. }
  426. }
  427. case ev := <-w.txsCh:
  428. // Apply transactions to the pending state if we're not mining.
  429. //
  430. // Note all transactions received may not be continuous with transactions
  431. // already included in the current mining block. These transactions will
  432. // be automatically eliminated.
  433. if !w.isRunning() && w.current != nil {
  434. // If block is already full, abort
  435. if gp := w.current.gasPool; gp != nil && gp.Gas() < params.TxGas {
  436. continue
  437. }
  438. w.mu.RLock()
  439. coinbase := w.coinbase
  440. w.mu.RUnlock()
  441. txs := make(map[common.Address]types.Transactions)
  442. for _, tx := range ev.Txs {
  443. acc, _ := types.Sender(w.current.signer, tx)
  444. txs[acc] = append(txs[acc], tx)
  445. }
  446. txset := types.NewTransactionsByPriceAndNonce(w.current.signer, txs)
  447. tcount := w.current.tcount
  448. w.commitTransactions(txset, coinbase, nil)
  449. // Only update the snapshot if any new transactons were added
  450. // to the pending block
  451. if tcount != w.current.tcount {
  452. w.updateSnapshot()
  453. }
  454. } else {
  455. // Special case, if the consensus engine is 0 period clique(dev mode),
  456. // submit mining work here since all empty submission will be rejected
  457. // by clique. Of course the advance sealing(empty submission) is disabled.
  458. if (w.chainConfig.Clique != nil && w.chainConfig.Clique.Period == 0) ||
  459. (w.chainConfig.Parlia != nil && w.chainConfig.Parlia.Period == 0) {
  460. w.commitNewWork(nil, true, time.Now().Unix())
  461. }
  462. }
  463. atomic.AddInt32(&w.newTxs, int32(len(ev.Txs)))
  464. // System stopped
  465. case <-w.exitCh:
  466. return
  467. case <-w.txsSub.Err():
  468. return
  469. case <-w.chainHeadSub.Err():
  470. return
  471. case <-w.chainSideSub.Err():
  472. return
  473. }
  474. }
  475. }
  476. // taskLoop is a standalone goroutine to fetch sealing task from the generator and
  477. // push them to consensus engine.
  478. func (w *worker) taskLoop() {
  479. var (
  480. stopCh chan struct{}
  481. prev common.Hash
  482. )
  483. // interrupt aborts the in-flight sealing task.
  484. interrupt := func() {
  485. if stopCh != nil {
  486. close(stopCh)
  487. stopCh = nil
  488. }
  489. }
  490. for {
  491. select {
  492. case task := <-w.taskCh:
  493. if w.newTaskHook != nil {
  494. w.newTaskHook(task)
  495. }
  496. // Reject duplicate sealing work due to resubmitting.
  497. sealHash := w.engine.SealHash(task.block.Header())
  498. if sealHash == prev {
  499. continue
  500. }
  501. // Interrupt previous sealing operation
  502. interrupt()
  503. stopCh, prev = make(chan struct{}), sealHash
  504. if w.skipSealHook != nil && w.skipSealHook(task) {
  505. continue
  506. }
  507. w.pendingMu.Lock()
  508. w.pendingTasks[sealHash] = task
  509. w.pendingMu.Unlock()
  510. if err := w.engine.Seal(w.chain, task.block, w.resultCh, stopCh); err != nil {
  511. log.Warn("Block sealing failed", "err", err)
  512. }
  513. case <-w.exitCh:
  514. interrupt()
  515. return
  516. }
  517. }
  518. }
  519. // resultLoop is a standalone goroutine to handle sealing result submitting
  520. // and flush relative data to the database.
  521. func (w *worker) resultLoop() {
  522. for {
  523. select {
  524. case block := <-w.resultCh:
  525. // Short circuit when receiving empty result.
  526. if block == nil {
  527. continue
  528. }
  529. // Short circuit when receiving duplicate result caused by resubmitting.
  530. if w.chain.HasBlock(block.Hash(), block.NumberU64()) {
  531. continue
  532. }
  533. var (
  534. sealhash = w.engine.SealHash(block.Header())
  535. hash = block.Hash()
  536. )
  537. w.pendingMu.RLock()
  538. task, exist := w.pendingTasks[sealhash]
  539. w.pendingMu.RUnlock()
  540. if !exist {
  541. log.Error("Block found but no relative pending task", "number", block.Number(), "sealhash", sealhash, "hash", hash)
  542. continue
  543. }
  544. // Different block could share same sealhash, deep copy here to prevent write-write conflict.
  545. var (
  546. receipts = make([]*types.Receipt, len(task.receipts))
  547. logs []*types.Log
  548. )
  549. for i, receipt := range task.receipts {
  550. // add block location fields
  551. receipt.BlockHash = hash
  552. receipt.BlockNumber = block.Number()
  553. receipt.TransactionIndex = uint(i)
  554. receipts[i] = new(types.Receipt)
  555. *receipts[i] = *receipt
  556. // Update the block hash in all logs since it is now available and not when the
  557. // receipt/log of individual transactions were created.
  558. for _, log := range receipt.Logs {
  559. log.BlockHash = hash
  560. }
  561. logs = append(logs, receipt.Logs...)
  562. }
  563. // Commit block and state to database.
  564. _, err := w.chain.WriteBlockWithState(block, receipts, logs, task.state, true)
  565. if err != nil {
  566. log.Error("Failed writing block to chain", "err", err)
  567. continue
  568. }
  569. log.Info("Successfully sealed new block", "number", block.Number(), "sealhash", sealhash, "hash", hash,
  570. "elapsed", common.PrettyDuration(time.Since(task.createdAt)))
  571. // Broadcast the block and announce chain insertion event
  572. w.mux.Post(core.NewMinedBlockEvent{Block: block})
  573. // Insert the block into the set of pending ones to resultLoop for confirmations
  574. w.unconfirmed.Insert(block.NumberU64(), block.Hash())
  575. case <-w.exitCh:
  576. return
  577. }
  578. }
  579. }
  580. // makeCurrent creates a new environment for the current cycle.
  581. func (w *worker) makeCurrent(parent *types.Block, header *types.Header) error {
  582. // Retrieve the parent state to execute on top and start a prefetcher for
  583. // the miner to speed block sealing up a bit
  584. state, err := w.chain.StateAt(parent.Root())
  585. if err != nil {
  586. return err
  587. }
  588. state.StartPrefetcher("miner")
  589. env := &environment{
  590. signer: types.MakeSigner(w.chainConfig, header.Number),
  591. state: state,
  592. ancestors: mapset.NewSet(),
  593. family: mapset.NewSet(),
  594. uncles: mapset.NewSet(),
  595. header: header,
  596. }
  597. // Keep track of transactions which return errors so they can be removed
  598. env.tcount = 0
  599. // Swap out the old work with the new one, terminating any leftover prefetcher
  600. // processes in the mean time and starting a new one.
  601. if w.current != nil && w.current.state != nil {
  602. w.current.state.StopPrefetcher()
  603. }
  604. w.current = env
  605. return nil
  606. }
  607. // commitUncle adds the given block to uncle block set, returns error if failed to add.
  608. func (w *worker) commitUncle(env *environment, uncle *types.Header) error {
  609. hash := uncle.Hash()
  610. if env.uncles.Contains(hash) {
  611. return errors.New("uncle not unique")
  612. }
  613. if env.header.ParentHash == uncle.ParentHash {
  614. return errors.New("uncle is sibling")
  615. }
  616. if !env.ancestors.Contains(uncle.ParentHash) {
  617. return errors.New("uncle's parent unknown")
  618. }
  619. if env.family.Contains(hash) {
  620. return errors.New("uncle already included")
  621. }
  622. env.uncles.Add(uncle.Hash())
  623. return nil
  624. }
  625. // updateSnapshot updates pending snapshot block and state.
  626. // Note this function assumes the current variable is thread safe.
  627. func (w *worker) updateSnapshot() {
  628. w.snapshotMu.Lock()
  629. defer w.snapshotMu.Unlock()
  630. var uncles []*types.Header
  631. w.current.uncles.Each(func(item interface{}) bool {
  632. hash, ok := item.(common.Hash)
  633. if !ok {
  634. return false
  635. }
  636. uncle, exist := w.localUncles[hash]
  637. if !exist {
  638. uncle, exist = w.remoteUncles[hash]
  639. }
  640. if !exist {
  641. return false
  642. }
  643. uncles = append(uncles, uncle.Header())
  644. return false
  645. })
  646. w.snapshotBlock = types.NewBlock(
  647. w.current.header,
  648. w.current.txs,
  649. uncles,
  650. w.current.receipts,
  651. trie.NewStackTrie(nil),
  652. )
  653. w.snapshotState = w.current.state.Copy()
  654. }
  655. func (w *worker) commitTransaction(tx *types.Transaction, coinbase common.Address) ([]*types.Log, error) {
  656. snap := w.current.state.Snapshot()
  657. 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())
  658. if err != nil {
  659. w.current.state.RevertToSnapshot(snap)
  660. return nil, err
  661. }
  662. w.current.txs = append(w.current.txs, tx)
  663. w.current.receipts = append(w.current.receipts, receipt)
  664. return receipt.Logs, nil
  665. }
  666. func (w *worker) commitTransactions(txs *types.TransactionsByPriceAndNonce, coinbase common.Address, interrupt *int32) bool {
  667. // Short circuit if current is nil
  668. if w.current == nil {
  669. return true
  670. }
  671. if w.current.gasPool == nil {
  672. w.current.gasPool = new(core.GasPool).AddGas(w.current.header.GasLimit)
  673. w.current.gasPool.SubGas(params.SystemTxsGas)
  674. }
  675. var coalescedLogs []*types.Log
  676. var stopTimer *time.Timer
  677. delay := w.engine.Delay(w.chain, w.current.header)
  678. if delay != nil {
  679. stopTimer = time.NewTimer(*delay - w.config.DelayLeftOver)
  680. log.Debug("Time left for mining work", "left", (*delay - w.config.DelayLeftOver).String(), "leftover", w.config.DelayLeftOver)
  681. defer stopTimer.Stop()
  682. }
  683. LOOP:
  684. for {
  685. // In the following three cases, we will interrupt the execution of the transaction.
  686. // (1) new head block event arrival, the interrupt signal is 1
  687. // (2) worker start or restart, the interrupt signal is 1
  688. // (3) worker recreate the mining block with any newly arrived transactions, the interrupt signal is 2.
  689. // For the first two cases, the semi-finished work will be discarded.
  690. // For the third case, the semi-finished work will be submitted to the consensus engine.
  691. if interrupt != nil && atomic.LoadInt32(interrupt) != commitInterruptNone {
  692. // Notify resubmit loop to increase resubmitting interval due to too frequent commits.
  693. if atomic.LoadInt32(interrupt) == commitInterruptResubmit {
  694. ratio := float64(w.current.header.GasLimit-w.current.gasPool.Gas()) / float64(w.current.header.GasLimit)
  695. if ratio < 0.1 {
  696. ratio = 0.1
  697. }
  698. w.resubmitAdjustCh <- &intervalAdjust{
  699. ratio: ratio,
  700. inc: true,
  701. }
  702. }
  703. return atomic.LoadInt32(interrupt) == commitInterruptNewHead
  704. }
  705. // If we don't have enough gas for any further transactions then we're done
  706. if w.current.gasPool.Gas() < params.TxGas {
  707. log.Trace("Not enough gas for further transactions", "have", w.current.gasPool, "want", params.TxGas)
  708. break
  709. }
  710. if stopTimer != nil {
  711. select {
  712. case <-stopTimer.C:
  713. log.Info("Not enough time for further transactions", "txs", len(w.current.txs))
  714. break LOOP
  715. default:
  716. }
  717. }
  718. // Retrieve the next transaction and abort if all done
  719. tx := txs.Peek()
  720. if tx == nil {
  721. break
  722. }
  723. // Error may be ignored here. The error has already been checked
  724. // during transaction acceptance is the transaction pool.
  725. //
  726. // We use the eip155 signer regardless of the current hf.
  727. //from, _ := types.Sender(w.current.signer, tx)
  728. // Check whether the tx is replay protected. If we're not in the EIP155 hf
  729. // phase, start ignoring the sender until we do.
  730. if tx.Protected() && !w.chainConfig.IsEIP155(w.current.header.Number) {
  731. //log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", w.chainConfig.EIP155Block)
  732. txs.Pop()
  733. continue
  734. }
  735. // Start executing the transaction
  736. w.current.state.Prepare(tx.Hash(), common.Hash{}, w.current.tcount)
  737. logs, err := w.commitTransaction(tx, coinbase)
  738. switch {
  739. case errors.Is(err, core.ErrGasLimitReached):
  740. // Pop the current out-of-gas transaction without shifting in the next from the account
  741. //log.Trace("Gas limit exceeded for current block", "sender", from)
  742. txs.Pop()
  743. case errors.Is(err, core.ErrNonceTooLow):
  744. // New head notification data race between the transaction pool and miner, shift
  745. //log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
  746. txs.Shift()
  747. case errors.Is(err, core.ErrNonceTooHigh):
  748. // Reorg notification data race between the transaction pool and miner, skip account =
  749. //log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce())
  750. txs.Pop()
  751. case errors.Is(err, nil):
  752. // Everything ok, collect the logs and shift in the next transaction from the same account
  753. coalescedLogs = append(coalescedLogs, logs...)
  754. w.current.tcount++
  755. txs.Shift()
  756. case errors.Is(err, core.ErrTxTypeNotSupported):
  757. // Pop the unsupported transaction without shifting in the next from the account
  758. //log.Trace("Skipping unsupported transaction type", "sender", from, "type", tx.Type())
  759. txs.Pop()
  760. default:
  761. // Strange error, discard the transaction and get the next in line (note, the
  762. // nonce-too-high clause will prevent us from executing in vain).
  763. //log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
  764. txs.Shift()
  765. }
  766. }
  767. if !w.isRunning() && len(coalescedLogs) > 0 {
  768. // We don't push the pendingLogsEvent while we are mining. The reason is that
  769. // when we are mining, the worker will regenerate a mining block every 3 seconds.
  770. // In order to avoid pushing the repeated pendingLog, we disable the pending log pushing.
  771. // make a copy, the state caches the logs and these logs get "upgraded" from pending to mined
  772. // logs by filling in the block hash when the block was mined by the local miner. This can
  773. // cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed.
  774. cpy := make([]*types.Log, len(coalescedLogs))
  775. for i, l := range coalescedLogs {
  776. cpy[i] = new(types.Log)
  777. *cpy[i] = *l
  778. }
  779. w.pendingLogsFeed.Send(cpy)
  780. }
  781. // Notify resubmit loop to decrease resubmitting interval if current interval is larger
  782. // than the user-specified one.
  783. if interrupt != nil {
  784. w.resubmitAdjustCh <- &intervalAdjust{inc: false}
  785. }
  786. return false
  787. }
  788. // commitNewWork generates several new sealing tasks based on the parent block.
  789. func (w *worker) commitNewWork(interrupt *int32, noempty bool, timestamp int64) {
  790. w.mu.RLock()
  791. defer w.mu.RUnlock()
  792. tstart := time.Now()
  793. parent := w.chain.CurrentBlock()
  794. if parent.Time() >= uint64(timestamp) {
  795. timestamp = int64(parent.Time() + 1)
  796. }
  797. num := parent.Number()
  798. header := &types.Header{
  799. ParentHash: parent.Hash(),
  800. Number: num.Add(num, common.Big1),
  801. GasLimit: core.CalcGasLimit(parent, w.config.GasFloor, w.config.GasCeil),
  802. Extra: w.extra,
  803. Time: uint64(timestamp),
  804. }
  805. // Only set the coinbase if our consensus engine is running (avoid spurious block rewards)
  806. if w.isRunning() {
  807. if w.coinbase == (common.Address{}) {
  808. log.Error("Refusing to mine without etherbase")
  809. return
  810. }
  811. header.Coinbase = w.coinbase
  812. }
  813. if err := w.engine.Prepare(w.chain, header); err != nil {
  814. log.Error("Failed to prepare header for mining", "err", err)
  815. return
  816. }
  817. // If we are care about TheDAO hard-fork check whether to override the extra-data or not
  818. if daoBlock := w.chainConfig.DAOForkBlock; daoBlock != nil {
  819. // Check whether the block is among the fork extra-override range
  820. limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
  821. if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
  822. // Depending whether we support or oppose the fork, override differently
  823. if w.chainConfig.DAOForkSupport {
  824. header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
  825. } else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
  826. header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
  827. }
  828. }
  829. }
  830. // Could potentially happen if starting to mine in an odd state.
  831. err := w.makeCurrent(parent, header)
  832. if err != nil {
  833. log.Error("Failed to create mining context", "err", err)
  834. return
  835. }
  836. // Create the current work task and check any fork transitions needed
  837. env := w.current
  838. if w.chainConfig.DAOForkSupport && w.chainConfig.DAOForkBlock != nil && w.chainConfig.DAOForkBlock.Cmp(header.Number) == 0 {
  839. misc.ApplyDAOHardFork(env.state)
  840. }
  841. systemcontracts.UpgradeBuildInSystemContract(w.chainConfig, header.Number, env.state)
  842. // Accumulate the uncles for the current block
  843. uncles := make([]*types.Header, 0)
  844. // Create an empty block based on temporary copied state for
  845. // sealing in advance without waiting block execution finished.
  846. if !noempty && atomic.LoadUint32(&w.noempty) == 0 {
  847. w.commit(uncles, nil, false, tstart)
  848. }
  849. // Fill the block with all available pending transactions.
  850. pending, err := w.eth.TxPool().Pending()
  851. if err != nil {
  852. log.Error("Failed to fetch pending transactions", "err", err)
  853. }
  854. // Short circuit if there is no available pending transactions
  855. if len(pending) != 0 {
  856. start := time.Now()
  857. // Split the pending transactions into locals and remotes
  858. localTxs, remoteTxs := make(map[common.Address]types.Transactions), pending
  859. for _, account := range w.eth.TxPool().Locals() {
  860. if txs := remoteTxs[account]; len(txs) > 0 {
  861. delete(remoteTxs, account)
  862. localTxs[account] = txs
  863. }
  864. }
  865. if len(localTxs) > 0 {
  866. txs := types.NewTransactionsByPriceAndNonce(w.current.signer, localTxs)
  867. if w.commitTransactions(txs, w.coinbase, interrupt) {
  868. return
  869. }
  870. }
  871. if len(remoteTxs) > 0 {
  872. txs := types.NewTransactionsByPriceAndNonce(w.current.signer, remoteTxs)
  873. if w.commitTransactions(txs, w.coinbase, interrupt) {
  874. return
  875. }
  876. }
  877. commitTxsTimer.UpdateSince(start)
  878. log.Info("Gas pool", "height", header.Number.String(), "pool", w.current.gasPool.String())
  879. }
  880. w.commit(uncles, w.fullTaskHook, false, tstart)
  881. }
  882. // commit runs any post-transaction state modifications, assembles the final block
  883. // and commits new work if consensus engine is running.
  884. func (w *worker) commit(uncles []*types.Header, interval func(), update bool, start time.Time) error {
  885. s := w.current.state
  886. block, receipts, err := w.engine.FinalizeAndAssemble(w.chain, types.CopyHeader(w.current.header), s, w.current.txs, uncles, w.current.receipts)
  887. if err != nil {
  888. return err
  889. }
  890. if w.isRunning() {
  891. if interval != nil {
  892. interval()
  893. }
  894. select {
  895. case w.taskCh <- &task{receipts: receipts, state: s, block: block, createdAt: time.Now()}:
  896. w.unconfirmed.Shift(block.NumberU64() - 1)
  897. log.Info("Commit new mining work", "number", block.Number(), "sealhash", w.engine.SealHash(block.Header()),
  898. "uncles", len(uncles), "txs", w.current.tcount,
  899. "gas", block.GasUsed(),
  900. "elapsed", common.PrettyDuration(time.Since(start)))
  901. case <-w.exitCh:
  902. log.Info("Worker has exited")
  903. }
  904. }
  905. if update {
  906. w.updateSnapshot()
  907. }
  908. return nil
  909. }
  910. // postSideBlock fires a side chain event, only use it for testing.
  911. func (w *worker) postSideBlock(event core.ChainSideEvent) {
  912. select {
  913. case w.chainSideCh <- event:
  914. case <-w.exitCh:
  915. }
  916. }