worker.go 32 KB

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