worker.go 18 KB

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