worker.go 20 KB

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