worker.go 33 KB

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