worker.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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/core"
  27. "github.com/ethereum/go-ethereum/core/state"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/core/vm"
  30. "github.com/ethereum/go-ethereum/ethdb"
  31. "github.com/ethereum/go-ethereum/event"
  32. "github.com/ethereum/go-ethereum/logger"
  33. "github.com/ethereum/go-ethereum/logger/glog"
  34. "github.com/ethereum/go-ethereum/params"
  35. "github.com/ethereum/go-ethereum/pow"
  36. "gopkg.in/fatih/set.v0"
  37. )
  38. var jsonlogger = logger.NewJsonLogger()
  39. const (
  40. resultQueueSize = 10
  41. miningLogAtDepth = 5
  42. )
  43. // Agent can register themself with the worker
  44. type Agent interface {
  45. Work() chan<- *Work
  46. SetReturnCh(chan<- *Result)
  47. Stop()
  48. Start()
  49. GetHashRate() int64
  50. }
  51. type uint64RingBuffer struct {
  52. ints []uint64 //array of all integers in buffer
  53. next int //where is the next insertion? assert 0 <= next < len(ints)
  54. }
  55. // Work is the workers current environment and holds
  56. // all of the current state information
  57. type Work struct {
  58. config *params.ChainConfig
  59. signer types.Signer
  60. state *state.StateDB // apply state changes here
  61. ancestors *set.Set // ancestor set (used for checking uncle parent validity)
  62. family *set.Set // family set (used for checking uncle invalidity)
  63. uncles *set.Set // uncle set
  64. tcount int // tx count in cycle
  65. ownedAccounts *set.Set
  66. lowGasTxs types.Transactions
  67. failedTxs types.Transactions
  68. localMinedBlocks *uint64RingBuffer // the most recent block numbers that were mined locally (used to check block inclusion)
  69. Block *types.Block // the new block
  70. header *types.Header
  71. txs []*types.Transaction
  72. receipts []*types.Receipt
  73. createdAt time.Time
  74. }
  75. type Result struct {
  76. Work *Work
  77. Block *types.Block
  78. }
  79. // worker is the main object which takes care of applying messages to the new state
  80. type worker struct {
  81. config *params.ChainConfig
  82. mu sync.Mutex
  83. // update loop
  84. mux *event.TypeMux
  85. events event.Subscription
  86. wg sync.WaitGroup
  87. agents map[Agent]struct{}
  88. recv chan *Result
  89. pow pow.PoW
  90. eth Backend
  91. chain *core.BlockChain
  92. proc core.Validator
  93. chainDb ethdb.Database
  94. coinbase common.Address
  95. gasPrice *big.Int
  96. extra []byte
  97. currentMu sync.Mutex
  98. current *Work
  99. uncleMu sync.Mutex
  100. possibleUncles map[common.Hash]*types.Block
  101. txQueueMu sync.Mutex
  102. txQueue map[common.Hash]*types.Transaction
  103. // atomic status counters
  104. mining int32
  105. atWork int32
  106. fullValidation bool
  107. }
  108. func newWorker(config *params.ChainConfig, coinbase common.Address, eth Backend, mux *event.TypeMux) *worker {
  109. worker := &worker{
  110. config: config,
  111. eth: eth,
  112. mux: mux,
  113. chainDb: eth.ChainDb(),
  114. recv: make(chan *Result, resultQueueSize),
  115. gasPrice: new(big.Int),
  116. chain: eth.BlockChain(),
  117. proc: eth.BlockChain().Validator(),
  118. possibleUncles: make(map[common.Hash]*types.Block),
  119. coinbase: coinbase,
  120. txQueue: make(map[common.Hash]*types.Transaction),
  121. agents: make(map[Agent]struct{}),
  122. fullValidation: false,
  123. }
  124. worker.events = worker.mux.Subscribe(core.ChainHeadEvent{}, core.ChainSideEvent{}, core.TxPreEvent{})
  125. go worker.update()
  126. go worker.wait()
  127. worker.commitNewWork()
  128. return worker
  129. }
  130. func (self *worker) setEtherbase(addr common.Address) {
  131. self.mu.Lock()
  132. defer self.mu.Unlock()
  133. self.coinbase = addr
  134. }
  135. func (self *worker) pending() (*types.Block, *state.StateDB) {
  136. self.currentMu.Lock()
  137. defer self.currentMu.Unlock()
  138. if atomic.LoadInt32(&self.mining) == 0 {
  139. return types.NewBlock(
  140. self.current.header,
  141. self.current.txs,
  142. nil,
  143. self.current.receipts,
  144. ), self.current.state.Copy()
  145. }
  146. return self.current.Block, self.current.state.Copy()
  147. }
  148. func (self *worker) pendingBlock() *types.Block {
  149. self.currentMu.Lock()
  150. defer self.currentMu.Unlock()
  151. if atomic.LoadInt32(&self.mining) == 0 {
  152. return types.NewBlock(
  153. self.current.header,
  154. self.current.txs,
  155. nil,
  156. self.current.receipts,
  157. )
  158. }
  159. return self.current.Block
  160. }
  161. func (self *worker) start() {
  162. self.mu.Lock()
  163. defer self.mu.Unlock()
  164. atomic.StoreInt32(&self.mining, 1)
  165. // spin up agents
  166. for agent := range self.agents {
  167. agent.Start()
  168. }
  169. }
  170. func (self *worker) stop() {
  171. self.wg.Wait()
  172. self.mu.Lock()
  173. defer self.mu.Unlock()
  174. if atomic.LoadInt32(&self.mining) == 1 {
  175. // Stop all agents.
  176. for agent := range self.agents {
  177. agent.Stop()
  178. // Remove CPU agents.
  179. if _, ok := agent.(*CpuAgent); ok {
  180. delete(self.agents, agent)
  181. }
  182. }
  183. }
  184. atomic.StoreInt32(&self.mining, 0)
  185. atomic.StoreInt32(&self.atWork, 0)
  186. }
  187. func (self *worker) register(agent Agent) {
  188. self.mu.Lock()
  189. defer self.mu.Unlock()
  190. self.agents[agent] = struct{}{}
  191. agent.SetReturnCh(self.recv)
  192. }
  193. func (self *worker) unregister(agent Agent) {
  194. self.mu.Lock()
  195. defer self.mu.Unlock()
  196. delete(self.agents, agent)
  197. agent.Stop()
  198. }
  199. func (self *worker) update() {
  200. for event := range self.events.Chan() {
  201. // A real event arrived, process interesting content
  202. switch ev := event.Data.(type) {
  203. case core.ChainHeadEvent:
  204. self.commitNewWork()
  205. case core.ChainSideEvent:
  206. self.uncleMu.Lock()
  207. self.possibleUncles[ev.Block.Hash()] = ev.Block
  208. self.uncleMu.Unlock()
  209. case core.TxPreEvent:
  210. // Apply transaction to the pending state if we're not mining
  211. if atomic.LoadInt32(&self.mining) == 0 {
  212. self.currentMu.Lock()
  213. acc, _ := types.Sender(self.current.signer, ev.Tx)
  214. txs := map[common.Address]types.Transactions{acc: types.Transactions{ev.Tx}}
  215. txset := types.NewTransactionsByPriceAndNonce(txs)
  216. self.current.commitTransactions(self.mux, txset, self.gasPrice, self.chain)
  217. self.currentMu.Unlock()
  218. }
  219. }
  220. }
  221. }
  222. func newLocalMinedBlock(blockNumber uint64, prevMinedBlocks *uint64RingBuffer) (minedBlocks *uint64RingBuffer) {
  223. if prevMinedBlocks == nil {
  224. minedBlocks = &uint64RingBuffer{next: 0, ints: make([]uint64, miningLogAtDepth+1)}
  225. } else {
  226. minedBlocks = prevMinedBlocks
  227. }
  228. minedBlocks.ints[minedBlocks.next] = blockNumber
  229. minedBlocks.next = (minedBlocks.next + 1) % len(minedBlocks.ints)
  230. return minedBlocks
  231. }
  232. func (self *worker) wait() {
  233. for {
  234. mustCommitNewWork := true
  235. for result := range self.recv {
  236. atomic.AddInt32(&self.atWork, -1)
  237. if result == nil {
  238. continue
  239. }
  240. block := result.Block
  241. work := result.Work
  242. if self.fullValidation {
  243. if _, err := self.chain.InsertChain(types.Blocks{block}); err != nil {
  244. glog.V(logger.Error).Infoln("mining err", err)
  245. continue
  246. }
  247. go self.mux.Post(core.NewMinedBlockEvent{Block: block})
  248. } else {
  249. work.state.Commit(self.config.IsEIP158(block.Number()))
  250. parent := self.chain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  251. if parent == nil {
  252. glog.V(logger.Error).Infoln("Invalid block found during mining")
  253. continue
  254. }
  255. auxValidator := self.eth.BlockChain().AuxValidator()
  256. if err := core.ValidateHeader(self.config, auxValidator, block.Header(), parent.Header(), true, false); err != nil && err != core.BlockFutureErr {
  257. glog.V(logger.Error).Infoln("Invalid header on mined block:", err)
  258. continue
  259. }
  260. stat, err := self.chain.WriteBlock(block)
  261. if err != nil {
  262. glog.V(logger.Error).Infoln("error writing block to chain", 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.WriteTransactions(self.chainDb, block)
  278. // store the receipts
  279. core.WriteReceipts(self.chainDb, work.receipts)
  280. // Write map map bloom filters
  281. core.WriteMipmapBloom(self.chainDb, block.NumberU64(), work.receipts)
  282. // implicit by posting ChainHeadEvent
  283. mustCommitNewWork = false
  284. }
  285. // broadcast before waiting for validation
  286. go func(block *types.Block, logs vm.Logs, receipts []*types.Receipt) {
  287. self.mux.Post(core.NewMinedBlockEvent{Block: block})
  288. self.mux.Post(core.ChainEvent{Block: block, Hash: block.Hash(), Logs: logs})
  289. if stat == core.CanonStatTy {
  290. self.mux.Post(core.ChainHeadEvent{Block: block})
  291. self.mux.Post(logs)
  292. }
  293. if err := core.WriteBlockReceipts(self.chainDb, block.Hash(), block.NumberU64(), receipts); err != nil {
  294. glog.V(logger.Warn).Infoln("error writing block receipts:", err)
  295. }
  296. }(block, work.state.Logs(), work.receipts)
  297. }
  298. // check staleness and display confirmation
  299. var stale, confirm string
  300. canonBlock := self.chain.GetBlockByNumber(block.NumberU64())
  301. if canonBlock != nil && canonBlock.Hash() != block.Hash() {
  302. stale = "stale "
  303. } else {
  304. confirm = "Wait 5 blocks for confirmation"
  305. work.localMinedBlocks = newLocalMinedBlock(block.Number().Uint64(), work.localMinedBlocks)
  306. }
  307. glog.V(logger.Info).Infof("🔨 Mined %sblock (#%v / %x). %s", stale, block.Number(), block.Hash().Bytes()[:4], confirm)
  308. if mustCommitNewWork {
  309. self.commitNewWork()
  310. }
  311. }
  312. }
  313. }
  314. // push sends a new work task to currently live miner agents.
  315. func (self *worker) push(work *Work) {
  316. if atomic.LoadInt32(&self.mining) != 1 {
  317. return
  318. }
  319. for agent := range self.agents {
  320. atomic.AddInt32(&self.atWork, 1)
  321. if ch := agent.Work(); ch != nil {
  322. ch <- work
  323. }
  324. }
  325. }
  326. // makeCurrent creates a new environment for the current cycle.
  327. func (self *worker) makeCurrent(parent *types.Block, header *types.Header) error {
  328. state, err := self.chain.StateAt(parent.Root())
  329. if err != nil {
  330. return err
  331. }
  332. work := &Work{
  333. config: self.config,
  334. signer: types.NewEIP155Signer(self.config.ChainId),
  335. state: state,
  336. ancestors: set.New(),
  337. family: set.New(),
  338. uncles: set.New(),
  339. header: header,
  340. createdAt: time.Now(),
  341. }
  342. // when 08 is processed ancestors contain 07 (quick block)
  343. for _, ancestor := range self.chain.GetBlocksFromHash(parent.Hash(), 7) {
  344. for _, uncle := range ancestor.Uncles() {
  345. work.family.Add(uncle.Hash())
  346. }
  347. work.family.Add(ancestor.Hash())
  348. work.ancestors.Add(ancestor.Hash())
  349. }
  350. accounts := self.eth.AccountManager().Accounts()
  351. // Keep track of transactions which return errors so they can be removed
  352. work.tcount = 0
  353. work.ownedAccounts = accountAddressesSet(accounts)
  354. if self.current != nil {
  355. work.localMinedBlocks = self.current.localMinedBlocks
  356. }
  357. self.current = work
  358. return nil
  359. }
  360. func (w *worker) setGasPrice(p *big.Int) {
  361. w.mu.Lock()
  362. defer w.mu.Unlock()
  363. // calculate the minimal gas price the miner accepts when sorting out transactions.
  364. const pct = int64(90)
  365. w.gasPrice = gasprice(p, pct)
  366. w.mux.Post(core.GasPriceChanged{Price: w.gasPrice})
  367. }
  368. func (self *worker) isBlockLocallyMined(current *Work, deepBlockNum uint64) bool {
  369. //Did this instance mine a block at {deepBlockNum} ?
  370. var isLocal = false
  371. for idx, blockNum := range current.localMinedBlocks.ints {
  372. if deepBlockNum == blockNum {
  373. isLocal = true
  374. current.localMinedBlocks.ints[idx] = 0 //prevent showing duplicate logs
  375. break
  376. }
  377. }
  378. //Short-circuit on false, because the previous and following tests must both be true
  379. if !isLocal {
  380. return false
  381. }
  382. //Does the block at {deepBlockNum} send earnings to my coinbase?
  383. var block = self.chain.GetBlockByNumber(deepBlockNum)
  384. return block != nil && block.Coinbase() == self.coinbase
  385. }
  386. func (self *worker) logLocalMinedBlocks(current, previous *Work) {
  387. if previous != nil && current.localMinedBlocks != nil {
  388. nextBlockNum := current.Block.NumberU64()
  389. for checkBlockNum := previous.Block.NumberU64(); checkBlockNum < nextBlockNum; checkBlockNum++ {
  390. inspectBlockNum := checkBlockNum - miningLogAtDepth
  391. if self.isBlockLocallyMined(current, inspectBlockNum) {
  392. glog.V(logger.Info).Infof("🔨 🔗 Mined %d blocks back: block #%v", miningLogAtDepth, inspectBlockNum)
  393. }
  394. }
  395. }
  396. }
  397. func (self *worker) commitNewWork() {
  398. self.mu.Lock()
  399. defer self.mu.Unlock()
  400. self.uncleMu.Lock()
  401. defer self.uncleMu.Unlock()
  402. self.currentMu.Lock()
  403. defer self.currentMu.Unlock()
  404. tstart := time.Now()
  405. parent := self.chain.CurrentBlock()
  406. tstamp := tstart.Unix()
  407. if parent.Time().Cmp(new(big.Int).SetInt64(tstamp)) >= 0 {
  408. tstamp = parent.Time().Int64() + 1
  409. }
  410. // this will ensure we're not going off too far in the future
  411. if now := time.Now().Unix(); tstamp > now+4 {
  412. wait := time.Duration(tstamp-now) * time.Second
  413. glog.V(logger.Info).Infoln("We are too far in the future. Waiting for", wait)
  414. time.Sleep(wait)
  415. }
  416. num := parent.Number()
  417. header := &types.Header{
  418. ParentHash: parent.Hash(),
  419. Number: num.Add(num, common.Big1),
  420. Difficulty: core.CalcDifficulty(self.config, uint64(tstamp), parent.Time().Uint64(), parent.Number(), parent.Difficulty()),
  421. GasLimit: core.CalcGasLimit(parent),
  422. GasUsed: new(big.Int),
  423. Coinbase: self.coinbase,
  424. Extra: self.extra,
  425. Time: big.NewInt(tstamp),
  426. }
  427. // If we are care about TheDAO hard-fork check whether to override the extra-data or not
  428. if daoBlock := self.config.DAOForkBlock; daoBlock != nil {
  429. // Check whether the block is among the fork extra-override range
  430. limit := new(big.Int).Add(daoBlock, params.DAOForkExtraRange)
  431. if header.Number.Cmp(daoBlock) >= 0 && header.Number.Cmp(limit) < 0 {
  432. // Depending whether we support or oppose the fork, override differently
  433. if self.config.DAOForkSupport {
  434. header.Extra = common.CopyBytes(params.DAOForkBlockExtra)
  435. } else if bytes.Compare(header.Extra, params.DAOForkBlockExtra) == 0 {
  436. header.Extra = []byte{} // If miner opposes, don't let it use the reserved extra-data
  437. }
  438. }
  439. }
  440. previous := self.current
  441. // Could potentially happen if starting to mine in an odd state.
  442. err := self.makeCurrent(parent, header)
  443. if err != nil {
  444. glog.V(logger.Info).Infoln("Could not create new env for mining, retrying on next block.")
  445. return
  446. }
  447. // Create the current work task and check any fork transitions needed
  448. work := self.current
  449. if self.config.DAOForkSupport && self.config.DAOForkBlock != nil && self.config.DAOForkBlock.Cmp(header.Number) == 0 {
  450. core.ApplyDAOHardFork(work.state)
  451. }
  452. pending, err := self.eth.TxPool().Pending()
  453. if err != nil {
  454. glog.Errorf("Could not fetch pending transactions: %v", err)
  455. return
  456. }
  457. txs := types.NewTransactionsByPriceAndNonce(pending)
  458. work.commitTransactions(self.mux, txs, self.gasPrice, self.chain)
  459. self.eth.TxPool().RemoveBatch(work.lowGasTxs)
  460. self.eth.TxPool().RemoveBatch(work.failedTxs)
  461. // compute uncles for the new block.
  462. var (
  463. uncles []*types.Header
  464. badUncles []common.Hash
  465. )
  466. for hash, uncle := range self.possibleUncles {
  467. if len(uncles) == 2 {
  468. break
  469. }
  470. if err := self.commitUncle(work, uncle.Header()); err != nil {
  471. if glog.V(logger.Ridiculousness) {
  472. glog.V(logger.Detail).Infof("Bad uncle found and will be removed (%x)\n", hash[:4])
  473. glog.V(logger.Detail).Infoln(uncle)
  474. }
  475. badUncles = append(badUncles, hash)
  476. } else {
  477. glog.V(logger.Debug).Infof("commiting %x as uncle\n", hash[:4])
  478. uncles = append(uncles, uncle.Header())
  479. }
  480. }
  481. for _, hash := range badUncles {
  482. delete(self.possibleUncles, hash)
  483. }
  484. if atomic.LoadInt32(&self.mining) == 1 {
  485. // commit state root after all state transitions.
  486. core.AccumulateRewards(work.state, header, uncles)
  487. header.Root = work.state.IntermediateRoot(self.config.IsEIP158(header.Number))
  488. }
  489. // create the new block whose nonce will be mined.
  490. work.Block = types.NewBlock(header, work.txs, uncles, work.receipts)
  491. // We only care about logging if we're actually mining.
  492. if atomic.LoadInt32(&self.mining) == 1 {
  493. glog.V(logger.Info).Infof("commit new work on block %v with %d txs & %d uncles. Took %v\n", work.Block.Number(), work.tcount, len(uncles), time.Since(tstart))
  494. self.logLocalMinedBlocks(work, previous)
  495. }
  496. self.push(work)
  497. }
  498. func (self *worker) commitUncle(work *Work, uncle *types.Header) error {
  499. hash := uncle.Hash()
  500. if work.uncles.Has(hash) {
  501. return core.UncleError("Uncle not unique")
  502. }
  503. if !work.ancestors.Has(uncle.ParentHash) {
  504. return core.UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  505. }
  506. if work.family.Has(hash) {
  507. return core.UncleError(fmt.Sprintf("Uncle already in family (%x)", hash))
  508. }
  509. work.uncles.Add(uncle.Hash())
  510. return nil
  511. }
  512. func (env *Work) commitTransactions(mux *event.TypeMux, txs *types.TransactionsByPriceAndNonce, gasPrice *big.Int, bc *core.BlockChain) {
  513. gp := new(core.GasPool).AddGas(env.header.GasLimit)
  514. var coalescedLogs vm.Logs
  515. for {
  516. // Retrieve the next transaction and abort if all done
  517. tx := txs.Peek()
  518. if tx == nil {
  519. break
  520. }
  521. // Error may be ignored here. The error has already been checked
  522. // during transaction acceptance is the transaction pool.
  523. //
  524. // We use the eip155 signer regardless of the current hf.
  525. from, _ := types.Sender(env.signer, tx)
  526. // Check whether the tx is replay protected. If we're not in the EIP155 hf
  527. // phase, start ignoring the sender until we do.
  528. if tx.Protected() && !env.config.IsEIP155(env.header.Number) {
  529. glog.V(logger.Detail).Infof("Transaction (%x) is replay protected, but we haven't yet hardforked. Transaction will be ignored until we hardfork.\n", tx.Hash())
  530. txs.Pop()
  531. continue
  532. }
  533. // Ignore any transactions (and accounts subsequently) with low gas limits
  534. if tx.GasPrice().Cmp(gasPrice) < 0 && !env.ownedAccounts.Has(from) {
  535. // Pop the current low-priced transaction without shifting in the next from the account
  536. glog.V(logger.Info).Infof("Transaction (%x) below gas price (tx=%v ask=%v). All sequential txs from this address(%x) will be ignored\n", tx.Hash().Bytes()[:4], common.CurrencyToString(tx.GasPrice()), common.CurrencyToString(gasPrice), from[:4])
  537. env.lowGasTxs = append(env.lowGasTxs, tx)
  538. txs.Pop()
  539. continue
  540. }
  541. // Start executing the transaction
  542. env.state.StartRecord(tx.Hash(), common.Hash{}, env.tcount)
  543. err, logs := env.commitTransaction(tx, bc, gp)
  544. switch {
  545. case core.IsGasLimitErr(err):
  546. // Pop the current out-of-gas transaction without shifting in the next from the account
  547. glog.V(logger.Detail).Infof("Gas limit reached for (%x) in this block. Continue to try smaller txs\n", from[:4])
  548. txs.Pop()
  549. case err != nil:
  550. // Pop the current failed transaction without shifting in the next from the account
  551. glog.V(logger.Detail).Infof("Transaction (%x) failed, will be removed: %v\n", tx.Hash().Bytes()[:4], err)
  552. env.failedTxs = append(env.failedTxs, tx)
  553. txs.Pop()
  554. default:
  555. // Everything ok, collect the logs and shift in the next transaction from the same account
  556. coalescedLogs = append(coalescedLogs, logs...)
  557. env.tcount++
  558. txs.Shift()
  559. }
  560. }
  561. if len(coalescedLogs) > 0 || env.tcount > 0 {
  562. // make a copy, the state caches the logs and these logs get "upgraded" from pending to mined
  563. // logs by filling in the block hash when the block was mined by the local miner. This can
  564. // cause a race condition if a log was "upgraded" before the PendingLogsEvent is processed.
  565. cpy := make(vm.Logs, len(coalescedLogs))
  566. for i, l := range coalescedLogs {
  567. cpy[i] = new(vm.Log)
  568. *cpy[i] = *l
  569. }
  570. go func(logs vm.Logs, tcount int) {
  571. if len(logs) > 0 {
  572. mux.Post(core.PendingLogsEvent{Logs: logs})
  573. }
  574. if tcount > 0 {
  575. mux.Post(core.PendingStateEvent{})
  576. }
  577. }(cpy, env.tcount)
  578. }
  579. }
  580. func (env *Work) commitTransaction(tx *types.Transaction, bc *core.BlockChain, gp *core.GasPool) (error, vm.Logs) {
  581. snap := env.state.Snapshot()
  582. receipt, logs, _, err := core.ApplyTransaction(env.config, bc, gp, env.state, env.header, tx, env.header.GasUsed, vm.Config{})
  583. if err != nil {
  584. env.state.RevertToSnapshot(snap)
  585. return err, nil
  586. }
  587. env.txs = append(env.txs, tx)
  588. env.receipts = append(env.receipts, receipt)
  589. return nil, logs
  590. }
  591. // TODO: remove or use
  592. func (self *worker) HashRate() int64 {
  593. return 0
  594. }
  595. // gasprice calculates a reduced gas price based on the pct
  596. // XXX Use big.Rat?
  597. func gasprice(price *big.Int, pct int64) *big.Int {
  598. p := new(big.Int).Set(price)
  599. p.Div(p, big.NewInt(100))
  600. p.Mul(p, big.NewInt(pct))
  601. return p
  602. }
  603. func accountAddressesSet(accounts []accounts.Account) *set.Set {
  604. accountSet := set.New()
  605. for _, account := range accounts {
  606. accountSet.Add(account.Address)
  607. }
  608. return accountSet
  609. }