worker.go 34 KB

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