worker.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. package miner
  2. import (
  3. "fmt"
  4. "math/big"
  5. "sort"
  6. "sync"
  7. "sync/atomic"
  8. "github.com/ethereum/go-ethereum/accounts"
  9. "github.com/ethereum/go-ethereum/common"
  10. "github.com/ethereum/go-ethereum/core"
  11. "github.com/ethereum/go-ethereum/core/state"
  12. "github.com/ethereum/go-ethereum/core/types"
  13. "github.com/ethereum/go-ethereum/event"
  14. "github.com/ethereum/go-ethereum/logger"
  15. "github.com/ethereum/go-ethereum/logger/glog"
  16. "github.com/ethereum/go-ethereum/pow"
  17. "gopkg.in/fatih/set.v0"
  18. )
  19. var jsonlogger = logger.NewJsonLogger()
  20. // Work holds the current work
  21. type Work struct {
  22. Number uint64
  23. Nonce uint64
  24. MixDigest []byte
  25. SeedHash []byte
  26. }
  27. // Agent can register themself with the worker
  28. type Agent interface {
  29. Work() chan<- *types.Block
  30. SetReturnCh(chan<- *types.Block)
  31. Stop()
  32. Start()
  33. GetHashRate() int64
  34. }
  35. // environment is the workers current environment and holds
  36. // all of the current state information
  37. type environment struct {
  38. totalUsedGas *big.Int // total gas usage in the cycle
  39. state *state.StateDB // apply state changes here
  40. coinbase *state.StateObject // the miner's account
  41. block *types.Block // the new block
  42. ancestors *set.Set // ancestor set (used for checking uncle parent validity)
  43. family *set.Set // family set (used for checking uncle invalidity)
  44. uncles *set.Set // uncle set
  45. remove *set.Set // tx which will be removed
  46. tcount int // tx count in cycle
  47. ignoredTransactors *set.Set
  48. lowGasTransactors *set.Set
  49. ownedAccounts *set.Set
  50. lowGasTxs types.Transactions
  51. }
  52. // env returns a new environment for the current cycle
  53. func env(block *types.Block, eth core.Backend) *environment {
  54. state := state.New(block.Root(), eth.StateDb())
  55. env := &environment{
  56. totalUsedGas: new(big.Int),
  57. state: state,
  58. block: block,
  59. ancestors: set.New(),
  60. family: set.New(),
  61. uncles: set.New(),
  62. coinbase: state.GetOrNewStateObject(block.Coinbase()),
  63. }
  64. return env
  65. }
  66. // worker is the main object which takes care of applying messages to the new state
  67. type worker struct {
  68. mu sync.Mutex
  69. agents []Agent
  70. recv chan *types.Block
  71. mux *event.TypeMux
  72. quit chan struct{}
  73. pow pow.PoW
  74. eth core.Backend
  75. chain *core.ChainManager
  76. proc *core.BlockProcessor
  77. coinbase common.Address
  78. gasPrice *big.Int
  79. extra []byte
  80. currentMu sync.Mutex
  81. current *environment
  82. uncleMu sync.Mutex
  83. possibleUncles map[common.Hash]*types.Block
  84. txQueueMu sync.Mutex
  85. txQueue map[common.Hash]*types.Transaction
  86. // atomic status counters
  87. mining int32
  88. atWork int32
  89. }
  90. func newWorker(coinbase common.Address, eth core.Backend) *worker {
  91. worker := &worker{
  92. eth: eth,
  93. mux: eth.EventMux(),
  94. recv: make(chan *types.Block),
  95. gasPrice: new(big.Int),
  96. chain: eth.ChainManager(),
  97. proc: eth.BlockProcessor(),
  98. possibleUncles: make(map[common.Hash]*types.Block),
  99. coinbase: coinbase,
  100. txQueue: make(map[common.Hash]*types.Transaction),
  101. quit: make(chan struct{}),
  102. }
  103. go worker.update()
  104. go worker.wait()
  105. worker.commitNewWork()
  106. return worker
  107. }
  108. func (self *worker) pendingState() *state.StateDB {
  109. self.currentMu.Lock()
  110. defer self.currentMu.Unlock()
  111. return self.current.state
  112. }
  113. func (self *worker) pendingBlock() *types.Block {
  114. self.currentMu.Lock()
  115. defer self.currentMu.Unlock()
  116. return self.current.block
  117. }
  118. func (self *worker) start() {
  119. self.mu.Lock()
  120. defer self.mu.Unlock()
  121. atomic.StoreInt32(&self.mining, 1)
  122. // spin up agents
  123. for _, agent := range self.agents {
  124. agent.Start()
  125. }
  126. }
  127. func (self *worker) stop() {
  128. self.mu.Lock()
  129. defer self.mu.Unlock()
  130. if atomic.LoadInt32(&self.mining) == 1 {
  131. var keep []Agent
  132. // stop all agents
  133. for _, agent := range self.agents {
  134. agent.Stop()
  135. // keep all that's not a cpu agent
  136. if _, ok := agent.(*CpuAgent); !ok {
  137. keep = append(keep, agent)
  138. }
  139. }
  140. self.agents = keep
  141. }
  142. atomic.StoreInt32(&self.mining, 0)
  143. atomic.StoreInt32(&self.atWork, 0)
  144. }
  145. func (self *worker) register(agent Agent) {
  146. self.mu.Lock()
  147. defer self.mu.Unlock()
  148. self.agents = append(self.agents, agent)
  149. agent.SetReturnCh(self.recv)
  150. }
  151. func (self *worker) update() {
  152. events := self.mux.Subscribe(core.ChainHeadEvent{}, core.ChainSideEvent{}, core.TxPreEvent{})
  153. out:
  154. for {
  155. select {
  156. case event := <-events.Chan():
  157. switch ev := event.(type) {
  158. case core.ChainHeadEvent:
  159. self.commitNewWork()
  160. case core.ChainSideEvent:
  161. self.uncleMu.Lock()
  162. self.possibleUncles[ev.Block.Hash()] = ev.Block
  163. self.uncleMu.Unlock()
  164. case core.TxPreEvent:
  165. // Apply transaction to the pending state if we're not mining
  166. if atomic.LoadInt32(&self.mining) == 0 {
  167. self.mu.Lock()
  168. self.commitTransactions(types.Transactions{ev.Tx})
  169. self.mu.Unlock()
  170. }
  171. }
  172. case <-self.quit:
  173. break out
  174. }
  175. }
  176. events.Unsubscribe()
  177. }
  178. func (self *worker) wait() {
  179. for {
  180. for block := range self.recv {
  181. atomic.AddInt32(&self.atWork, -1)
  182. if block == nil {
  183. continue
  184. }
  185. if _, err := self.chain.InsertChain(types.Blocks{block}); err == nil {
  186. for _, uncle := range block.Uncles() {
  187. delete(self.possibleUncles, uncle.Hash())
  188. }
  189. self.mux.Post(core.NewMinedBlockEvent{block})
  190. var stale string
  191. canonBlock := self.chain.GetBlockByNumber(block.NumberU64())
  192. if canonBlock != nil && canonBlock.Hash() != block.Hash() {
  193. stale = "stale-"
  194. }
  195. glog.V(logger.Info).Infof("🔨 Mined %sblock #%v (%x)", stale, block.Number(), block.Hash().Bytes()[:4])
  196. jsonlogger.LogJson(&logger.EthMinerNewBlock{
  197. BlockHash: block.Hash().Hex(),
  198. BlockNumber: block.Number(),
  199. ChainHeadHash: block.ParentHeaderHash.Hex(),
  200. BlockPrevHash: block.ParentHeaderHash.Hex(),
  201. })
  202. } else {
  203. self.commitNewWork()
  204. }
  205. }
  206. }
  207. }
  208. func (self *worker) push() {
  209. if atomic.LoadInt32(&self.mining) == 1 {
  210. self.current.block.Header().GasUsed = self.current.totalUsedGas
  211. self.current.block.SetRoot(self.current.state.Root())
  212. // push new work to agents
  213. for _, agent := range self.agents {
  214. atomic.AddInt32(&self.atWork, 1)
  215. if agent.Work() != nil {
  216. agent.Work() <- self.current.block.Copy()
  217. } else {
  218. common.Report(fmt.Sprintf("%v %T\n", agent, agent))
  219. }
  220. }
  221. }
  222. }
  223. func (self *worker) makeCurrent() {
  224. block := self.chain.NewBlock(self.coinbase)
  225. if block.Time() == self.chain.CurrentBlock().Time() {
  226. block.Header().Time++
  227. }
  228. block.Header().Extra = self.extra
  229. // when 08 is processed ancestors contain 07 (quick block)
  230. current := env(block, self.eth)
  231. for _, ancestor := range self.chain.GetAncestors(block, 7) {
  232. for _, uncle := range ancestor.Uncles() {
  233. current.family.Add(uncle.Hash())
  234. }
  235. current.family.Add(ancestor.Hash())
  236. current.ancestors.Add(ancestor.Hash())
  237. }
  238. accounts, _ := self.eth.AccountManager().Accounts()
  239. // Keep track of transactions which return errors so they can be removed
  240. current.remove = set.New()
  241. current.tcount = 0
  242. current.ignoredTransactors = set.New()
  243. current.lowGasTransactors = set.New()
  244. current.ownedAccounts = accountAddressesSet(accounts)
  245. parent := self.chain.GetBlock(current.block.ParentHash())
  246. current.coinbase.SetGasPool(core.CalcGasLimit(parent))
  247. self.current = current
  248. }
  249. func (w *worker) setGasPrice(p *big.Int) {
  250. w.mu.Lock()
  251. defer w.mu.Unlock()
  252. // calculate the minimal gas price the miner accepts when sorting out transactions.
  253. const pct = int64(90)
  254. w.gasPrice = gasprice(p, pct)
  255. w.mux.Post(core.GasPriceChanged{w.gasPrice})
  256. }
  257. func (self *worker) commitNewWork() {
  258. self.mu.Lock()
  259. defer self.mu.Unlock()
  260. self.uncleMu.Lock()
  261. defer self.uncleMu.Unlock()
  262. self.currentMu.Lock()
  263. defer self.currentMu.Unlock()
  264. self.makeCurrent()
  265. current := self.current
  266. transactions := self.eth.TxPool().GetTransactions()
  267. sort.Sort(types.TxByNonce{transactions})
  268. // commit transactions for this run
  269. self.commitTransactions(transactions)
  270. self.eth.TxPool().RemoveTransactions(current.lowGasTxs)
  271. var (
  272. uncles []*types.Header
  273. badUncles []common.Hash
  274. )
  275. for hash, uncle := range self.possibleUncles {
  276. if len(uncles) == 2 {
  277. break
  278. }
  279. if err := self.commitUncle(uncle.Header()); err != nil {
  280. if glog.V(logger.Ridiculousness) {
  281. glog.V(logger.Detail).Infof("Bad uncle found and will be removed (%x)\n", hash[:4])
  282. glog.V(logger.Detail).Infoln(uncle)
  283. }
  284. badUncles = append(badUncles, hash)
  285. } else {
  286. glog.V(logger.Debug).Infof("commiting %x as uncle\n", hash[:4])
  287. uncles = append(uncles, uncle.Header())
  288. }
  289. }
  290. // We only care about logging if we're actually mining
  291. if atomic.LoadInt32(&self.mining) == 1 {
  292. glog.V(logger.Info).Infof("commit new work on block %v with %d txs & %d uncles\n", current.block.Number(), current.tcount, len(uncles))
  293. }
  294. for _, hash := range badUncles {
  295. delete(self.possibleUncles, hash)
  296. }
  297. self.current.block.SetUncles(uncles)
  298. core.AccumulateRewards(self.current.state, self.current.block)
  299. self.current.state.Update()
  300. self.push()
  301. }
  302. var (
  303. inclusionReward = new(big.Int).Div(core.BlockReward, big.NewInt(32))
  304. _uncleReward = new(big.Int).Mul(core.BlockReward, big.NewInt(15))
  305. uncleReward = new(big.Int).Div(_uncleReward, big.NewInt(16))
  306. )
  307. func (self *worker) commitUncle(uncle *types.Header) error {
  308. if self.current.uncles.Has(uncle.Hash()) {
  309. // Error not unique
  310. return core.UncleError("Uncle not unique")
  311. }
  312. self.current.uncles.Add(uncle.Hash())
  313. if !self.current.ancestors.Has(uncle.ParentHash) {
  314. return core.UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  315. }
  316. if self.current.family.Has(uncle.Hash()) {
  317. return core.UncleError(fmt.Sprintf("Uncle already in family (%x)", uncle.Hash()))
  318. }
  319. return nil
  320. }
  321. func (self *worker) commitTransactions(transactions types.Transactions) {
  322. current := self.current
  323. for _, tx := range transactions {
  324. // We can skip err. It has already been validated in the tx pool
  325. from, _ := tx.From()
  326. // Check if it falls within margin. Txs from owned accounts are always processed.
  327. if tx.GasPrice().Cmp(self.gasPrice) < 0 && !current.ownedAccounts.Has(from) {
  328. // ignore the transaction and transactor. We ignore the transactor
  329. // because nonce will fail after ignoring this transaction so there's
  330. // no point
  331. current.lowGasTransactors.Add(from)
  332. 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(self.gasPrice), from[:4])
  333. }
  334. // Continue with the next transaction if the transaction sender is included in
  335. // the low gas tx set. This will also remove the tx and all sequential transaction
  336. // from this transactor
  337. if current.lowGasTransactors.Has(from) {
  338. // add tx to the low gas set. This will be removed at the end of the run
  339. // owned accounts are ignored
  340. if !current.ownedAccounts.Has(from) {
  341. current.lowGasTxs = append(current.lowGasTxs, tx)
  342. }
  343. continue
  344. }
  345. // Move on to the next transaction when the transactor is in ignored transactions set
  346. // This may occur when a transaction hits the gas limit. When a gas limit is hit and
  347. // the transaction is processed (that could potentially be included in the block) it
  348. // will throw a nonce error because the previous transaction hasn't been processed.
  349. // Therefor we need to ignore any transaction after the ignored one.
  350. if current.ignoredTransactors.Has(from) {
  351. continue
  352. }
  353. self.current.state.StartRecord(tx.Hash(), common.Hash{}, 0)
  354. err := self.commitTransaction(tx)
  355. switch {
  356. case core.IsNonceErr(err) || core.IsInvalidTxErr(err):
  357. // Remove invalid transactions
  358. from, _ := tx.From()
  359. self.chain.TxState().RemoveNonce(from, tx.Nonce())
  360. current.remove.Add(tx.Hash())
  361. if glog.V(logger.Detail) {
  362. glog.Infof("TX (%x) failed, will be removed: %v\n", tx.Hash().Bytes()[:4], err)
  363. }
  364. case state.IsGasLimitErr(err):
  365. from, _ := tx.From()
  366. // ignore the transactor so no nonce errors will be thrown for this account
  367. // next time the worker is run, they'll be picked up again.
  368. current.ignoredTransactors.Add(from)
  369. glog.V(logger.Detail).Infof("Gas limit reached for (%x) in this block. Continue to try smaller txs\n", from[:4])
  370. default:
  371. current.tcount++
  372. }
  373. }
  374. }
  375. func (self *worker) commitTransaction(tx *types.Transaction) error {
  376. snap := self.current.state.Copy()
  377. receipt, _, err := self.proc.ApplyTransaction(self.current.coinbase, self.current.state, self.current.block, tx, self.current.totalUsedGas, true)
  378. if err != nil && (core.IsNonceErr(err) || state.IsGasLimitErr(err) || core.IsInvalidTxErr(err)) {
  379. self.current.state.Set(snap)
  380. return err
  381. }
  382. self.current.block.AddTransaction(tx)
  383. self.current.block.AddReceipt(receipt)
  384. return nil
  385. }
  386. // TODO: remove or use
  387. func (self *worker) HashRate() int64 {
  388. return 0
  389. }
  390. // gasprice calculates a reduced gas price based on the pct
  391. // XXX Use big.Rat?
  392. func gasprice(price *big.Int, pct int64) *big.Int {
  393. p := new(big.Int).Set(price)
  394. p.Div(p, big.NewInt(100))
  395. p.Mul(p, big.NewInt(pct))
  396. return p
  397. }
  398. func accountAddressesSet(accounts []accounts.Account) *set.Set {
  399. accountSet := set.New()
  400. for _, account := range accounts {
  401. accountSet.Add(account.Address)
  402. }
  403. return accountSet
  404. }