worker.go 20 KB

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