worker.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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. }
  107. func newWorker(config *params.ChainConfig, engine consensus.Engine, coinbase common.Address, eth Backend, mux *event.TypeMux) *worker {
  108. worker := &worker{
  109. config: config,
  110. engine: engine,
  111. eth: eth,
  112. mux: mux,
  113. txCh: make(chan core.TxPreEvent, txChanSize),
  114. chainHeadCh: make(chan core.ChainHeadEvent, chainHeadChanSize),
  115. chainSideCh: make(chan core.ChainSideEvent, chainSideChanSize),
  116. chainDb: eth.ChainDb(),
  117. recv: make(chan *Result, resultQueueSize),
  118. chain: eth.BlockChain(),
  119. proc: eth.BlockChain().Validator(),
  120. possibleUncles: make(map[common.Hash]*types.Block),
  121. coinbase: coinbase,
  122. agents: make(map[Agent]struct{}),
  123. unconfirmed: newUnconfirmedBlocks(eth.BlockChain(), miningLogAtDepth),
  124. }
  125. // Subscribe TxPreEvent for tx pool
  126. worker.txSub = eth.TxPool().SubscribeTxPreEvent(worker.txCh)
  127. // Subscribe events for blockchain
  128. worker.chainHeadSub = eth.BlockChain().SubscribeChainHeadEvent(worker.chainHeadCh)
  129. worker.chainSideSub = eth.BlockChain().SubscribeChainSideEvent(worker.chainSideCh)
  130. go worker.update()
  131. go worker.wait()
  132. worker.commitNewWork()
  133. return worker
  134. }
  135. func (self *worker) setEtherbase(addr common.Address) {
  136. self.mu.Lock()
  137. defer self.mu.Unlock()
  138. self.coinbase = addr
  139. }
  140. func (self *worker) setExtra(extra []byte) {
  141. self.mu.Lock()
  142. defer self.mu.Unlock()
  143. self.extra = extra
  144. }
  145. func (self *worker) pending() (*types.Block, *state.StateDB) {
  146. self.currentMu.Lock()
  147. defer self.currentMu.Unlock()
  148. if atomic.LoadInt32(&self.mining) == 0 {
  149. return types.NewBlock(
  150. self.current.header,
  151. self.current.txs,
  152. nil,
  153. self.current.receipts,
  154. ), self.current.state.Copy()
  155. }
  156. return self.current.Block, self.current.state.Copy()
  157. }
  158. func (self *worker) pendingBlock() *types.Block {
  159. self.currentMu.Lock()
  160. defer self.currentMu.Unlock()
  161. if atomic.LoadInt32(&self.mining) == 0 {
  162. return types.NewBlock(
  163. self.current.header,
  164. self.current.txs,
  165. nil,
  166. self.current.receipts,
  167. )
  168. }
  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.txSub.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 TxPreEvent
  220. case ev := <-self.txCh:
  221. // Apply transaction to the pending state if we're not mining
  222. if atomic.LoadInt32(&self.mining) == 0 {
  223. self.currentMu.Lock()
  224. acc, _ := types.Sender(self.current.signer, ev.Tx)
  225. txs := map[common.Address]types.Transactions{acc: {ev.Tx}}
  226. txset := types.NewTransactionsByPriceAndNonce(self.current.signer, txs)
  227. self.current.commitTransactions(self.mux, txset, self.chain, self.coinbase)
  228. self.currentMu.Unlock()
  229. } else {
  230. // If we're mining, but nothing is being processed, wake on new transactions
  231. if self.config.Clique != nil && self.config.Clique.Period == 0 {
  232. self.commitNewWork()
  233. }
  234. }
  235. // System stopped
  236. case <-self.txSub.Err():
  237. return
  238. case <-self.chainHeadSub.Err():
  239. return
  240. case <-self.chainSideSub.Err():
  241. return
  242. }
  243. }
  244. }
  245. func (self *worker) wait() {
  246. for {
  247. mustCommitNewWork := true
  248. for result := range self.recv {
  249. atomic.AddInt32(&self.atWork, -1)
  250. if result == nil {
  251. continue
  252. }
  253. block := result.Block
  254. work := result.Work
  255. // Update the block hash in all logs since it is now available and not when the
  256. // receipt/log of individual transactions were created.
  257. for _, r := range work.receipts {
  258. for _, l := range r.Logs {
  259. l.BlockHash = block.Hash()
  260. }
  261. }
  262. for _, log := range work.state.Logs() {
  263. log.BlockHash = block.Hash()
  264. }
  265. stat, err := self.chain.WriteBlockAndState(block, work.receipts, work.state)
  266. if err != nil {
  267. log.Error("Failed writing block to chain", "err", err)
  268. continue
  269. }
  270. // check if canon block and write transactions
  271. if stat == core.CanonStatTy {
  272. // implicit by posting ChainHeadEvent
  273. mustCommitNewWork = false
  274. }
  275. // Broadcast the block and announce chain insertion event
  276. self.mux.Post(core.NewMinedBlockEvent{Block: block})
  277. var (
  278. events []interface{}
  279. logs = work.state.Logs()
  280. )
  281. events = append(events, core.ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
  282. if stat == core.CanonStatTy {
  283. events = append(events, core.ChainHeadEvent{Block: block})
  284. }
  285. self.chain.PostChainEvents(events, logs)
  286. // Insert the block into the set of pending ones to wait for confirmations
  287. self.unconfirmed.Insert(block.NumberU64(), block.Hash())
  288. if mustCommitNewWork {
  289. self.commitNewWork()
  290. }
  291. }
  292. }
  293. }
  294. // push sends a new work task to currently live miner agents.
  295. func (self *worker) push(work *Work) {
  296. if atomic.LoadInt32(&self.mining) != 1 {
  297. return
  298. }
  299. for agent := range self.agents {
  300. atomic.AddInt32(&self.atWork, 1)
  301. if ch := agent.Work(); ch != nil {
  302. ch <- work
  303. }
  304. }
  305. }
  306. // makeCurrent creates a new environment for the current cycle.
  307. func (self *worker) makeCurrent(parent *types.Block, header *types.Header) error {
  308. state, err := self.chain.StateAt(parent.Root())
  309. if err != nil {
  310. return err
  311. }
  312. work := &Work{
  313. config: self.config,
  314. signer: types.NewEIP155Signer(self.config.ChainId),
  315. state: state,
  316. ancestors: set.New(),
  317. family: set.New(),
  318. uncles: set.New(),
  319. header: header,
  320. createdAt: time.Now(),
  321. }
  322. // when 08 is processed ancestors contain 07 (quick block)
  323. for _, ancestor := range self.chain.GetBlocksFromHash(parent.Hash(), 7) {
  324. for _, uncle := range ancestor.Uncles() {
  325. work.family.Add(uncle.Hash())
  326. }
  327. work.family.Add(ancestor.Hash())
  328. work.ancestors.Add(ancestor.Hash())
  329. }
  330. // Keep track of transactions which return errors so they can be removed
  331. work.tcount = 0
  332. self.current = work
  333. return nil
  334. }
  335. func (self *worker) commitNewWork() {
  336. self.mu.Lock()
  337. defer self.mu.Unlock()
  338. self.uncleMu.Lock()
  339. defer self.uncleMu.Unlock()
  340. self.currentMu.Lock()
  341. defer self.currentMu.Unlock()
  342. tstart := time.Now()
  343. parent := self.chain.CurrentBlock()
  344. tstamp := tstart.Unix()
  345. if parent.Time().Cmp(new(big.Int).SetInt64(tstamp)) >= 0 {
  346. tstamp = parent.Time().Int64() + 1
  347. }
  348. // this will ensure we're not going off too far in the future
  349. if now := time.Now().Unix(); tstamp > now+1 {
  350. wait := time.Duration(tstamp-now) * time.Second
  351. log.Info("Mining too far in the future", "wait", common.PrettyDuration(wait))
  352. time.Sleep(wait)
  353. }
  354. num := parent.Number()
  355. header := &types.Header{
  356. ParentHash: parent.Hash(),
  357. Number: num.Add(num, common.Big1),
  358. GasLimit: core.CalcGasLimit(parent),
  359. Extra: self.extra,
  360. Time: big.NewInt(tstamp),
  361. }
  362. // Only set the coinbase if we are mining (avoid spurious block rewards)
  363. if atomic.LoadInt32(&self.mining) == 1 {
  364. header.Coinbase = self.coinbase
  365. }
  366. if err := self.engine.Prepare(self.chain, header); err != nil {
  367. log.Error("Failed to prepare header for mining", "err", err)
  368. return
  369. }
  370. // If we are care about TheDAO hard-fork check whether to override the extra-data or not
  371. if daoBlock := self.config.DAOForkBlock; daoBlock != nil {
  372. // Check whether the block is among the fork extra-override range
  373. limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
  374. if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
  375. // Depending whether we support or oppose the fork, override differently
  376. if self.config.DAOForkSupport {
  377. header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
  378. } else if bytes.Equal(header.Extra, params.DAOForkBlockExtra) {
  379. header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
  380. }
  381. }
  382. }
  383. // Could potentially happen if starting to mine in an odd state.
  384. err := self.makeCurrent(parent, header)
  385. if err != nil {
  386. log.Error("Failed to create mining context", "err", err)
  387. return
  388. }
  389. // Create the current work task and check any fork transitions needed
  390. work := self.current
  391. if self.config.DAOForkSupport && self.config.DAOForkBlock != nil && self.config.DAOForkBlock.Cmp(header.Number) == 0 {
  392. misc.ApplyDAOHardFork(work.state)
  393. }
  394. pending, err := self.eth.TxPool().Pending()
  395. if err != nil {
  396. log.Error("Failed to fetch pending transactions", "err", err)
  397. return
  398. }
  399. txs := types.NewTransactionsByPriceAndNonce(self.current.signer, pending)
  400. work.commitTransactions(self.mux, txs, self.chain, self.coinbase)
  401. // compute uncles for the new block.
  402. var (
  403. uncles []*types.Header
  404. badUncles []common.Hash
  405. )
  406. for hash, uncle := range self.possibleUncles {
  407. if len(uncles) == 2 {
  408. break
  409. }
  410. if err := self.commitUncle(work, uncle.Header()); err != nil {
  411. log.Trace("Bad uncle found and will be removed", "hash", hash)
  412. log.Trace(fmt.Sprint(uncle))
  413. badUncles = append(badUncles, hash)
  414. } else {
  415. log.Debug("Committing new uncle to block", "hash", hash)
  416. uncles = append(uncles, uncle.Header())
  417. }
  418. }
  419. for _, hash := range badUncles {
  420. delete(self.possibleUncles, hash)
  421. }
  422. // Create the new block to seal with the consensus engine
  423. if work.Block, err = self.engine.Finalize(self.chain, header, work.state, work.txs, uncles, work.receipts); err != nil {
  424. log.Error("Failed to finalize block for sealing", "err", err)
  425. return
  426. }
  427. // We only care about logging if we're actually mining.
  428. if atomic.LoadInt32(&self.mining) == 1 {
  429. log.Info("Commit new mining work", "number", work.Block.Number(), "txs", work.tcount, "uncles", len(uncles), "elapsed", common.PrettyDuration(time.Since(tstart)))
  430. self.unconfirmed.Shift(work.Block.NumberU64() - 1)
  431. }
  432. self.push(work)
  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 (env *Work) commitTransactions(mux *event.TypeMux, txs *types.TransactionsByPriceAndNonce, bc *core.BlockChain, coinbase common.Address) {
  449. gp := new(core.GasPool).AddGas(env.header.GasLimit)
  450. var coalescedLogs []*types.Log
  451. for {
  452. // If we don't have enough gas for any further transactions then we're done
  453. if gp.Gas() < params.TxGas {
  454. log.Trace("Not enough gas for further transactions", "gp", gp)
  455. break
  456. }
  457. // Retrieve the next transaction and abort if all done
  458. tx := txs.Peek()
  459. if tx == nil {
  460. break
  461. }
  462. // Error may be ignored here. The error has already been checked
  463. // during transaction acceptance is the transaction pool.
  464. //
  465. // We use the eip155 signer regardless of the current hf.
  466. from, _ := types.Sender(env.signer, tx)
  467. // Check whether the tx is replay protected. If we're not in the EIP155 hf
  468. // phase, start ignoring the sender until we do.
  469. if tx.Protected() && !env.config.IsEIP155(env.header.Number) {
  470. log.Trace("Ignoring reply protected transaction", "hash", tx.Hash(), "eip155", env.config.EIP155Block)
  471. txs.Pop()
  472. continue
  473. }
  474. // Start executing the transaction
  475. env.state.Prepare(tx.Hash(), common.Hash{}, env.tcount)
  476. err, logs := env.commitTransaction(tx, bc, coinbase, gp)
  477. switch err {
  478. case core.ErrGasLimitReached:
  479. // Pop the current out-of-gas transaction without shifting in the next from the account
  480. log.Trace("Gas limit exceeded for current block", "sender", from)
  481. txs.Pop()
  482. case core.ErrNonceTooLow:
  483. // New head notification data race between the transaction pool and miner, shift
  484. log.Trace("Skipping transaction with low nonce", "sender", from, "nonce", tx.Nonce())
  485. txs.Shift()
  486. case core.ErrNonceTooHigh:
  487. // Reorg notification data race between the transaction pool and miner, skip account =
  488. log.Trace("Skipping account with hight nonce", "sender", from, "nonce", tx.Nonce())
  489. txs.Pop()
  490. case nil:
  491. // Everything ok, collect the logs and shift in the next transaction from the same account
  492. coalescedLogs = append(coalescedLogs, logs...)
  493. env.tcount++
  494. txs.Shift()
  495. default:
  496. // Strange error, discard the transaction and get the next in line (note, the
  497. // nonce-too-high clause will prevent us from executing in vain).
  498. log.Debug("Transaction failed, account skipped", "hash", tx.Hash(), "err", err)
  499. txs.Shift()
  500. }
  501. }
  502. if len(coalescedLogs) > 0 || env.tcount > 0 {
  503. // make a copy, the state caches the logs and these logs get "upgraded" from pending to mined
  504. // logs by filling in the block hash when the block was mined by the local miner. This can
  505. // cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed.
  506. cpy := make([]*types.Log, len(coalescedLogs))
  507. for i, l := range coalescedLogs {
  508. cpy[i] = new(types.Log)
  509. *cpy[i] = *l
  510. }
  511. go func(logs []*types.Log, tcount int) {
  512. if len(logs) > 0 {
  513. mux.Post(core.PendingLogsEvent{Logs: logs})
  514. }
  515. if tcount > 0 {
  516. mux.Post(core.PendingStateEvent{})
  517. }
  518. }(cpy, env.tcount)
  519. }
  520. }
  521. func (env *Work) commitTransaction(tx *types.Transaction, bc *core.BlockChain, coinbase common.Address, gp *core.GasPool) (error, []*types.Log) {
  522. snap := env.state.Snapshot()
  523. receipt, _, err := core.ApplyTransaction(env.config, bc, &coinbase, gp, env.state, env.header, tx, &env.header.GasUsed, vm.Config{})
  524. if err != nil {
  525. env.state.RevertToSnapshot(snap)
  526. return err, nil
  527. }
  528. env.txs = append(env.txs, tx)
  529. env.receipts = append(env.receipts, receipt)
  530. return nil, receipt.Logs
  531. }