worker.go 31 KB

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