worker.go 17 KB

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