worker.go 18 KB

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