worker.go 20 KB

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