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