worker.go 33 KB

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