worker.go 19 KB

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