worker.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/consensus"
  26. "github.com/ethereum/go-ethereum/consensus/misc"
  27. "github.com/ethereum/go-ethereum/core"
  28. "github.com/ethereum/go-ethereum/core/state"
  29. "github.com/ethereum/go-ethereum/core/types"
  30. "github.com/ethereum/go-ethereum/core/vm"
  31. "github.com/ethereum/go-ethereum/ethdb"
  32. "github.com/ethereum/go-ethereum/event"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/params"
  35. "gopkg.in/fatih/set.v0"
  36. )
  37. const (
  38. resultQueueSize = 10
  39. miningLogAtDepth = 5
  40. // txChanSize is the size of channel listening to NewTxsEvent.
  41. // The number is referenced from the size of tx pool.
  42. txChanSize = 4096
  43. // chainHeadChanSize is the size of channel listening to ChainHeadEvent.
  44. chainHeadChanSize = 10
  45. // chainSideChanSize is the size of channel listening to ChainSideEvent.
  46. chainSideChanSize = 10
  47. )
  48. // Agent can register themself with the worker
  49. type Agent interface {
  50. Work() chan<- *Work
  51. SetReturnCh(chan<- *Result)
  52. Stop()
  53. Start()
  54. GetHashRate() int64
  55. }
  56. // Work is the workers current environment and holds
  57. // all of the current state information
  58. type Work struct {
  59. config *params.ChainConfig
  60. signer types.Signer
  61. state *state.StateDB // apply state changes here
  62. ancestors *set.Set // ancestor set (used for checking uncle parent validity)
  63. family *set.Set // family set (used for checking uncle invalidity)
  64. uncles *set.Set // uncle set
  65. tcount int // tx count in cycle
  66. gasPool *core.GasPool // available gas used to pack transactions
  67. Block *types.Block // the new block
  68. header *types.Header
  69. txs []*types.Transaction
  70. receipts []*types.Receipt
  71. createdAt time.Time
  72. }
  73. type Result struct {
  74. Work *Work
  75. Block *types.Block
  76. }
  77. // worker is the main object which takes care of applying messages to the new state
  78. type worker struct {
  79. config *params.ChainConfig
  80. engine consensus.Engine
  81. mu sync.Mutex
  82. // update loop
  83. mux *event.TypeMux
  84. txsCh chan core.NewTxsEvent
  85. txsSub event.Subscription
  86. chainHeadCh chan core.ChainHeadEvent
  87. chainHeadSub event.Subscription
  88. chainSideCh chan core.ChainSideEvent
  89. chainSideSub event.Subscription
  90. wg sync.WaitGroup
  91. agents map[Agent]struct{}
  92. recv chan *Result
  93. eth Backend
  94. chain *core.BlockChain
  95. proc core.Validator
  96. chainDb ethdb.Database
  97. coinbase common.Address
  98. extra []byte
  99. currentMu sync.Mutex
  100. current *Work
  101. snapshotMu sync.RWMutex
  102. snapshotBlock *types.Block
  103. snapshotState *state.StateDB
  104. uncleMu sync.Mutex
  105. possibleUncles map[common.Hash]*types.Block
  106. unconfirmed *unconfirmedBlocks // set of locally mined blocks pending canonicalness confirmations
  107. // atomic status counters
  108. mining int32
  109. atWork int32
  110. }
  111. func newWorker(config *params.ChainConfig, engine consensus.Engine, coinbase common.Address, eth Backend, mux *event.TypeMux) *worker {
  112. worker := &worker{
  113. config: config,
  114. engine: engine,
  115. eth: eth,
  116. mux: mux,
  117. txsCh: make(chan core.NewTxsEvent, txChanSize),
  118. chainHeadCh: make(chan core.ChainHeadEvent, chainHeadChanSize),
  119. chainSideCh: make(chan core.ChainSideEvent, chainSideChanSize),
  120. chainDb: eth.ChainDb(),
  121. recv: make(chan *Result, resultQueueSize),
  122. chain: eth.BlockChain(),
  123. proc: eth.BlockChain().Validator(),
  124. possibleUncles: make(map[common.Hash]*types.Block),
  125. coinbase: coinbase,
  126. agents: make(map[Agent]struct{}),
  127. unconfirmed: newUnconfirmedBlocks(eth.BlockChain(), miningLogAtDepth),
  128. }
  129. // Subscribe NewTxsEvent for tx pool
  130. worker.txsSub = eth.TxPool().SubscribeNewTxsEvent(worker.txsCh)
  131. // Subscribe events for blockchain
  132. worker.chainHeadSub = eth.BlockChain().SubscribeChainHeadEvent(worker.chainHeadCh)
  133. worker.chainSideSub = eth.BlockChain().SubscribeChainSideEvent(worker.chainSideCh)
  134. go worker.update()
  135. go worker.wait()
  136. worker.commitNewWork()
  137. return worker
  138. }
  139. func (self *worker) setEtherbase(addr common.Address) {
  140. self.mu.Lock()
  141. defer self.mu.Unlock()
  142. self.coinbase = addr
  143. }
  144. func (self *worker) setExtra(extra []byte) {
  145. self.mu.Lock()
  146. defer self.mu.Unlock()
  147. self.extra = extra
  148. }
  149. func (self *worker) pending() (*types.Block, *state.StateDB) {
  150. if atomic.LoadInt32(&self.mining) == 0 {
  151. // return a snapshot to avoid contention on currentMu mutex
  152. self.snapshotMu.RLock()
  153. defer self.snapshotMu.RUnlock()
  154. return self.snapshotBlock, self.snapshotState.Copy()
  155. }
  156. self.currentMu.Lock()
  157. defer self.currentMu.Unlock()
  158. return self.current.Block, self.current.state.Copy()
  159. }
  160. func (self *worker) pendingBlock() *types.Block {
  161. if atomic.LoadInt32(&self.mining) == 0 {
  162. // return a snapshot to avoid contention on currentMu mutex
  163. self.snapshotMu.RLock()
  164. defer self.snapshotMu.RUnlock()
  165. return self.snapshotBlock
  166. }
  167. self.currentMu.Lock()
  168. defer self.currentMu.Unlock()
  169. return self.current.Block
  170. }
  171. func (self *worker) start() {
  172. self.mu.Lock()
  173. defer self.mu.Unlock()
  174. atomic.StoreInt32(&self.mining, 1)
  175. // spin up agents
  176. for agent := range self.agents {
  177. agent.Start()
  178. }
  179. }
  180. func (self *worker) stop() {
  181. self.wg.Wait()
  182. self.mu.Lock()
  183. defer self.mu.Unlock()
  184. if atomic.LoadInt32(&self.mining) == 1 {
  185. for agent := range self.agents {
  186. agent.Stop()
  187. }
  188. }
  189. atomic.StoreInt32(&self.mining, 0)
  190. atomic.StoreInt32(&self.atWork, 0)
  191. }
  192. func (self *worker) register(agent Agent) {
  193. self.mu.Lock()
  194. defer self.mu.Unlock()
  195. self.agents[agent] = struct{}{}
  196. agent.SetReturnCh(self.recv)
  197. }
  198. func (self *worker) unregister(agent Agent) {
  199. self.mu.Lock()
  200. defer self.mu.Unlock()
  201. delete(self.agents, agent)
  202. agent.Stop()
  203. }
  204. func (self *worker) update() {
  205. defer self.txsSub.Unsubscribe()
  206. defer self.chainHeadSub.Unsubscribe()
  207. defer self.chainSideSub.Unsubscribe()
  208. for {
  209. // A real event arrived, process interesting content
  210. select {
  211. // Handle ChainHeadEvent
  212. case <-self.chainHeadCh:
  213. self.commitNewWork()
  214. // Handle ChainSideEvent
  215. case ev := <-self.chainSideCh:
  216. self.uncleMu.Lock()
  217. self.possibleUncles[ev.Block.Hash()] = ev.Block
  218. self.uncleMu.Unlock()
  219. // Handle NewTxsEvent
  220. case ev := <-self.txsCh:
  221. // Apply transactions to the pending state if we're not mining.
  222. //
  223. // Note all transactions received may not be continuous with transactions
  224. // already included in the current mining block. These transactions will
  225. // be automatically eliminated.
  226. if atomic.LoadInt32(&self.mining) == 0 {
  227. self.currentMu.Lock()
  228. txs := make(map[common.Address]types.Transactions)
  229. for _, tx := range ev.Txs {
  230. acc, _ := types.Sender(self.current.signer, tx)
  231. txs[acc] = append(txs[acc], tx)
  232. }
  233. txset := types.NewTransactionsByPriceAndNonce(self.current.signer, txs)
  234. self.current.commitTransactions(self.mux, txset, self.chain, self.coinbase)
  235. self.updateSnapshot()
  236. self.currentMu.Unlock()
  237. } else {
  238. // If we're mining, but nothing is being processed, wake on new transactions
  239. if self.config.Clique != nil && self.config.Clique.Period == 0 {
  240. self.commitNewWork()
  241. }
  242. }
  243. // System stopped
  244. case <-self.txsSub.Err():
  245. return
  246. case <-self.chainHeadSub.Err():
  247. return
  248. case <-self.chainSideSub.Err():
  249. return
  250. }
  251. }
  252. }
  253. func (self *worker) wait() {
  254. for {
  255. mustCommitNewWork := true
  256. for result := range self.recv {
  257. atomic.AddInt32(&self.atWork, -1)
  258. if result == nil {
  259. continue
  260. }
  261. block := result.Block
  262. work := result.Work
  263. // Update the block hash in all logs since it is now available and not when the
  264. // receipt/log of individual transactions were created.
  265. for _, r := range work.receipts {
  266. for _, l := range r.Logs {
  267. l.BlockHash = block.Hash()
  268. }
  269. }
  270. for _, log := range work.state.Logs() {
  271. log.BlockHash = block.Hash()
  272. }
  273. stat, err := self.chain.WriteBlockWithState(block, work.receipts, work.state)
  274. if err != nil {
  275. log.Error("Failed writing block to chain", "err", err)
  276. continue
  277. }
  278. // check if canon block and write transactions
  279. if stat == core.CanonStatTy {
  280. // implicit by posting ChainHeadEvent
  281. mustCommitNewWork = false
  282. }
  283. // Broadcast the block and announce chain insertion event
  284. self.mux.Post(core.NewMinedBlockEvent{Block: block})
  285. var (
  286. events []interface{}
  287. logs = work.state.Logs()
  288. )
  289. events = append(events, core.ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
  290. if stat == core.CanonStatTy {
  291. events = append(events, core.ChainHeadEvent{Block: block})
  292. }
  293. self.chain.PostChainEvents(events, logs)
  294. // Insert the block into the set of pending ones to wait for confirmations
  295. self.unconfirmed.Insert(block.NumberU64(), block.Hash())
  296. if mustCommitNewWork {
  297. self.commitNewWork()
  298. }
  299. }
  300. }
  301. }
  302. // push sends a new work task to currently live miner agents.
  303. func (self *worker) push(work *Work) {
  304. if atomic.LoadInt32(&self.mining) != 1 {
  305. return
  306. }
  307. for agent := range self.agents {
  308. atomic.AddInt32(&self.atWork, 1)
  309. if ch := agent.Work(); ch != nil {
  310. ch <- work
  311. }
  312. }
  313. }
  314. // makeCurrent creates a new environment for the current cycle.
  315. func (self *worker) makeCurrent(parent *types.Block, header *types.Header) error {
  316. state, err := self.chain.StateAt(parent.Root())
  317. if err != nil {
  318. return err
  319. }
  320. work := &Work{
  321. config: self.config,
  322. signer: types.NewEIP155Signer(self.config.ChainId),
  323. state: state,
  324. ancestors: set.New(),
  325. family: set.New(),
  326. uncles: set.New(),
  327. header: header,
  328. createdAt: time.Now(),
  329. }
  330. // when 08 is processed ancestors contain 07 (quick block)
  331. for _, ancestor := range self.chain.GetBlocksFromHash(parent.Hash(), 7) {
  332. for _, uncle := range ancestor.Uncles() {
  333. work.family.Add(uncle.Hash())
  334. }
  335. work.family.Add(ancestor.Hash())
  336. work.ancestors.Add(ancestor.Hash())
  337. }
  338. // Keep track of transactions which return errors so they can be removed
  339. work.tcount = 0
  340. self.current = work
  341. return nil
  342. }
  343. func (self *worker) commitNewWork() {
  344. self.mu.Lock()
  345. defer self.mu.Unlock()
  346. self.uncleMu.Lock()
  347. defer self.uncleMu.Unlock()
  348. self.currentMu.Lock()
  349. defer self.currentMu.Unlock()
  350. tstart := time.Now()
  351. parent := self.chain.CurrentBlock()
  352. tstamp := tstart.Unix()
  353. if parent.Time().Cmp(new(big.Int).SetInt64(tstamp)) >= 0 {
  354. tstamp = parent.Time().Int64() + 1
  355. }
  356. // this will ensure we're not going off too far in the future
  357. if now := time.Now().Unix(); tstamp > now+1 {
  358. wait := time.Duration(tstamp-now) * time.Second
  359. log.Info("Mining too far in the future", "wait", common.PrettyDuration(wait))
  360. time.Sleep(wait)
  361. }
  362. num := parent.Number()
  363. header := &types.Header{
  364. ParentHash: parent.Hash(),
  365. Number: num.Add(num, common.Big1),
  366. GasLimit: core.CalcGasLimit(parent),
  367. Extra: self.extra,
  368. Time: big.NewInt(tstamp),
  369. }
  370. // Only set the coinbase if we are mining (avoid spurious block rewards)
  371. if atomic.LoadInt32(&self.mining) == 1 {
  372. header.Coinbase = self.coinbase
  373. }
  374. if err := self.engine.Prepare(self.chain, header); err != nil {
  375. log.Error("Failed to prepare header for mining", "err", err)
  376. return
  377. }
  378. // If we are care about TheDAO hard-fork check whether to override the extra-data or not
  379. if daoBlock := self.config.DAOForkBlock; daoBlock != nil {
  380. // Check whether the block is among the fork extra-override range
  381. limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
  382. if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
  383. // Depending whether we support or oppose the fork, override differently
  384. if self.config.DAOForkSupport {
  385. header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
  386. } else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
  387. header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
  388. }
  389. }
  390. }
  391. // Could potentially happen if starting to mine in an odd state.
  392. err := self.makeCurrent(parent, header)
  393. if err != nil {
  394. log.Error("Failed to create mining context", "err", err)
  395. return
  396. }
  397. // Create the current work task and check any fork transitions needed
  398. work := self.current
  399. if self.config.DAOForkSupport && self.config.DAOForkBlock != nil && self.config.DAOForkBlock.Cmp(header.Number) == 0 {
  400. misc.ApplyDAOHardFork(work.state)
  401. }
  402. pending, err := self.eth.TxPool().Pending()
  403. if err != nil {
  404. log.Error("Failed to fetch pending transactions", "err", err)
  405. return
  406. }
  407. txs := types.NewTransactionsByPriceAndNonce(self.current.signer, pending)
  408. work.commitTransactions(self.mux, txs, self.chain, self.coinbase)
  409. // compute uncles for the new block.
  410. var (
  411. uncles []*types.Header
  412. badUncles []common.Hash
  413. )
  414. for hash, uncle := range self.possibleUncles {
  415. if len(uncles) == 2 {
  416. break
  417. }
  418. if err := self.commitUncle(work, uncle.Header()); err != nil {
  419. log.Trace("Bad uncle found and will be removed", "hash", hash)
  420. log.Trace(fmt.Sprint(uncle))
  421. badUncles = append(badUncles, hash)
  422. } else {
  423. log.Debug("Committing new uncle to block", "hash", hash)
  424. uncles = append(uncles, uncle.Header())
  425. }
  426. }
  427. for _, hash := range badUncles {
  428. delete(self.possibleUncles, hash)
  429. }
  430. // Create the new block to seal with the consensus engine
  431. if work.Block, err = self.engine.Finalize(self.chain, header, work.state, work.txs, uncles, work.receipts); err != nil {
  432. log.Error("Failed to finalize block for sealing", "err", err)
  433. return
  434. }
  435. // We only care about logging if we're actually mining.
  436. if atomic.LoadInt32(&self.mining) == 1 {
  437. log.Info("Commit new mining work", "number", work.Block.Number(), "txs", work.tcount, "uncles", len(uncles), "elapsed", common.PrettyDuration(time.Since(tstart)))
  438. self.unconfirmed.Shift(work.Block.NumberU64() - 1)
  439. }
  440. self.push(work)
  441. self.updateSnapshot()
  442. }
  443. func (self *worker) commitUncle(work *Work, uncle *types.Header) error {
  444. hash := uncle.Hash()
  445. if work.uncles.Has(hash) {
  446. return fmt.Errorf("uncle not unique")
  447. }
  448. if !work.ancestors.Has(uncle.ParentHash) {
  449. return fmt.Errorf("uncle's parent unknown (%x)", uncle.ParentHash[0:4])
  450. }
  451. if work.family.Has(hash) {
  452. return fmt.Errorf("uncle already in family (%x)", hash)
  453. }
  454. work.uncles.Add(uncle.Hash())
  455. return nil
  456. }
  457. func (self *worker) updateSnapshot() {
  458. self.snapshotMu.Lock()
  459. defer self.snapshotMu.Unlock()
  460. self.snapshotBlock = types.NewBlock(
  461. self.current.header,
  462. self.current.txs,
  463. nil,
  464. self.current.receipts,
  465. )
  466. self.snapshotState = self.current.state.Copy()
  467. }
  468. func (env *Work) commitTransactions(mux *event.TypeMux, txs *types.TransactionsByPriceAndNonce, bc *core.BlockChain, coinbase common.Address) {
  469. if env.gasPool == nil {
  470. env.gasPool = new(core.GasPool).AddGas(env.header.GasLimit)
  471. }
  472. var coalescedLogs []*types.Log
  473. for {
  474. // If we don't have enough gas for any further transactions then we're done
  475. if env.gasPool.Gas() < params.TxGas {
  476. log.Trace("Not enough gas for further transactions", "have", env.gasPool, "want", params.TxGas)
  477. break
  478. }
  479. // Retrieve the next transaction and abort if all done
  480. tx := txs.Peek()
  481. if tx == nil {
  482. break
  483. }
  484. // Error may be ignored here. The error has already been checked
  485. // during transaction acceptance is the transaction pool.
  486. //
  487. // We use the eip155 signer regardless of the current hf.
  488. from, _ := types.Sender(env.signer, tx)
  489. // Check whether the tx is replay protected. If we're not in the EIP155 hf
  490. // phase, start ignoring the sender until we do.
  491. if tx.Protected() && !env.config.IsEIP155(env.header.Number) {
  492. log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block)
  493. txs.Pop()
  494. continue
  495. }
  496. // Start executing the transaction
  497. env.state.Prepare(tx.Hash(), common.Hash{}, env.tcount)
  498. err, logs := env.commitTransaction(tx, bc, coinbase, env.gasPool)
  499. switch err {
  500. case core.ErrGasLimitReached:
  501. // Pop the current out-of-gas transaction without shifting in the next from the account
  502. log.Trace("Gas limit exceeded for current block", "sender", from)
  503. txs.Pop()
  504. case core.ErrNonceTooLow:
  505. // New head notification data race between the transaction pool and miner, shift
  506. log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
  507. txs.Shift()
  508. case core.ErrNonceTooHigh:
  509. // Reorg notification data race between the transaction pool and miner, skip account =
  510. log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce())
  511. txs.Pop()
  512. case nil:
  513. // Everything ok, collect the logs and shift in the next transaction from the same account
  514. coalescedLogs = append(coalescedLogs, logs...)
  515. env.tcount++
  516. txs.Shift()
  517. default:
  518. // Strange error, discard the transaction and get the next in line (note, the
  519. // nonce-too-high clause will prevent us from executing in vain).
  520. log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
  521. txs.Shift()
  522. }
  523. }
  524. if len(coalescedLogs) > 0 || env.tcount > 0 {
  525. // make a copy, the state caches the logs and these logs get "upgraded" from pending to mined
  526. // logs by filling in the block hash when the block was mined by the local miner. This can
  527. // cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed.
  528. cpy := make([]*types.Log, len(coalescedLogs))
  529. for i, l := range coalescedLogs {
  530. cpy[i] = new(types.Log)
  531. *cpy[i] = *l
  532. }
  533. go func(logs []*types.Log, tcount int) {
  534. if len(logs) > 0 {
  535. mux.Post(core.PendingLogsEvent{Logs: logs})
  536. }
  537. if tcount > 0 {
  538. mux.Post(core.PendingStateEvent{})
  539. }
  540. }(cpy, env.tcount)
  541. }
  542. }
  543. func (env *Work) commitTransaction(tx *types.Transaction, bc *core.BlockChain, coinbase common.Address, gp *core.GasPool) (error, []*types.Log) {
  544. snap := env.state.Snapshot()
  545. receipt, _, err := core.ApplyTransaction(env.config, bc, &coinbase, gp, env.state, env.header, tx, &env.header.GasUsed, vm.Config{})
  546. if err != nil {
  547. env.state.RevertToSnapshot(snap)
  548. return err, nil
  549. }
  550. env.txs = append(env.txs, tx)
  551. env.receipts = append(env.receipts, receipt)
  552. return nil, receipt.Logs
  553. }