worker.go 17 KB

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