worker_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package miner
  17. import (
  18. "math/big"
  19. "testing"
  20. "time"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/consensus"
  23. "github.com/ethereum/go-ethereum/consensus/clique"
  24. "github.com/ethereum/go-ethereum/consensus/ethash"
  25. "github.com/ethereum/go-ethereum/core"
  26. "github.com/ethereum/go-ethereum/core/types"
  27. "github.com/ethereum/go-ethereum/core/vm"
  28. "github.com/ethereum/go-ethereum/crypto"
  29. "github.com/ethereum/go-ethereum/ethdb"
  30. "github.com/ethereum/go-ethereum/event"
  31. "github.com/ethereum/go-ethereum/params"
  32. )
  33. var (
  34. // Test chain configurations
  35. testTxPoolConfig core.TxPoolConfig
  36. ethashChainConfig *params.ChainConfig
  37. cliqueChainConfig *params.ChainConfig
  38. // Test accounts
  39. testBankKey, _ = crypto.GenerateKey()
  40. testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
  41. testBankFunds = big.NewInt(1000000000000000000)
  42. acc1Key, _ = crypto.GenerateKey()
  43. acc1Addr = crypto.PubkeyToAddress(acc1Key.PublicKey)
  44. // Test transactions
  45. pendingTxs []*types.Transaction
  46. newTxs []*types.Transaction
  47. )
  48. func init() {
  49. testTxPoolConfig = core.DefaultTxPoolConfig
  50. testTxPoolConfig.Journal = ""
  51. ethashChainConfig = params.TestChainConfig
  52. cliqueChainConfig = params.TestChainConfig
  53. cliqueChainConfig.Clique = &params.CliqueConfig{
  54. Period: 10,
  55. Epoch: 30000,
  56. }
  57. tx1, _ := types.SignTx(types.NewTransaction(0, acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), types.HomesteadSigner{}, testBankKey)
  58. pendingTxs = append(pendingTxs, tx1)
  59. tx2, _ := types.SignTx(types.NewTransaction(1, acc1Addr, big.NewInt(1000), params.TxGas, nil, nil), types.HomesteadSigner{}, testBankKey)
  60. newTxs = append(newTxs, tx2)
  61. }
  62. // testWorkerBackend implements worker.Backend interfaces and wraps all information needed during the testing.
  63. type testWorkerBackend struct {
  64. db ethdb.Database
  65. txPool *core.TxPool
  66. chain *core.BlockChain
  67. testTxFeed event.Feed
  68. uncleBlock *types.Block
  69. }
  70. func newTestWorkerBackend(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) *testWorkerBackend {
  71. var (
  72. db = ethdb.NewMemDatabase()
  73. gspec = core.Genesis{
  74. Config: chainConfig,
  75. Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
  76. }
  77. )
  78. switch engine.(type) {
  79. case *clique.Clique:
  80. gspec.ExtraData = make([]byte, 32+common.AddressLength+65)
  81. copy(gspec.ExtraData[32:], testBankAddress[:])
  82. case *ethash.Ethash:
  83. default:
  84. t.Fatal("unexpect consensus engine type")
  85. }
  86. genesis := gspec.MustCommit(db)
  87. chain, _ := core.NewBlockChain(db, nil, gspec.Config, engine, vm.Config{})
  88. txpool := core.NewTxPool(testTxPoolConfig, chainConfig, chain)
  89. blocks, _ := core.GenerateChain(chainConfig, genesis, engine, db, 1, func(i int, gen *core.BlockGen) {
  90. gen.SetCoinbase(acc1Addr)
  91. })
  92. return &testWorkerBackend{
  93. db: db,
  94. chain: chain,
  95. txPool: txpool,
  96. uncleBlock: blocks[0],
  97. }
  98. }
  99. func (b *testWorkerBackend) BlockChain() *core.BlockChain { return b.chain }
  100. func (b *testWorkerBackend) TxPool() *core.TxPool { return b.txPool }
  101. func (b *testWorkerBackend) PostChainEvents(events []interface{}) {
  102. b.chain.PostChainEvents(events, nil)
  103. }
  104. func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) (*worker, *testWorkerBackend) {
  105. backend := newTestWorkerBackend(t, chainConfig, engine)
  106. backend.txPool.AddLocals(pendingTxs)
  107. w := newWorker(chainConfig, engine, backend, new(event.TypeMux), time.Second, params.GenesisGasLimit, params.GenesisGasLimit)
  108. w.setEtherbase(testBankAddress)
  109. return w, backend
  110. }
  111. func TestPendingStateAndBlockEthash(t *testing.T) {
  112. testPendingStateAndBlock(t, ethashChainConfig, ethash.NewFaker())
  113. }
  114. func TestPendingStateAndBlockClique(t *testing.T) {
  115. testPendingStateAndBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, ethdb.NewMemDatabase()))
  116. }
  117. func testPendingStateAndBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  118. defer engine.Close()
  119. w, b := newTestWorker(t, chainConfig, engine)
  120. defer w.close()
  121. // Ensure snapshot has been updated.
  122. time.Sleep(100 * time.Millisecond)
  123. block, state := w.pending()
  124. if block.NumberU64() != 1 {
  125. t.Errorf("block number mismatch, has %d, want %d", block.NumberU64(), 1)
  126. }
  127. if balance := state.GetBalance(acc1Addr); balance.Cmp(big.NewInt(1000)) != 0 {
  128. t.Errorf("account balance mismatch, has %d, want %d", balance, 1000)
  129. }
  130. b.txPool.AddLocals(newTxs)
  131. // Ensure the new tx events has been processed
  132. time.Sleep(100 * time.Millisecond)
  133. block, state = w.pending()
  134. if balance := state.GetBalance(acc1Addr); balance.Cmp(big.NewInt(2000)) != 0 {
  135. t.Errorf("account balance mismatch, has %d, want %d", balance, 2000)
  136. }
  137. }
  138. func TestEmptyWorkEthash(t *testing.T) {
  139. testEmptyWork(t, ethashChainConfig, ethash.NewFaker())
  140. }
  141. func TestEmptyWorkClique(t *testing.T) {
  142. testEmptyWork(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, ethdb.NewMemDatabase()))
  143. }
  144. func testEmptyWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  145. defer engine.Close()
  146. w, _ := newTestWorker(t, chainConfig, engine)
  147. defer w.close()
  148. var (
  149. taskCh = make(chan struct{}, 2)
  150. taskIndex int
  151. )
  152. checkEqual := func(t *testing.T, task *task, index int) {
  153. receiptLen, balance := 0, big.NewInt(0)
  154. if index == 1 {
  155. receiptLen, balance = 1, big.NewInt(1000)
  156. }
  157. if len(task.receipts) != receiptLen {
  158. t.Errorf("receipt number mismatch has %d, want %d", len(task.receipts), receiptLen)
  159. }
  160. if task.state.GetBalance(acc1Addr).Cmp(balance) != 0 {
  161. t.Errorf("account balance mismatch has %d, want %d", task.state.GetBalance(acc1Addr), balance)
  162. }
  163. }
  164. w.newTaskHook = func(task *task) {
  165. if task.block.NumberU64() == 1 {
  166. checkEqual(t, task, taskIndex)
  167. taskIndex += 1
  168. taskCh <- struct{}{}
  169. }
  170. }
  171. w.fullTaskHook = func() {
  172. time.Sleep(100 * time.Millisecond)
  173. }
  174. // Ensure worker has finished initialization
  175. for {
  176. b := w.pendingBlock()
  177. if b != nil && b.NumberU64() == 1 {
  178. break
  179. }
  180. }
  181. w.start()
  182. for i := 0; i < 2; i += 1 {
  183. select {
  184. case <-taskCh:
  185. case <-time.NewTimer(time.Second).C:
  186. t.Error("new task timeout")
  187. }
  188. }
  189. }
  190. func TestStreamUncleBlock(t *testing.T) {
  191. ethash := ethash.NewFaker()
  192. defer ethash.Close()
  193. w, b := newTestWorker(t, ethashChainConfig, ethash)
  194. defer w.close()
  195. var taskCh = make(chan struct{})
  196. taskIndex := 0
  197. w.newTaskHook = func(task *task) {
  198. if task.block.NumberU64() == 1 {
  199. if taskIndex == 2 {
  200. has := task.block.Header().UncleHash
  201. want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()})
  202. if has != want {
  203. t.Errorf("uncle hash mismatch, has %s, want %s", has.Hex(), want.Hex())
  204. }
  205. }
  206. taskCh <- struct{}{}
  207. taskIndex += 1
  208. }
  209. }
  210. w.skipSealHook = func(task *task) bool {
  211. return true
  212. }
  213. w.fullTaskHook = func() {
  214. time.Sleep(100 * time.Millisecond)
  215. }
  216. // Ensure worker has finished initialization
  217. for {
  218. b := w.pendingBlock()
  219. if b != nil && b.NumberU64() == 1 {
  220. break
  221. }
  222. }
  223. w.start()
  224. // Ignore the first two works
  225. for i := 0; i < 2; i += 1 {
  226. select {
  227. case <-taskCh:
  228. case <-time.NewTimer(time.Second).C:
  229. t.Error("new task timeout")
  230. }
  231. }
  232. b.PostChainEvents([]interface{}{core.ChainSideEvent{Block: b.uncleBlock}})
  233. select {
  234. case <-taskCh:
  235. case <-time.NewTimer(time.Second).C:
  236. t.Error("new task timeout")
  237. }
  238. }
  239. func TestRegenerateMiningBlockEthash(t *testing.T) {
  240. testRegenerateMiningBlock(t, ethashChainConfig, ethash.NewFaker())
  241. }
  242. func TestRegenerateMiningBlockClique(t *testing.T) {
  243. testRegenerateMiningBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, ethdb.NewMemDatabase()))
  244. }
  245. func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  246. defer engine.Close()
  247. w, b := newTestWorker(t, chainConfig, engine)
  248. defer w.close()
  249. var taskCh = make(chan struct{})
  250. taskIndex := 0
  251. w.newTaskHook = func(task *task) {
  252. if task.block.NumberU64() == 1 {
  253. if taskIndex == 2 {
  254. receiptLen, balance := 2, big.NewInt(2000)
  255. if len(task.receipts) != receiptLen {
  256. t.Errorf("receipt number mismatch has %d, want %d", len(task.receipts), receiptLen)
  257. }
  258. if task.state.GetBalance(acc1Addr).Cmp(balance) != 0 {
  259. t.Errorf("account balance mismatch has %d, want %d", task.state.GetBalance(acc1Addr), balance)
  260. }
  261. }
  262. taskCh <- struct{}{}
  263. taskIndex += 1
  264. }
  265. }
  266. w.skipSealHook = func(task *task) bool {
  267. return true
  268. }
  269. w.fullTaskHook = func() {
  270. time.Sleep(100 * time.Millisecond)
  271. }
  272. // Ensure worker has finished initialization
  273. for {
  274. b := w.pendingBlock()
  275. if b != nil && b.NumberU64() == 1 {
  276. break
  277. }
  278. }
  279. w.start()
  280. // Ignore the first two works
  281. for i := 0; i < 2; i += 1 {
  282. select {
  283. case <-taskCh:
  284. case <-time.NewTimer(time.Second).C:
  285. t.Error("new task timeout")
  286. }
  287. }
  288. b.txPool.AddLocals(newTxs)
  289. time.Sleep(time.Second)
  290. select {
  291. case <-taskCh:
  292. case <-time.NewTimer(time.Second).C:
  293. t.Error("new task timeout")
  294. }
  295. }
  296. func TestAdjustIntervalEthash(t *testing.T) {
  297. testAdjustInterval(t, ethashChainConfig, ethash.NewFaker())
  298. }
  299. func TestAdjustIntervalClique(t *testing.T) {
  300. testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, ethdb.NewMemDatabase()))
  301. }
  302. func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  303. defer engine.Close()
  304. w, _ := newTestWorker(t, chainConfig, engine)
  305. defer w.close()
  306. w.skipSealHook = func(task *task) bool {
  307. return true
  308. }
  309. w.fullTaskHook = func() {
  310. time.Sleep(100 * time.Millisecond)
  311. }
  312. var (
  313. progress = make(chan struct{}, 10)
  314. result = make([]float64, 0, 10)
  315. index = 0
  316. start = false
  317. )
  318. w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) {
  319. // Short circuit if interval checking hasn't started.
  320. if !start {
  321. return
  322. }
  323. var wantMinInterval, wantRecommitInterval time.Duration
  324. switch index {
  325. case 0:
  326. wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second
  327. case 1:
  328. origin := float64(3 * time.Second.Nanoseconds())
  329. estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias)
  330. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(int(estimate))*time.Nanosecond
  331. case 2:
  332. estimate := result[index-1]
  333. min := float64(3 * time.Second.Nanoseconds())
  334. estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias)
  335. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(int(estimate))*time.Nanosecond
  336. case 3:
  337. wantMinInterval, wantRecommitInterval = time.Second, time.Second
  338. }
  339. // Check interval
  340. if minInterval != wantMinInterval {
  341. t.Errorf("resubmit min interval mismatch want %s has %s", wantMinInterval, minInterval)
  342. }
  343. if recommitInterval != wantRecommitInterval {
  344. t.Errorf("resubmit interval mismatch want %s has %s", wantRecommitInterval, recommitInterval)
  345. }
  346. result = append(result, float64(recommitInterval.Nanoseconds()))
  347. index += 1
  348. progress <- struct{}{}
  349. }
  350. // Ensure worker has finished initialization
  351. for {
  352. b := w.pendingBlock()
  353. if b != nil && b.NumberU64() == 1 {
  354. break
  355. }
  356. }
  357. w.start()
  358. time.Sleep(time.Second)
  359. start = true
  360. w.setRecommitInterval(3 * time.Second)
  361. select {
  362. case <-progress:
  363. case <-time.NewTimer(time.Second).C:
  364. t.Error("interval reset timeout")
  365. }
  366. w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8}
  367. select {
  368. case <-progress:
  369. case <-time.NewTimer(time.Second).C:
  370. t.Error("interval reset timeout")
  371. }
  372. w.resubmitAdjustCh <- &intervalAdjust{inc: false}
  373. select {
  374. case <-progress:
  375. case <-time.NewTimer(time.Second).C:
  376. t.Error("interval reset timeout")
  377. }
  378. w.setRecommitInterval(500 * time.Millisecond)
  379. select {
  380. case <-progress:
  381. case <-time.NewTimer(time.Second).C:
  382. t.Error("interval reset timeout")
  383. }
  384. }