worker.go 15 KB

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