worker.go 18 KB

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