worker.go 30 KB

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