worker.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. for result := range self.recv {
  256. atomic.AddInt32(&self.atWork, -1)
  257. if result == nil {
  258. continue
  259. }
  260. block := result.Block
  261. work := result.Work
  262. // Update the block hash in all logs since it is now available and not when the
  263. // receipt/log of individual transactions were created.
  264. for _, r := range work.receipts {
  265. for _, l := range r.Logs {
  266. l.BlockHash = block.Hash()
  267. }
  268. }
  269. for _, log := range work.state.Logs() {
  270. log.BlockHash = block.Hash()
  271. }
  272. stat, err := self.chain.WriteBlockWithState(block, work.receipts, work.state)
  273. if err != nil {
  274. log.Error("Failed writing block to chain", "err", err)
  275. continue
  276. }
  277. // Broadcast the block and announce chain insertion event
  278. self.mux.Post(core.NewMinedBlockEvent{Block: block})
  279. var (
  280. events []interface{}
  281. logs = work.state.Logs()
  282. )
  283. events = append(events, core.ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
  284. if stat == core.CanonStatTy {
  285. events = append(events, core.ChainHeadEvent{Block: block})
  286. }
  287. self.chain.PostChainEvents(events, logs)
  288. // Insert the block into the set of pending ones to wait for confirmations
  289. self.unconfirmed.Insert(block.NumberU64(), block.Hash())
  290. }
  291. }
  292. }
  293. // push sends a new work task to currently live miner agents.
  294. func (self *worker) push(work *Work) {
  295. if atomic.LoadInt32(&self.mining) != 1 {
  296. return
  297. }
  298. for agent := range self.agents {
  299. atomic.AddInt32(&self.atWork, 1)
  300. if ch := agent.Work(); ch != nil {
  301. ch <- work
  302. }
  303. }
  304. }
  305. // makeCurrent creates a new environment for the current cycle.
  306. func (self *worker) makeCurrent(parent *types.Block, header *types.Header) error {
  307. state, err := self.chain.StateAt(parent.Root())
  308. if err != nil {
  309. return err
  310. }
  311. work := &Work{
  312. config: self.config,
  313. signer: types.NewEIP155Signer(self.config.ChainID),
  314. state: state,
  315. ancestors: set.New(),
  316. family: set.New(),
  317. uncles: set.New(),
  318. header: header,
  319. createdAt: time.Now(),
  320. }
  321. // when 08 is processed ancestors contain 07 (quick block)
  322. for _, ancestor := range self.chain.GetBlocksFromHash(parent.Hash(), 7) {
  323. for _, uncle := range ancestor.Uncles() {
  324. work.family.Add(uncle.Hash())
  325. }
  326. work.family.Add(ancestor.Hash())
  327. work.ancestors.Add(ancestor.Hash())
  328. }
  329. // Keep track of transactions which return errors so they can be removed
  330. work.tcount = 0
  331. self.current = work
  332. return nil
  333. }
  334. func (self *worker) commitNewWork() {
  335. self.mu.Lock()
  336. defer self.mu.Unlock()
  337. self.uncleMu.Lock()
  338. defer self.uncleMu.Unlock()
  339. self.currentMu.Lock()
  340. defer self.currentMu.Unlock()
  341. tstart := time.Now()
  342. parent := self.chain.CurrentBlock()
  343. tstamp := tstart.Unix()
  344. if parent.Time().Cmp(new(big.Int).SetInt64(tstamp)) >= 0 {
  345. tstamp = parent.Time().Int64() + 1
  346. }
  347. // this will ensure we're not going off too far in the future
  348. if now := time.Now().Unix(); tstamp > now+1 {
  349. wait := time.Duration(tstamp-now) * time.Second
  350. log.Info("Mining too far in the future", "wait", common.PrettyDuration(wait))
  351. time.Sleep(wait)
  352. }
  353. num := parent.Number()
  354. header := &types.Header{
  355. ParentHash: parent.Hash(),
  356. Number: num.Add(num, common.Big1),
  357. GasLimit: core.CalcGasLimit(parent),
  358. Extra: self.extra,
  359. Time: big.NewInt(tstamp),
  360. }
  361. // Only set the coinbase if we are mining (avoid spurious block rewards)
  362. if atomic.LoadInt32(&self.mining) == 1 {
  363. header.Coinbase = self.coinbase
  364. }
  365. if err := self.engine.Prepare(self.chain, header); err != nil {
  366. log.Error("Failed to prepare header for mining", "err", err)
  367. return
  368. }
  369. // If we are care about TheDAO hard-fork check whether to override the extra-data or not
  370. if daoBlock := self.config.DAOForkBlock; daoBlock != nil {
  371. // Check whether the block is among the fork extra-override range
  372. limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
  373. if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
  374. // Depending whether we support or oppose the fork, override differently
  375. if self.config.DAOForkSupport {
  376. header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
  377. } else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
  378. header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
  379. }
  380. }
  381. }
  382. // Could potentially happen if starting to mine in an odd state.
  383. err := self.makeCurrent(parent, header)
  384. if err != nil {
  385. log.Error("Failed to create mining context", "err", err)
  386. return
  387. }
  388. // Create the current work task and check any fork transitions needed
  389. work := self.current
  390. if self.config.DAOForkSupport && self.config.DAOForkBlock != nil && self.config.DAOForkBlock.Cmp(header.Number) == 0 {
  391. misc.ApplyDAOHardFork(work.state)
  392. }
  393. pending, err := self.eth.TxPool().Pending()
  394. if err != nil {
  395. log.Error("Failed to fetch pending transactions", "err", err)
  396. return
  397. }
  398. txs := types.NewTransactionsByPriceAndNonce(self.current.signer, pending)
  399. work.commitTransactions(self.mux, txs, self.chain, self.coinbase)
  400. // compute uncles for the new block.
  401. var (
  402. uncles []*types.Header
  403. badUncles []common.Hash
  404. )
  405. for hash, uncle := range self.possibleUncles {
  406. if len(uncles) == 2 {
  407. break
  408. }
  409. if err := self.commitUncle(work, uncle.Header()); err != nil {
  410. log.Trace("Bad uncle found and will be removed", "hash", hash)
  411. log.Trace(fmt.Sprint(uncle))
  412. badUncles = append(badUncles, hash)
  413. } else {
  414. log.Debug("Committing new uncle to block", "hash", hash)
  415. uncles = append(uncles, uncle.Header())
  416. }
  417. }
  418. for _, hash := range badUncles {
  419. delete(self.possibleUncles, hash)
  420. }
  421. // Create the new block to seal with the consensus engine
  422. if work.Block, err = self.engine.Finalize(self.chain, header, work.state, work.txs, uncles, work.receipts); err != nil {
  423. log.Error("Failed to finalize block for sealing", "err", err)
  424. return
  425. }
  426. // We only care about logging if we're actually mining.
  427. if atomic.LoadInt32(&self.mining) == 1 {
  428. log.Info("Commit new mining work", "number", work.Block.Number(), "txs", work.tcount, "uncles", len(uncles), "elapsed", common.PrettyDuration(time.Since(tstart)))
  429. self.unconfirmed.Shift(work.Block.NumberU64() - 1)
  430. }
  431. self.push(work)
  432. self.updateSnapshot()
  433. }
  434. func (self *worker) commitUncle(work *Work, uncle *types.Header) error {
  435. hash := uncle.Hash()
  436. if work.uncles.Has(hash) {
  437. return fmt.Errorf("uncle not unique")
  438. }
  439. if !work.ancestors.Has(uncle.ParentHash) {
  440. return fmt.Errorf("uncle's parent unknown (%x)", uncle.ParentHash[0:4])
  441. }
  442. if work.family.Has(hash) {
  443. return fmt.Errorf("uncle already in family (%x)", hash)
  444. }
  445. work.uncles.Add(uncle.Hash())
  446. return nil
  447. }
  448. func (self *worker) updateSnapshot() {
  449. self.snapshotMu.Lock()
  450. defer self.snapshotMu.Unlock()
  451. self.snapshotBlock = types.NewBlock(
  452. self.current.header,
  453. self.current.txs,
  454. nil,
  455. self.current.receipts,
  456. )
  457. self.snapshotState = self.current.state.Copy()
  458. }
  459. func (env *Work) commitTransactions(mux *event.TypeMux, txs *types.TransactionsByPriceAndNonce, bc *core.BlockChain, coinbase common.Address) {
  460. if env.gasPool == nil {
  461. env.gasPool = new(core.GasPool).AddGas(env.header.GasLimit)
  462. }
  463. var coalescedLogs []*types.Log
  464. for {
  465. // If we don't have enough gas for any further transactions then we're done
  466. if env.gasPool.Gas() < params.TxGas {
  467. log.Trace("Not enough gas for further transactions", "have", env.gasPool, "want", params.TxGas)
  468. break
  469. }
  470. // Retrieve the next transaction and abort if all done
  471. tx := txs.Peek()
  472. if tx == nil {
  473. break
  474. }
  475. // Error may be ignored here. The error has already been checked
  476. // during transaction acceptance is the transaction pool.
  477. //
  478. // We use the eip155 signer regardless of the current hf.
  479. from, _ := types.Sender(env.signer, tx)
  480. // Check whether the tx is replay protected. If we're not in the EIP155 hf
  481. // phase, start ignoring the sender until we do.
  482. if tx.Protected() && !env.config.IsEIP155(env.header.Number) {
  483. log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block)
  484. txs.Pop()
  485. continue
  486. }
  487. // Start executing the transaction
  488. env.state.Prepare(tx.Hash(), common.Hash{}, env.tcount)
  489. err, logs := env.commitTransaction(tx, bc, coinbase, env.gasPool)
  490. switch err {
  491. case core.ErrGasLimitReached:
  492. // Pop the current out-of-gas transaction without shifting in the next from the account
  493. log.Trace("Gas limit exceeded for current block", "sender", from)
  494. txs.Pop()
  495. case core.ErrNonceTooLow:
  496. // New head notification data race between the transaction pool and miner, shift
  497. log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
  498. txs.Shift()
  499. case core.ErrNonceTooHigh:
  500. // Reorg notification data race between the transaction pool and miner, skip account =
  501. log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce())
  502. txs.Pop()
  503. case nil:
  504. // Everything ok, collect the logs and shift in the next transaction from the same account
  505. coalescedLogs = append(coalescedLogs, logs...)
  506. env.tcount++
  507. txs.Shift()
  508. default:
  509. // Strange error, discard the transaction and get the next in line (note, the
  510. // nonce-too-high clause will prevent us from executing in vain).
  511. log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
  512. txs.Shift()
  513. }
  514. }
  515. if len(coalescedLogs) > 0 || env.tcount > 0 {
  516. // make a copy, the state caches the logs and these logs get "upgraded" from pending to mined
  517. // logs by filling in the block hash when the block was mined by the local miner. This can
  518. // cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed.
  519. cpy := make([]*types.Log, len(coalescedLogs))
  520. for i, l := range coalescedLogs {
  521. cpy[i] = new(types.Log)
  522. *cpy[i] = *l
  523. }
  524. go func(logs []*types.Log, tcount int) {
  525. if len(logs) > 0 {
  526. mux.Post(core.PendingLogsEvent{Logs: logs})
  527. }
  528. if tcount > 0 {
  529. mux.Post(core.PendingStateEvent{})
  530. }
  531. }(cpy, env.tcount)
  532. }
  533. }
  534. func (env *Work) commitTransaction(tx *types.Transaction, bc *core.BlockChain, coinbase common.Address, gp *core.GasPool) (error, []*types.Log) {
  535. snap := env.state.Snapshot()
  536. receipt, _, err := core.ApplyTransaction(env.config, bc, &coinbase, gp, env.state, env.header, tx, &env.header.GasUsed, vm.Config{})
  537. if err != nil {
  538. env.state.RevertToSnapshot(snap)
  539. return err, nil
  540. }
  541. env.txs = append(env.txs, tx)
  542. env.receipts = append(env.receipts, receipt)
  543. return nil, receipt.Logs
  544. }