worker.go 17 KB

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