worker_test.go 13 KB

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