worker.go 19 KB

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