worker.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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/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. atWork int64
  61. eth core.Backend
  62. chain *core.ChainManager
  63. proc *core.BlockProcessor
  64. coinbase common.Address
  65. extra []byte
  66. current *environment
  67. uncleMu sync.Mutex
  68. possibleUncles map[common.Hash]*types.Block
  69. mining bool
  70. }
  71. func newWorker(coinbase common.Address, eth core.Backend) *worker {
  72. return &worker{
  73. eth: eth,
  74. mux: eth.EventMux(),
  75. recv: make(chan *types.Block),
  76. chain: eth.ChainManager(),
  77. proc: eth.BlockProcessor(),
  78. possibleUncles: make(map[common.Hash]*types.Block),
  79. coinbase: coinbase,
  80. }
  81. }
  82. func (self *worker) start() {
  83. self.mining = true
  84. self.quit = make(chan struct{})
  85. // spin up agents
  86. for _, agent := range self.agents {
  87. agent.Start()
  88. }
  89. go self.update()
  90. go self.wait()
  91. }
  92. func (self *worker) stop() {
  93. self.mining = false
  94. atomic.StoreInt64(&self.atWork, 0)
  95. close(self.quit)
  96. }
  97. func (self *worker) register(agent Agent) {
  98. self.agents = append(self.agents, agent)
  99. agent.SetReturnCh(self.recv)
  100. }
  101. func (self *worker) update() {
  102. events := self.mux.Subscribe(core.ChainHeadEvent{}, core.ChainSideEvent{})
  103. timer := time.NewTicker(2 * time.Second)
  104. out:
  105. for {
  106. select {
  107. case event := <-events.Chan():
  108. switch ev := event.(type) {
  109. case core.ChainHeadEvent:
  110. self.commitNewWork()
  111. case core.ChainSideEvent:
  112. self.uncleMu.Lock()
  113. self.possibleUncles[ev.Block.Hash()] = ev.Block
  114. self.uncleMu.Unlock()
  115. }
  116. case <-self.quit:
  117. // stop all agents
  118. for _, agent := range self.agents {
  119. agent.Stop()
  120. }
  121. break out
  122. case <-timer.C:
  123. if glog.V(logger.Debug) {
  124. glog.Infoln("Hash rate:", self.HashRate(), "Khash")
  125. }
  126. // XXX In case all mined a possible uncle
  127. if atomic.LoadInt64(&self.atWork) == 0 {
  128. self.commitNewWork()
  129. }
  130. }
  131. }
  132. events.Unsubscribe()
  133. }
  134. func (self *worker) wait() {
  135. for {
  136. for block := range self.recv {
  137. atomic.AddInt64(&self.atWork, -1)
  138. if block == nil {
  139. continue
  140. }
  141. if err := self.chain.InsertChain(types.Blocks{block}); err == nil {
  142. for _, uncle := range block.Uncles() {
  143. delete(self.possibleUncles, uncle.Hash())
  144. }
  145. self.mux.Post(core.NewMinedBlockEvent{block})
  146. glog.V(logger.Info).Infof("🔨 Mined block #%v", block.Number())
  147. jsonlogger.LogJson(&logger.EthMinerNewBlock{
  148. BlockHash: block.Hash().Hex(),
  149. BlockNumber: block.Number(),
  150. ChainHeadHash: block.ParentHeaderHash.Hex(),
  151. BlockPrevHash: block.ParentHeaderHash.Hex(),
  152. })
  153. } else {
  154. self.commitNewWork()
  155. }
  156. }
  157. }
  158. }
  159. func (self *worker) push() {
  160. if self.mining {
  161. self.current.block.Header().GasUsed = self.current.totalUsedGas
  162. self.current.block.SetRoot(self.current.state.Root())
  163. // push new work to agents
  164. for _, agent := range self.agents {
  165. atomic.AddInt64(&self.atWork, 1)
  166. agent.Work() <- self.current.block.Copy()
  167. }
  168. }
  169. }
  170. func (self *worker) commitNewWork() {
  171. self.mu.Lock()
  172. defer self.mu.Unlock()
  173. self.uncleMu.Lock()
  174. defer self.uncleMu.Unlock()
  175. block := self.chain.NewBlock(self.coinbase)
  176. if block.Time() == self.chain.CurrentBlock().Time() {
  177. block.Header().Time++
  178. }
  179. block.Header().Extra = self.extra
  180. self.current = env(block, self.eth)
  181. for _, ancestor := range self.chain.GetAncestors(block, 7) {
  182. self.current.family.Add(ancestor.Hash())
  183. }
  184. parent := self.chain.GetBlock(self.current.block.ParentHash())
  185. self.current.coinbase.SetGasPool(core.CalcGasLimit(parent, self.current.block))
  186. transactions := self.eth.TxPool().GetTransactions()
  187. sort.Sort(types.TxByNonce{transactions})
  188. // Keep track of transactions which return errors so they can be removed
  189. var (
  190. remove types.Transactions
  191. tcount = 0
  192. )
  193. gasLimit:
  194. for i, tx := range transactions {
  195. err := self.commitTransaction(tx)
  196. switch {
  197. case core.IsNonceErr(err):
  198. fallthrough
  199. case core.IsInvalidTxErr(err):
  200. // Remove invalid transactions
  201. from, _ := tx.From()
  202. self.chain.TxState().RemoveNonce(from, tx.Nonce())
  203. remove = append(remove, tx)
  204. if glog.V(logger.Info) {
  205. glog.Infof("TX (%x) failed, will be removed: %v\n", tx.Hash().Bytes()[:4], err)
  206. }
  207. glog.V(logger.Debug).Infoln(tx)
  208. case state.IsGasLimitErr(err):
  209. glog.V(logger.Info).Infof("Gas limit reached for block. %d TXs included in this block\n", i)
  210. // Break on gas limit
  211. break gasLimit
  212. default:
  213. tcount++
  214. }
  215. }
  216. self.eth.TxPool().RemoveSet(remove)
  217. var (
  218. uncles []*types.Header
  219. badUncles []common.Hash
  220. )
  221. for hash, uncle := range self.possibleUncles {
  222. if len(uncles) == 2 {
  223. break
  224. }
  225. if err := self.commitUncle(uncle.Header()); err != nil {
  226. glog.V(logger.Info).Infof("Bad uncle found and will be removed (%x)\n", hash[:4])
  227. glog.V(logger.Debug).Infoln(uncle)
  228. badUncles = append(badUncles, hash)
  229. } else {
  230. glog.V(logger.Info).Infof("commiting %x as uncle\n", hash[:4])
  231. uncles = append(uncles, uncle.Header())
  232. }
  233. }
  234. glog.V(logger.Info).Infof("commit new work on block %v with %d txs & %d uncles\n", self.current.block.Number(), tcount, len(uncles))
  235. for _, hash := range badUncles {
  236. delete(self.possibleUncles, hash)
  237. }
  238. self.current.block.SetUncles(uncles)
  239. core.AccumulateRewards(self.current.state, self.current.block)
  240. self.current.state.Update()
  241. self.push()
  242. }
  243. var (
  244. inclusionReward = new(big.Int).Div(core.BlockReward, big.NewInt(32))
  245. _uncleReward = new(big.Int).Mul(core.BlockReward, big.NewInt(15))
  246. uncleReward = new(big.Int).Div(_uncleReward, big.NewInt(16))
  247. )
  248. func (self *worker) commitUncle(uncle *types.Header) error {
  249. if self.current.uncles.Has(uncle.Hash()) {
  250. // Error not unique
  251. return core.UncleError("Uncle not unique")
  252. }
  253. self.current.uncles.Add(uncle.Hash())
  254. if !self.current.family.Has(uncle.ParentHash) {
  255. return core.UncleError(fmt.Sprintf("Uncle's parent unknown (%x)", uncle.ParentHash[0:4]))
  256. }
  257. if self.current.family.Has(uncle.Hash()) {
  258. return core.UncleError(fmt.Sprintf("Uncle already in family (%x)", uncle.Hash()))
  259. }
  260. return nil
  261. }
  262. func (self *worker) commitTransaction(tx *types.Transaction) error {
  263. snap := self.current.state.Copy()
  264. receipt, _, err := self.proc.ApplyTransaction(self.current.coinbase, self.current.state, self.current.block, tx, self.current.totalUsedGas, true)
  265. if err != nil && (core.IsNonceErr(err) || state.IsGasLimitErr(err) || core.IsInvalidTxErr(err)) {
  266. self.current.state.Set(snap)
  267. return err
  268. }
  269. self.current.block.AddTransaction(tx)
  270. self.current.block.AddReceipt(receipt)
  271. return nil
  272. }
  273. func (self *worker) HashRate() int64 {
  274. var tot int64
  275. for _, agent := range self.agents {
  276. tot += agent.GetHashRate()
  277. }
  278. return tot
  279. }