worker.go 25 KB

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