worker.go 21 KB

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