worker.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. glog.V(logger.Info).Infof("🔨 Mined block #%v", block.Number())
  191. jsonlogger.LogJson(&logger.EthMinerNewBlock{
  192. BlockHash: block.Hash().Hex(),
  193. BlockNumber: block.Number(),
  194. ChainHeadHash: block.ParentHeaderHash.Hex(),
  195. BlockPrevHash: block.ParentHeaderHash.Hex(),
  196. })
  197. } else {
  198. self.commitNewWork()
  199. }
  200. }
  201. }
  202. }
  203. func (self *worker) push() {
  204. if atomic.LoadInt32(&self.mining) == 1 {
  205. self.current.block.Header().GasUsed = self.current.totalUsedGas
  206. self.current.block.SetRoot(self.current.state.Root())
  207. // push new work to agents
  208. for _, agent := range self.agents {
  209. atomic.AddInt32(&self.atWork, 1)
  210. if agent.Work() != nil {
  211. agent.Work() <- self.current.block.Copy()
  212. } else {
  213. common.Report(fmt.Sprintf("%v %T\n", agent, agent))
  214. }
  215. }
  216. }
  217. }
  218. func (self *worker) makeCurrent() {
  219. block := self.chain.NewBlock(self.coinbase)
  220. if block.Time() == self.chain.CurrentBlock().Time() {
  221. block.Header().Time++
  222. }
  223. block.Header().Extra = self.extra
  224. current := env(block, self.eth)
  225. for _, ancestor := range self.chain.GetAncestors(block, 7) {
  226. for _, uncle := range ancestor.Uncles() {
  227. current.family.Add(uncle.Hash())
  228. }
  229. current.family.Add(ancestor.Hash())
  230. current.ancestors.Add(ancestor.Hash())
  231. }
  232. accounts, _ := self.eth.AccountManager().Accounts()
  233. // Keep track of transactions which return errors so they can be removed
  234. current.remove = set.New()
  235. current.tcount = 0
  236. current.ignoredTransactors = set.New()
  237. current.lowGasTransactors = set.New()
  238. current.ownedAccounts = accountAddressesSet(accounts)
  239. parent := self.chain.GetBlock(current.block.ParentHash())
  240. current.coinbase.SetGasPool(core.CalcGasLimit(parent))
  241. self.current = current
  242. }
  243. func (w *worker) setGasPrice(p *big.Int) {
  244. w.mu.Lock()
  245. defer w.mu.Unlock()
  246. // calculate the minimal gas price the miner accepts when sorting out transactions.
  247. const pct = int64(90)
  248. w.gasPrice = gasprice(p, pct)
  249. w.mux.Post(core.GasPriceChanged{w.gasPrice})
  250. }
  251. func (self *worker) commitNewWork() {
  252. self.mu.Lock()
  253. defer self.mu.Unlock()
  254. self.uncleMu.Lock()
  255. defer self.uncleMu.Unlock()
  256. self.currentMu.Lock()
  257. defer self.currentMu.Unlock()
  258. self.makeCurrent()
  259. current := self.current
  260. transactions := self.eth.TxPool().GetTransactions()
  261. sort.Sort(types.TxByNonce{transactions})
  262. // commit transactions for this run
  263. self.commitTransactions(transactions)
  264. self.eth.TxPool().RemoveTransactions(current.lowGasTxs)
  265. var (
  266. uncles []*types.Header
  267. badUncles []common.Hash
  268. )
  269. for hash, uncle := range self.possibleUncles {
  270. if len(uncles) == 2 {
  271. break
  272. }
  273. if err := self.commitUncle(uncle.Header()); err != nil {
  274. if glog.V(logger.Ridiculousness) {
  275. glog.V(logger.Detail).Infof("Bad uncle found and will be removed (%x)\n", hash[:4])
  276. glog.V(logger.Detail).Infoln(uncle)
  277. }
  278. badUncles = append(badUncles, hash)
  279. } else {
  280. glog.V(logger.Debug).Infof("commiting %x as uncle\n", hash[:4])
  281. uncles = append(uncles, uncle.Header())
  282. }
  283. }
  284. // We only care about logging if we're actually mining
  285. if atomic.LoadInt32(&self.mining) == 1 {
  286. glog.V(logger.Info).Infof("commit new work on block %v with %d txs & %d uncles\n", current.block.Number(), current.tcount, len(uncles))
  287. }
  288. for _, hash := range badUncles {
  289. delete(self.possibleUncles, hash)
  290. }
  291. self.current.block.SetUncles(uncles)
  292. core.AccumulateRewards(self.current.state, self.current.block)
  293. self.current.state.Update()
  294. self.push()
  295. }
  296. var (
  297. inclusionReward = new(big.Int).Div(core.BlockReward, big.NewInt(32))
  298. _uncleReward = new(big.Int).Mul(core.BlockReward, big.NewInt(15))
  299. uncleReward = new(big.Int).Div(_uncleReward, big.NewInt(16))
  300. )
  301. func (self *worker) commitUncle(uncle *types.Header) error {
  302. if self.current.uncles.Has(uncle.Hash()) {
  303. // Error not unique
  304. return core.UncleError("Uncle not unique")
  305. }
  306. self.current.uncles.Add(uncle.Hash())
  307. if !self.current.ancestors.Has(uncle.ParentHash) {
  308. return core.UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  309. }
  310. if self.current.family.Has(uncle.Hash()) {
  311. return core.UncleError(fmt.Sprintf("Uncle already in family (%x)", uncle.Hash()))
  312. }
  313. return nil
  314. }
  315. func (self *worker) commitTransactions(transactions types.Transactions) {
  316. current := self.current
  317. for _, tx := range transactions {
  318. // We can skip err. It has already been validated in the tx pool
  319. from, _ := tx.From()
  320. // Check if it falls within margin. Txs from owned accounts are always processed.
  321. if tx.GasPrice().Cmp(self.gasPrice) < 0 && !current.ownedAccounts.Has(from) {
  322. // ignore the transaction and transactor. We ignore the transactor
  323. // because nonce will fail after ignoring this transaction so there's
  324. // no point
  325. current.lowGasTransactors.Add(from)
  326. 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])
  327. }
  328. // Continue with the next transaction if the transaction sender is included in
  329. // the low gas tx set. This will also remove the tx and all sequential transaction
  330. // from this transactor
  331. if current.lowGasTransactors.Has(from) {
  332. // add tx to the low gas set. This will be removed at the end of the run
  333. // owned accounts are ignored
  334. if !current.ownedAccounts.Has(from) {
  335. current.lowGasTxs = append(current.lowGasTxs, tx)
  336. }
  337. continue
  338. }
  339. // Move on to the next transaction when the transactor is in ignored transactions set
  340. // This may occur when a transaction hits the gas limit. When a gas limit is hit and
  341. // the transaction is processed (that could potentially be included in the block) it
  342. // will throw a nonce error because the previous transaction hasn't been processed.
  343. // Therefor we need to ignore any transaction after the ignored one.
  344. if current.ignoredTransactors.Has(from) {
  345. continue
  346. }
  347. self.current.state.StartRecord(tx.Hash(), common.Hash{}, 0)
  348. err := self.commitTransaction(tx)
  349. switch {
  350. case core.IsNonceErr(err) || core.IsInvalidTxErr(err):
  351. // Remove invalid transactions
  352. from, _ := tx.From()
  353. self.chain.TxState().RemoveNonce(from, tx.Nonce())
  354. current.remove.Add(tx.Hash())
  355. if glog.V(logger.Detail) {
  356. glog.Infof("TX (%x) failed, will be removed: %v\n", tx.Hash().Bytes()[:4], err)
  357. }
  358. case state.IsGasLimitErr(err):
  359. from, _ := tx.From()
  360. // ignore the transactor so no nonce errors will be thrown for this account
  361. // next time the worker is run, they'll be picked up again.
  362. current.ignoredTransactors.Add(from)
  363. glog.V(logger.Detail).Infof("Gas limit reached for (%x) in this block. Continue to try smaller txs\n", from[:4])
  364. default:
  365. current.tcount++
  366. }
  367. }
  368. }
  369. func (self *worker) commitTransaction(tx *types.Transaction) error {
  370. snap := self.current.state.Copy()
  371. receipt, _, err := self.proc.ApplyTransaction(self.current.coinbase, self.current.state, self.current.block, tx, self.current.totalUsedGas, true)
  372. if err != nil && (core.IsNonceErr(err) || state.IsGasLimitErr(err) || core.IsInvalidTxErr(err)) {
  373. self.current.state.Set(snap)
  374. return err
  375. }
  376. self.current.block.AddTransaction(tx)
  377. self.current.block.AddReceipt(receipt)
  378. return nil
  379. }
  380. // TODO: remove or use
  381. func (self *worker) HashRate() int64 {
  382. return 0
  383. }
  384. // gasprice calculates a reduced gas price based on the pct
  385. // XXX Use big.Rat?
  386. func gasprice(price *big.Int, pct int64) *big.Int {
  387. p := new(big.Int).Set(price)
  388. p.Div(p, big.NewInt(100))
  389. p.Mul(p, big.NewInt(pct))
  390. return p
  391. }
  392. func accountAddressesSet(accounts []accounts.Account) *set.Set {
  393. accountSet := set.New()
  394. for _, account := range accounts {
  395. accountSet.Add(account.Address)
  396. }
  397. return accountSet
  398. }