worker.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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. defer timer.Stop()
  254. <-timer.C // discard the initial tick
  255. // commit aborts in-flight transaction execution with given signal and resubmits a new one.
  256. commit := func(noempty bool, s int32) {
  257. if interrupt != nil {
  258. atomic.StoreInt32(interrupt, s)
  259. }
  260. interrupt = new(int32)
  261. w.newWorkCh <- &newWorkReq{interrupt: interrupt, noempty: noempty, timestamp: timestamp}
  262. timer.Reset(recommit)
  263. atomic.StoreInt32(&w.newTxs, 0)
  264. }
  265. // recalcRecommit recalculates the resubmitting interval upon feedback.
  266. recalcRecommit := func(target float64, inc bool) {
  267. var (
  268. prev = float64(recommit.Nanoseconds())
  269. next float64
  270. )
  271. if inc {
  272. next = prev*(1-intervalAdjustRatio) + intervalAdjustRatio*(target+intervalAdjustBias)
  273. // Recap if interval is larger than the maximum time interval
  274. if next > float64(maxRecommitInterval.Nanoseconds()) {
  275. next = float64(maxRecommitInterval.Nanoseconds())
  276. }
  277. } else {
  278. next = prev*(1-intervalAdjustRatio) + intervalAdjustRatio*(target-intervalAdjustBias)
  279. // Recap if interval is less than the user specified minimum
  280. if next < float64(minRecommit.Nanoseconds()) {
  281. next = float64(minRecommit.Nanoseconds())
  282. }
  283. }
  284. recommit = time.Duration(int64(next))
  285. }
  286. // clearPending cleans the stale pending tasks.
  287. clearPending := func(number uint64) {
  288. w.pendingMu.Lock()
  289. for h, t := range w.pendingTasks {
  290. if t.block.NumberU64()+staleThreshold <= number {
  291. delete(w.pendingTasks, h)
  292. }
  293. }
  294. w.pendingMu.Unlock()
  295. }
  296. for {
  297. select {
  298. case <-w.startCh:
  299. clearPending(w.chain.CurrentBlock().NumberU64())
  300. timestamp = time.Now().Unix()
  301. commit(false, commitInterruptNewHead)
  302. case head := <-w.chainHeadCh:
  303. clearPending(head.Block.NumberU64())
  304. timestamp = time.Now().Unix()
  305. commit(false, commitInterruptNewHead)
  306. case <-timer.C:
  307. // If mining is running resubmit a new work cycle periodically to pull in
  308. // higher priced transactions. Disable this overhead for pending blocks.
  309. if w.isRunning() && (w.chainConfig.Clique == nil || w.chainConfig.Clique.Period > 0) {
  310. // Short circuit if no new transaction arrives.
  311. if atomic.LoadInt32(&w.newTxs) == 0 {
  312. timer.Reset(recommit)
  313. continue
  314. }
  315. commit(true, commitInterruptResubmit)
  316. }
  317. case interval := <-w.resubmitIntervalCh:
  318. // Adjust resubmit interval explicitly by user.
  319. if interval < minRecommitInterval {
  320. log.Warn("Sanitizing miner recommit interval", "provided", interval, "updated", minRecommitInterval)
  321. interval = minRecommitInterval
  322. }
  323. log.Info("Miner recommit interval update", "from", minRecommit, "to", interval)
  324. minRecommit, recommit = interval, interval
  325. if w.resubmitHook != nil {
  326. w.resubmitHook(minRecommit, recommit)
  327. }
  328. case adjust := <-w.resubmitAdjustCh:
  329. // Adjust resubmit interval by feedback.
  330. if adjust.inc {
  331. before := recommit
  332. recalcRecommit(float64(recommit.Nanoseconds())/adjust.ratio, true)
  333. log.Trace("Increase miner recommit interval", "from", before, "to", recommit)
  334. } else {
  335. before := recommit
  336. recalcRecommit(float64(minRecommit.Nanoseconds()), false)
  337. log.Trace("Decrease miner recommit interval", "from", before, "to", recommit)
  338. }
  339. if w.resubmitHook != nil {
  340. w.resubmitHook(minRecommit, recommit)
  341. }
  342. case <-w.exitCh:
  343. return
  344. }
  345. }
  346. }
  347. // mainLoop is a standalone goroutine to regenerate the sealing task based on the received event.
  348. func (w *worker) mainLoop() {
  349. defer w.txsSub.Unsubscribe()
  350. defer w.chainHeadSub.Unsubscribe()
  351. defer w.chainSideSub.Unsubscribe()
  352. for {
  353. select {
  354. case req := <-w.newWorkCh:
  355. w.commitNewWork(req.interrupt, req.noempty, req.timestamp)
  356. case ev := <-w.chainSideCh:
  357. // Short circuit for duplicate side blocks
  358. if _, exist := w.localUncles[ev.Block.Hash()]; exist {
  359. continue
  360. }
  361. if _, exist := w.remoteUncles[ev.Block.Hash()]; exist {
  362. continue
  363. }
  364. // Add side block to possible uncle block set depending on the author.
  365. if w.isLocalBlock != nil && w.isLocalBlock(ev.Block) {
  366. w.localUncles[ev.Block.Hash()] = ev.Block
  367. } else {
  368. w.remoteUncles[ev.Block.Hash()] = ev.Block
  369. }
  370. // If our mining block contains less than 2 uncle blocks,
  371. // add the new uncle block if valid and regenerate a mining block.
  372. if w.isRunning() && w.current != nil && w.current.uncles.Cardinality() < 2 {
  373. start := time.Now()
  374. if err := w.commitUncle(w.current, ev.Block.Header()); err == nil {
  375. var uncles []*types.Header
  376. w.current.uncles.Each(func(item interface{}) bool {
  377. hash, ok := item.(common.Hash)
  378. if !ok {
  379. return false
  380. }
  381. uncle, exist := w.localUncles[hash]
  382. if !exist {
  383. uncle, exist = w.remoteUncles[hash]
  384. }
  385. if !exist {
  386. return false
  387. }
  388. uncles = append(uncles, uncle.Header())
  389. return false
  390. })
  391. w.commit(uncles, nil, true, start)
  392. }
  393. }
  394. case ev := <-w.txsCh:
  395. // Apply transactions to the pending state if we're not mining.
  396. //
  397. // Note all transactions received may not be continuous with transactions
  398. // already included in the current mining block. These transactions will
  399. // be automatically eliminated.
  400. if !w.isRunning() && w.current != nil {
  401. // If block is already full, abort
  402. if gp := w.current.gasPool; gp != nil && gp.Gas() < params.TxGas {
  403. continue
  404. }
  405. w.mu.RLock()
  406. coinbase := w.coinbase
  407. w.mu.RUnlock()
  408. txs := make(map[common.Address]types.Transactions)
  409. for _, tx := range ev.Txs {
  410. acc, _ := types.Sender(w.current.signer, tx)
  411. txs[acc] = append(txs[acc], tx)
  412. }
  413. txset := types.NewTransactionsByPriceAndNonce(w.current.signer, txs)
  414. tcount := w.current.tcount
  415. w.commitTransactions(txset, coinbase, nil)
  416. // Only update the snapshot if any new transactons were added
  417. // to the pending block
  418. if tcount != w.current.tcount {
  419. w.updateSnapshot()
  420. }
  421. } else {
  422. // If clique is running in dev mode(period is 0), disable
  423. // advance sealing here.
  424. if w.chainConfig.Clique != nil && w.chainConfig.Clique.Period == 0 {
  425. w.commitNewWork(nil, true, time.Now().Unix())
  426. }
  427. }
  428. atomic.AddInt32(&w.newTxs, int32(len(ev.Txs)))
  429. // System stopped
  430. case <-w.exitCh:
  431. return
  432. case <-w.txsSub.Err():
  433. return
  434. case <-w.chainHeadSub.Err():
  435. return
  436. case <-w.chainSideSub.Err():
  437. return
  438. }
  439. }
  440. }
  441. // taskLoop is a standalone goroutine to fetch sealing task from the generator and
  442. // push them to consensus engine.
  443. func (w *worker) taskLoop() {
  444. var (
  445. stopCh chan struct{}
  446. prev common.Hash
  447. )
  448. // interrupt aborts the in-flight sealing task.
  449. interrupt := func() {
  450. if stopCh != nil {
  451. close(stopCh)
  452. stopCh = nil
  453. }
  454. }
  455. for {
  456. select {
  457. case task := <-w.taskCh:
  458. if w.newTaskHook != nil {
  459. w.newTaskHook(task)
  460. }
  461. // Reject duplicate sealing work due to resubmitting.
  462. sealHash := w.engine.SealHash(task.block.Header())
  463. if sealHash == prev {
  464. continue
  465. }
  466. // Interrupt previous sealing operation
  467. interrupt()
  468. stopCh, prev = make(chan struct{}), sealHash
  469. if w.skipSealHook != nil && w.skipSealHook(task) {
  470. continue
  471. }
  472. w.pendingMu.Lock()
  473. w.pendingTasks[w.engine.SealHash(task.block.Header())] = task
  474. w.pendingMu.Unlock()
  475. if err := w.engine.Seal(w.chain, task.block, w.resultCh, stopCh); err != nil {
  476. log.Warn("Block sealing failed", "err", err)
  477. }
  478. case <-w.exitCh:
  479. interrupt()
  480. return
  481. }
  482. }
  483. }
  484. // resultLoop is a standalone goroutine to handle sealing result submitting
  485. // and flush relative data to the database.
  486. func (w *worker) resultLoop() {
  487. for {
  488. select {
  489. case block := <-w.resultCh:
  490. // Short circuit when receiving empty result.
  491. if block == nil {
  492. continue
  493. }
  494. // Short circuit when receiving duplicate result caused by resubmitting.
  495. if w.chain.HasBlock(block.Hash(), block.NumberU64()) {
  496. continue
  497. }
  498. var (
  499. sealhash = w.engine.SealHash(block.Header())
  500. hash = block.Hash()
  501. )
  502. w.pendingMu.RLock()
  503. task, exist := w.pendingTasks[sealhash]
  504. w.pendingMu.RUnlock()
  505. if !exist {
  506. log.Error("Block found but no relative pending task", "number", block.Number(), "sealhash", sealhash, "hash", hash)
  507. continue
  508. }
  509. // Different block could share same sealhash, deep copy here to prevent write-write conflict.
  510. var (
  511. receipts = make([]*types.Receipt, len(task.receipts))
  512. logs []*types.Log
  513. )
  514. for i, receipt := range task.receipts {
  515. // add block location fields
  516. receipt.BlockHash = hash
  517. receipt.BlockNumber = block.Number()
  518. receipt.TransactionIndex = uint(i)
  519. receipts[i] = new(types.Receipt)
  520. *receipts[i] = *receipt
  521. // Update the block hash in all logs since it is now available and not when the
  522. // receipt/log of individual transactions were created.
  523. for _, log := range receipt.Logs {
  524. log.BlockHash = hash
  525. }
  526. logs = append(logs, receipt.Logs...)
  527. }
  528. // Commit block and state to database.
  529. _, err := w.chain.WriteBlockWithState(block, receipts, logs, task.state, true)
  530. if err != nil {
  531. log.Error("Failed writing block to chain", "err", err)
  532. continue
  533. }
  534. log.Info("Successfully sealed new block", "number", block.Number(), "sealhash", sealhash, "hash", hash,
  535. "elapsed", common.PrettyDuration(time.Since(task.createdAt)))
  536. // Broadcast the block and announce chain insertion event
  537. w.mux.Post(core.NewMinedBlockEvent{Block: block})
  538. // Insert the block into the set of pending ones to resultLoop for confirmations
  539. w.unconfirmed.Insert(block.NumberU64(), block.Hash())
  540. case <-w.exitCh:
  541. return
  542. }
  543. }
  544. }
  545. // makeCurrent creates a new environment for the current cycle.
  546. func (w *worker) makeCurrent(parent *types.Block, header *types.Header) error {
  547. state, err := w.chain.StateAt(parent.Root())
  548. if err != nil {
  549. return err
  550. }
  551. env := &environment{
  552. signer: types.NewEIP155Signer(w.chainConfig.ChainID),
  553. state: state,
  554. ancestors: mapset.NewSet(),
  555. family: mapset.NewSet(),
  556. uncles: mapset.NewSet(),
  557. header: header,
  558. }
  559. // when 08 is processed ancestors contain 07 (quick block)
  560. for _, ancestor := range w.chain.GetBlocksFromHash(parent.Hash(), 7) {
  561. for _, uncle := range ancestor.Uncles() {
  562. env.family.Add(uncle.Hash())
  563. }
  564. env.family.Add(ancestor.Hash())
  565. env.ancestors.Add(ancestor.Hash())
  566. }
  567. // Keep track of transactions which return errors so they can be removed
  568. env.tcount = 0
  569. w.current = env
  570. return nil
  571. }
  572. // commitUncle adds the given block to uncle block set, returns error if failed to add.
  573. func (w *worker) commitUncle(env *environment, uncle *types.Header) error {
  574. hash := uncle.Hash()
  575. if env.uncles.Contains(hash) {
  576. return errors.New("uncle not unique")
  577. }
  578. if env.header.ParentHash == uncle.ParentHash {
  579. return errors.New("uncle is sibling")
  580. }
  581. if !env.ancestors.Contains(uncle.ParentHash) {
  582. return errors.New("uncle's parent unknown")
  583. }
  584. if env.family.Contains(hash) {
  585. return errors.New("uncle already included")
  586. }
  587. env.uncles.Add(uncle.Hash())
  588. return nil
  589. }
  590. // updateSnapshot updates pending snapshot block and state.
  591. // Note this function assumes the current variable is thread safe.
  592. func (w *worker) updateSnapshot() {
  593. w.snapshotMu.Lock()
  594. defer w.snapshotMu.Unlock()
  595. var uncles []*types.Header
  596. w.current.uncles.Each(func(item interface{}) bool {
  597. hash, ok := item.(common.Hash)
  598. if !ok {
  599. return false
  600. }
  601. uncle, exist := w.localUncles[hash]
  602. if !exist {
  603. uncle, exist = w.remoteUncles[hash]
  604. }
  605. if !exist {
  606. return false
  607. }
  608. uncles = append(uncles, uncle.Header())
  609. return false
  610. })
  611. w.snapshotBlock = types.NewBlock(
  612. w.current.header,
  613. w.current.txs,
  614. uncles,
  615. w.current.receipts,
  616. )
  617. w.snapshotState = w.current.state.Copy()
  618. }
  619. func (w *worker) commitTransaction(tx *types.Transaction, coinbase common.Address) ([]*types.Log, error) {
  620. snap := w.current.state.Snapshot()
  621. 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())
  622. if err != nil {
  623. w.current.state.RevertToSnapshot(snap)
  624. return nil, err
  625. }
  626. w.current.txs = append(w.current.txs, tx)
  627. w.current.receipts = append(w.current.receipts, receipt)
  628. return receipt.Logs, nil
  629. }
  630. func (w *worker) commitTransactions(txs *types.TransactionsByPriceAndNonce, coinbase common.Address, interrupt *int32) bool {
  631. // Short circuit if current is nil
  632. if w.current == nil {
  633. return true
  634. }
  635. if w.current.gasPool == nil {
  636. w.current.gasPool = new(core.GasPool).AddGas(w.current.header.GasLimit)
  637. }
  638. var coalescedLogs []*types.Log
  639. for {
  640. // In the following three cases, we will interrupt the execution of the transaction.
  641. // (1) new head block event arrival, the interrupt signal is 1
  642. // (2) worker start or restart, the interrupt signal is 1
  643. // (3) worker recreate the mining block with any newly arrived transactions, the interrupt signal is 2.
  644. // For the first two cases, the semi-finished work will be discarded.
  645. // For the third case, the semi-finished work will be submitted to the consensus engine.
  646. if interrupt != nil && atomic.LoadInt32(interrupt) != commitInterruptNone {
  647. // Notify resubmit loop to increase resubmitting interval due to too frequent commits.
  648. if atomic.LoadInt32(interrupt) == commitInterruptResubmit {
  649. ratio := float64(w.current.header.GasLimit-w.current.gasPool.Gas()) / float64(w.current.header.GasLimit)
  650. if ratio < 0.1 {
  651. ratio = 0.1
  652. }
  653. w.resubmitAdjustCh <- &intervalAdjust{
  654. ratio: ratio,
  655. inc: true,
  656. }
  657. }
  658. return atomic.LoadInt32(interrupt) == commitInterruptNewHead
  659. }
  660. // If we don't have enough gas for any further transactions then we're done
  661. if w.current.gasPool.Gas() < params.TxGas {
  662. log.Trace("Not enough gas for further transactions", "have", w.current.gasPool, "want", params.TxGas)
  663. break
  664. }
  665. // Retrieve the next transaction and abort if all done
  666. tx := txs.Peek()
  667. if tx == nil {
  668. break
  669. }
  670. // Error may be ignored here. The error has already been checked
  671. // during transaction acceptance is the transaction pool.
  672. //
  673. // We use the eip155 signer regardless of the current hf.
  674. from, _ := types.Sender(w.current.signer, tx)
  675. // Check whether the tx is replay protected. If we're not in the EIP155 hf
  676. // phase, start ignoring the sender until we do.
  677. if tx.Protected() && !w.chainConfig.IsEIP155(w.current.header.Number) {
  678. log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", w.chainConfig.EIP155Block)
  679. txs.Pop()
  680. continue
  681. }
  682. // Start executing the transaction
  683. w.current.state.Prepare(tx.Hash(), common.Hash{}, w.current.tcount)
  684. logs, err := w.commitTransaction(tx, coinbase)
  685. switch err {
  686. case core.ErrGasLimitReached:
  687. // Pop the current out-of-gas transaction without shifting in the next from the account
  688. log.Trace("Gas limit exceeded for current block", "sender", from)
  689. txs.Pop()
  690. case core.ErrNonceTooLow:
  691. // New head notification data race between the transaction pool and miner, shift
  692. log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
  693. txs.Shift()
  694. case core.ErrNonceTooHigh:
  695. // Reorg notification data race between the transaction pool and miner, skip account =
  696. log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce())
  697. txs.Pop()
  698. case nil:
  699. // Everything ok, collect the logs and shift in the next transaction from the same account
  700. coalescedLogs = append(coalescedLogs, logs...)
  701. w.current.tcount++
  702. txs.Shift()
  703. default:
  704. // Strange error, discard the transaction and get the next in line (note, the
  705. // nonce-too-high clause will prevent us from executing in vain).
  706. log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
  707. txs.Shift()
  708. }
  709. }
  710. if !w.isRunning() && len(coalescedLogs) > 0 {
  711. // We don't push the pendingLogsEvent while we are mining. The reason is that
  712. // when we are mining, the worker will regenerate a mining block every 3 seconds.
  713. // In order to avoid pushing the repeated pendingLog, we disable the pending log pushing.
  714. // make a copy, the state caches the logs and these logs get "upgraded" from pending to mined
  715. // logs by filling in the block hash when the block was mined by the local miner. This can
  716. // cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed.
  717. cpy := make([]*types.Log, len(coalescedLogs))
  718. for i, l := range coalescedLogs {
  719. cpy[i] = new(types.Log)
  720. *cpy[i] = *l
  721. }
  722. w.pendingLogsFeed.Send(cpy)
  723. }
  724. // Notify resubmit loop to decrease resubmitting interval if current interval is larger
  725. // than the user-specified one.
  726. if interrupt != nil {
  727. w.resubmitAdjustCh <- &intervalAdjust{inc: false}
  728. }
  729. return false
  730. }
  731. // commitNewWork generates several new sealing tasks based on the parent block.
  732. func (w *worker) commitNewWork(interrupt *int32, noempty bool, timestamp int64) {
  733. w.mu.RLock()
  734. defer w.mu.RUnlock()
  735. tstart := time.Now()
  736. parent := w.chain.CurrentBlock()
  737. if parent.Time() >= uint64(timestamp) {
  738. timestamp = int64(parent.Time() + 1)
  739. }
  740. // this will ensure we're not going off too far in the future
  741. if now := time.Now().Unix(); timestamp > now+1 {
  742. wait := time.Duration(timestamp-now) * time.Second
  743. log.Info("Mining too far in the future", "wait", common.PrettyDuration(wait))
  744. time.Sleep(wait)
  745. }
  746. num := parent.Number()
  747. header := &types.Header{
  748. ParentHash: parent.Hash(),
  749. Number: num.Add(num, common.Big1),
  750. GasLimit: core.CalcGasLimit(parent, w.config.GasFloor, w.config.GasCeil),
  751. Extra: w.extra,
  752. Time: uint64(timestamp),
  753. }
  754. // Only set the coinbase if our consensus engine is running (avoid spurious block rewards)
  755. if w.isRunning() {
  756. if w.coinbase == (common.Address{}) {
  757. log.Error("Refusing to mine without etherbase")
  758. return
  759. }
  760. header.Coinbase = w.coinbase
  761. }
  762. if err := w.engine.Prepare(w.chain, header); err != nil {
  763. log.Error("Failed to prepare header for mining", "err", err)
  764. return
  765. }
  766. // If we are care about TheDAO hard-fork check whether to override the extra-data or not
  767. if daoBlock := w.chainConfig.DAOForkBlock; daoBlock != nil {
  768. // Check whether the block is among the fork extra-override range
  769. limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
  770. if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
  771. // Depending whether we support or oppose the fork, override differently
  772. if w.chainConfig.DAOForkSupport {
  773. header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
  774. } else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
  775. header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
  776. }
  777. }
  778. }
  779. // Could potentially happen if starting to mine in an odd state.
  780. err := w.makeCurrent(parent, header)
  781. if err != nil {
  782. log.Error("Failed to create mining context", "err", err)
  783. return
  784. }
  785. // Create the current work task and check any fork transitions needed
  786. env := w.current
  787. if w.chainConfig.DAOForkSupport && w.chainConfig.DAOForkBlock != nil && w.chainConfig.DAOForkBlock.Cmp(header.Number) == 0 {
  788. misc.ApplyDAOHardFork(env.state)
  789. }
  790. // Accumulate the uncles for the current block
  791. uncles := make([]*types.Header, 0, 2)
  792. commitUncles := func(blocks map[common.Hash]*types.Block) {
  793. // Clean up stale uncle blocks first
  794. for hash, uncle := range blocks {
  795. if uncle.NumberU64()+staleThreshold <= header.Number.Uint64() {
  796. delete(blocks, hash)
  797. }
  798. }
  799. for hash, uncle := range blocks {
  800. if len(uncles) == 2 {
  801. break
  802. }
  803. if err := w.commitUncle(env, uncle.Header()); err != nil {
  804. log.Trace("Possible uncle rejected", "hash", hash, "reason", err)
  805. } else {
  806. log.Debug("Committing new uncle to block", "hash", hash)
  807. uncles = append(uncles, uncle.Header())
  808. }
  809. }
  810. }
  811. // Prefer to locally generated uncle
  812. commitUncles(w.localUncles)
  813. commitUncles(w.remoteUncles)
  814. if !noempty {
  815. // Create an empty block based on temporary copied state for sealing in advance without waiting block
  816. // execution finished.
  817. w.commit(uncles, nil, false, tstart)
  818. }
  819. // Fill the block with all available pending transactions.
  820. pending, err := w.eth.TxPool().Pending()
  821. if err != nil {
  822. log.Error("Failed to fetch pending transactions", "err", err)
  823. return
  824. }
  825. // Short circuit if there is no available pending transactions
  826. if len(pending) == 0 {
  827. w.updateSnapshot()
  828. return
  829. }
  830. // Split the pending transactions into locals and remotes
  831. localTxs, remoteTxs := make(map[common.Address]types.Transactions), pending
  832. for _, account := range w.eth.TxPool().Locals() {
  833. if txs := remoteTxs[account]; len(txs) > 0 {
  834. delete(remoteTxs, account)
  835. localTxs[account] = txs
  836. }
  837. }
  838. if len(localTxs) > 0 {
  839. txs := types.NewTransactionsByPriceAndNonce(w.current.signer, localTxs)
  840. if w.commitTransactions(txs, w.coinbase, interrupt) {
  841. return
  842. }
  843. }
  844. if len(remoteTxs) > 0 {
  845. txs := types.NewTransactionsByPriceAndNonce(w.current.signer, remoteTxs)
  846. if w.commitTransactions(txs, w.coinbase, interrupt) {
  847. return
  848. }
  849. }
  850. w.commit(uncles, w.fullTaskHook, true, tstart)
  851. }
  852. // commit runs any post-transaction state modifications, assembles the final block
  853. // and commits new work if consensus engine is running.
  854. func (w *worker) commit(uncles []*types.Header, interval func(), update bool, start time.Time) error {
  855. // Deep copy receipts here to avoid interaction between different tasks.
  856. receipts := make([]*types.Receipt, len(w.current.receipts))
  857. for i, l := range w.current.receipts {
  858. receipts[i] = new(types.Receipt)
  859. *receipts[i] = *l
  860. }
  861. s := w.current.state.Copy()
  862. block, err := w.engine.FinalizeAndAssemble(w.chain, w.current.header, s, w.current.txs, uncles, w.current.receipts)
  863. if err != nil {
  864. return err
  865. }
  866. if w.isRunning() {
  867. if interval != nil {
  868. interval()
  869. }
  870. select {
  871. case w.taskCh <- &task{receipts: receipts, state: s, block: block, createdAt: time.Now()}:
  872. w.unconfirmed.Shift(block.NumberU64() - 1)
  873. feesWei := new(big.Int)
  874. for i, tx := range block.Transactions() {
  875. feesWei.Add(feesWei, new(big.Int).Mul(new(big.Int).SetUint64(receipts[i].GasUsed), tx.GasPrice()))
  876. }
  877. feesEth := new(big.Float).Quo(new(big.Float).SetInt(feesWei), new(big.Float).SetInt(big.NewInt(params.Ether)))
  878. log.Info("Commit new mining work", "number", block.Number(), "sealhash", w.engine.SealHash(block.Header()),
  879. "uncles", len(uncles), "txs", w.current.tcount, "gas", block.GasUsed(), "fees", feesEth, "elapsed", common.PrettyDuration(time.Since(start)))
  880. case <-w.exitCh:
  881. log.Info("Worker has exited")
  882. }
  883. }
  884. if update {
  885. w.updateSnapshot()
  886. }
  887. return nil
  888. }
  889. // postSideBlock fires a side chain event, only use it for testing.
  890. func (w *worker) postSideBlock(event core.ChainSideEvent) {
  891. select {
  892. case w.chainSideCh <- event:
  893. case <-w.exitCh:
  894. }
  895. }