worker.go 18 KB

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