worker.go 11 KB

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