worker_test.go 13 KB

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