worker_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. "math/rand"
  20. "sync/atomic"
  21. "testing"
  22. "time"
  23. "github.com/ethereum/go-ethereum/accounts"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/consensus"
  26. "github.com/ethereum/go-ethereum/consensus/clique"
  27. "github.com/ethereum/go-ethereum/consensus/ethash"
  28. "github.com/ethereum/go-ethereum/core"
  29. "github.com/ethereum/go-ethereum/core/rawdb"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/core/vm"
  32. "github.com/ethereum/go-ethereum/crypto"
  33. "github.com/ethereum/go-ethereum/ethdb"
  34. "github.com/ethereum/go-ethereum/event"
  35. "github.com/ethereum/go-ethereum/params"
  36. )
  37. const (
  38. // testCode is the testing contract binary code which will initialises some
  39. // variables in constructor
  40. testCode = "0x60806040527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0060005534801561003457600080fd5b5060fc806100436000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80630c4dae8814603757806398a213cf146053575b600080fd5b603d607e565b6040518082815260200191505060405180910390f35b607c60048036036020811015606757600080fd5b81019080803590602001909291905050506084565b005b60005481565b806000819055507fe9e44f9f7da8c559de847a3232b57364adc0354f15a2cd8dc636d54396f9587a6000546040518082815260200191505060405180910390a15056fea265627a7a723058208ae31d9424f2d0bc2a3da1a5dd659db2d71ec322a17db8f87e19e209e3a1ff4a64736f6c634300050a0032"
  41. // testGas is the gas required for contract deployment.
  42. testGas = 144109
  43. )
  44. var (
  45. // Test chain configurations
  46. testTxPoolConfig core.TxPoolConfig
  47. ethashChainConfig *params.ChainConfig
  48. cliqueChainConfig *params.ChainConfig
  49. // Test accounts
  50. testBankKey, _ = crypto.GenerateKey()
  51. testBankAddress = crypto.PubkeyToAddress(testBankKey.PublicKey)
  52. testBankFunds = big.NewInt(1000000000000000000)
  53. testUserKey, _ = crypto.GenerateKey()
  54. testUserAddress = crypto.PubkeyToAddress(testUserKey.PublicKey)
  55. // Test transactions
  56. pendingTxs []*types.Transaction
  57. newTxs []*types.Transaction
  58. testConfig = &Config{
  59. Recommit: time.Second,
  60. GasFloor: params.GenesisGasLimit,
  61. GasCeil: params.GenesisGasLimit,
  62. }
  63. )
  64. func init() {
  65. testTxPoolConfig = core.DefaultTxPoolConfig
  66. testTxPoolConfig.Journal = ""
  67. ethashChainConfig = params.TestChainConfig
  68. cliqueChainConfig = params.TestChainConfig
  69. cliqueChainConfig.Clique = &params.CliqueConfig{
  70. Period: 10,
  71. Epoch: 30000,
  72. }
  73. signer := types.LatestSigner(params.TestChainConfig)
  74. tx1 := types.MustSignNewTx(testBankKey, signer, &types.AccessListTx{
  75. ChainID: params.TestChainConfig.ChainID,
  76. Nonce: 0,
  77. To: &testUserAddress,
  78. Value: big.NewInt(1000),
  79. Gas: params.TxGas,
  80. })
  81. pendingTxs = append(pendingTxs, tx1)
  82. tx2 := types.MustSignNewTx(testBankKey, signer, &types.LegacyTx{
  83. Nonce: 1,
  84. To: &testUserAddress,
  85. Value: big.NewInt(1000),
  86. Gas: params.TxGas,
  87. })
  88. newTxs = append(newTxs, tx2)
  89. rand.Seed(time.Now().UnixNano())
  90. }
  91. // testWorkerBackend implements worker.Backend interfaces and wraps all information needed during the testing.
  92. type testWorkerBackend struct {
  93. db ethdb.Database
  94. txPool *core.TxPool
  95. chain *core.BlockChain
  96. testTxFeed event.Feed
  97. genesis *core.Genesis
  98. uncleBlock *types.Block
  99. }
  100. func newTestWorkerBackend(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, n int) *testWorkerBackend {
  101. var gspec = core.Genesis{
  102. Config: chainConfig,
  103. Alloc: core.GenesisAlloc{testBankAddress: {Balance: testBankFunds}},
  104. }
  105. switch e := engine.(type) {
  106. case *clique.Clique:
  107. gspec.ExtraData = make([]byte, 32+common.AddressLength+crypto.SignatureLength)
  108. copy(gspec.ExtraData[32:32+common.AddressLength], testBankAddress.Bytes())
  109. e.Authorize(testBankAddress, func(account accounts.Account, s string, data []byte) ([]byte, error) {
  110. return crypto.Sign(crypto.Keccak256(data), testBankKey)
  111. })
  112. case *ethash.Ethash:
  113. default:
  114. t.Fatalf("unexpected consensus engine type: %T", engine)
  115. }
  116. genesis := gspec.MustCommit(db)
  117. chain, _ := core.NewBlockChain(db, &core.CacheConfig{TrieDirtyDisabled: true}, gspec.Config, engine, vm.Config{}, nil, nil)
  118. txpool := core.NewTxPool(testTxPoolConfig, chainConfig, chain)
  119. // Generate a small n-block chain and an uncle block for it
  120. if n > 0 {
  121. blocks, _ := core.GenerateChain(chainConfig, genesis, engine, db, n, func(i int, gen *core.BlockGen) {
  122. gen.SetCoinbase(testBankAddress)
  123. })
  124. if _, err := chain.InsertChain(blocks); err != nil {
  125. t.Fatalf("failed to insert origin chain: %v", err)
  126. }
  127. }
  128. parent := genesis
  129. if n > 0 {
  130. parent = chain.GetBlockByHash(chain.CurrentBlock().ParentHash())
  131. }
  132. blocks, _ := core.GenerateChain(chainConfig, parent, engine, db, 1, func(i int, gen *core.BlockGen) {
  133. gen.SetCoinbase(testUserAddress)
  134. })
  135. return &testWorkerBackend{
  136. db: db,
  137. chain: chain,
  138. txPool: txpool,
  139. genesis: &gspec,
  140. uncleBlock: blocks[0],
  141. }
  142. }
  143. func (b *testWorkerBackend) BlockChain() *core.BlockChain { return b.chain }
  144. func (b *testWorkerBackend) TxPool() *core.TxPool { return b.txPool }
  145. func (b *testWorkerBackend) newRandomUncle() *types.Block {
  146. var parent *types.Block
  147. cur := b.chain.CurrentBlock()
  148. if cur.NumberU64() == 0 {
  149. parent = b.chain.Genesis()
  150. } else {
  151. parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash())
  152. }
  153. blocks, _ := core.GenerateChain(b.chain.Config(), parent, b.chain.Engine(), b.db, 1, func(i int, gen *core.BlockGen) {
  154. var addr = make([]byte, common.AddressLength)
  155. rand.Read(addr)
  156. gen.SetCoinbase(common.BytesToAddress(addr))
  157. })
  158. return blocks[0]
  159. }
  160. func (b *testWorkerBackend) newRandomTx(creation bool) *types.Transaction {
  161. var tx *types.Transaction
  162. if creation {
  163. tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(testBankAddress), big.NewInt(0), testGas, nil, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey)
  164. } else {
  165. tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(testBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, nil, nil), types.HomesteadSigner{}, testBankKey)
  166. }
  167. return tx
  168. }
  169. func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int) (*worker, *testWorkerBackend) {
  170. backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks)
  171. backend.txPool.AddLocals(pendingTxs)
  172. w := newWorker(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false)
  173. w.setEtherbase(testBankAddress)
  174. return w, backend
  175. }
  176. func TestGenerateBlockAndImportEthash(t *testing.T) {
  177. testGenerateBlockAndImport(t, false)
  178. }
  179. func TestGenerateBlockAndImportClique(t *testing.T) {
  180. testGenerateBlockAndImport(t, true)
  181. }
  182. func testGenerateBlockAndImport(t *testing.T, isClique bool) {
  183. var (
  184. engine consensus.Engine
  185. chainConfig *params.ChainConfig
  186. db = rawdb.NewMemoryDatabase()
  187. )
  188. if isClique {
  189. chainConfig = params.AllCliqueProtocolChanges
  190. chainConfig.Clique = &params.CliqueConfig{Period: 1, Epoch: 30000}
  191. engine = clique.New(chainConfig.Clique, db)
  192. } else {
  193. chainConfig = params.AllEthashProtocolChanges
  194. engine = ethash.NewFaker()
  195. }
  196. w, b := newTestWorker(t, chainConfig, engine, db, 0)
  197. defer w.close()
  198. // This test chain imports the mined blocks.
  199. db2 := rawdb.NewMemoryDatabase()
  200. b.genesis.MustCommit(db2)
  201. chain, _ := core.NewBlockChain(db2, nil, b.chain.Config(), engine, vm.Config{}, nil, nil)
  202. defer chain.Stop()
  203. // Ignore empty commit here for less noise.
  204. w.skipSealHook = func(task *task) bool {
  205. return len(task.receipts) == 0
  206. }
  207. // Wait for mined blocks.
  208. sub := w.mux.Subscribe(core.NewMinedBlockEvent{})
  209. defer sub.Unsubscribe()
  210. // Start mining!
  211. w.start()
  212. for i := 0; i < 5; i++ {
  213. b.txPool.AddLocal(b.newRandomTx(true))
  214. b.txPool.AddLocal(b.newRandomTx(false))
  215. w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()})
  216. w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()})
  217. select {
  218. case ev := <-sub.Chan():
  219. block := ev.Data.(core.NewMinedBlockEvent).Block
  220. if _, err := chain.InsertChain([]*types.Block{block}); err != nil {
  221. t.Fatalf("failed to insert new mined block %d: %v", block.NumberU64(), err)
  222. }
  223. case <-time.After(3 * time.Second): // Worker needs 1s to include new changes.
  224. t.Fatalf("timeout")
  225. }
  226. }
  227. }
  228. func TestEmptyWorkEthash(t *testing.T) {
  229. testEmptyWork(t, ethashChainConfig, ethash.NewFaker())
  230. }
  231. func TestEmptyWorkClique(t *testing.T) {
  232. testEmptyWork(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  233. }
  234. func testEmptyWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  235. defer engine.Close()
  236. w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  237. defer w.close()
  238. var (
  239. taskIndex int
  240. taskCh = make(chan struct{}, 2)
  241. )
  242. checkEqual := func(t *testing.T, task *task, index int) {
  243. // The first empty work without any txs included
  244. receiptLen, balance := 0, big.NewInt(0)
  245. if index == 1 {
  246. // The second full work with 1 tx included
  247. receiptLen, balance = 1, big.NewInt(1000)
  248. }
  249. if len(task.receipts) != receiptLen {
  250. t.Fatalf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
  251. }
  252. if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
  253. t.Fatalf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
  254. }
  255. }
  256. w.newTaskHook = func(task *task) {
  257. if task.block.NumberU64() == 1 {
  258. checkEqual(t, task, taskIndex)
  259. taskIndex += 1
  260. taskCh <- struct{}{}
  261. }
  262. }
  263. w.skipSealHook = func(task *task) bool { return true }
  264. w.fullTaskHook = func() {
  265. time.Sleep(100 * time.Millisecond)
  266. }
  267. w.start() // Start mining!
  268. for i := 0; i < 2; i += 1 {
  269. select {
  270. case <-taskCh:
  271. case <-time.NewTimer(3 * time.Second).C:
  272. t.Error("new task timeout")
  273. }
  274. }
  275. }
  276. func TestStreamUncleBlock(t *testing.T) {
  277. ethash := ethash.NewFaker()
  278. defer ethash.Close()
  279. w, b := newTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1)
  280. defer w.close()
  281. var taskCh = make(chan struct{})
  282. taskIndex := 0
  283. w.newTaskHook = func(task *task) {
  284. if task.block.NumberU64() == 2 {
  285. // The first task is an empty task, the second
  286. // one has 1 pending tx, the third one has 1 tx
  287. // and 1 uncle.
  288. if taskIndex == 2 {
  289. have := task.block.Header().UncleHash
  290. want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()})
  291. if have != want {
  292. t.Errorf("uncle hash mismatch: have %s, want %s", have.Hex(), want.Hex())
  293. }
  294. }
  295. taskCh <- struct{}{}
  296. taskIndex += 1
  297. }
  298. }
  299. w.skipSealHook = func(task *task) bool {
  300. return true
  301. }
  302. w.fullTaskHook = func() {
  303. time.Sleep(100 * time.Millisecond)
  304. }
  305. w.start()
  306. for i := 0; i < 2; i += 1 {
  307. select {
  308. case <-taskCh:
  309. case <-time.NewTimer(time.Second).C:
  310. t.Error("new task timeout")
  311. }
  312. }
  313. w.postSideBlock(core.ChainSideEvent{Block: b.uncleBlock})
  314. select {
  315. case <-taskCh:
  316. case <-time.NewTimer(time.Second).C:
  317. t.Error("new task timeout")
  318. }
  319. }
  320. func TestRegenerateMiningBlockEthash(t *testing.T) {
  321. testRegenerateMiningBlock(t, ethashChainConfig, ethash.NewFaker())
  322. }
  323. func TestRegenerateMiningBlockClique(t *testing.T) {
  324. testRegenerateMiningBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  325. }
  326. func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  327. defer engine.Close()
  328. w, b := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  329. defer w.close()
  330. var taskCh = make(chan struct{})
  331. taskIndex := 0
  332. w.newTaskHook = func(task *task) {
  333. if task.block.NumberU64() == 1 {
  334. // The first task is an empty task, the second
  335. // one has 1 pending tx, the third one has 2 txs
  336. if taskIndex == 2 {
  337. receiptLen, balance := 2, big.NewInt(2000)
  338. if len(task.receipts) != receiptLen {
  339. t.Errorf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
  340. }
  341. if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
  342. t.Errorf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
  343. }
  344. }
  345. taskCh <- struct{}{}
  346. taskIndex += 1
  347. }
  348. }
  349. w.skipSealHook = func(task *task) bool {
  350. return true
  351. }
  352. w.fullTaskHook = func() {
  353. time.Sleep(100 * time.Millisecond)
  354. }
  355. w.start()
  356. // Ignore the first two works
  357. for i := 0; i < 2; i += 1 {
  358. select {
  359. case <-taskCh:
  360. case <-time.NewTimer(time.Second).C:
  361. t.Error("new task timeout")
  362. }
  363. }
  364. b.txPool.AddLocals(newTxs)
  365. time.Sleep(time.Second)
  366. select {
  367. case <-taskCh:
  368. case <-time.NewTimer(time.Second).C:
  369. t.Error("new task timeout")
  370. }
  371. }
  372. func TestAdjustIntervalEthash(t *testing.T) {
  373. testAdjustInterval(t, ethashChainConfig, ethash.NewFaker())
  374. }
  375. func TestAdjustIntervalClique(t *testing.T) {
  376. testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  377. }
  378. func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  379. defer engine.Close()
  380. w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  381. defer w.close()
  382. w.skipSealHook = func(task *task) bool {
  383. return true
  384. }
  385. w.fullTaskHook = func() {
  386. time.Sleep(100 * time.Millisecond)
  387. }
  388. var (
  389. progress = make(chan struct{}, 10)
  390. result = make([]float64, 0, 10)
  391. index = 0
  392. start uint32
  393. )
  394. w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) {
  395. // Short circuit if interval checking hasn't started.
  396. if atomic.LoadUint32(&start) == 0 {
  397. return
  398. }
  399. var wantMinInterval, wantRecommitInterval time.Duration
  400. switch index {
  401. case 0:
  402. wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second
  403. case 1:
  404. origin := float64(3 * time.Second.Nanoseconds())
  405. estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias)
  406. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
  407. case 2:
  408. estimate := result[index-1]
  409. min := float64(3 * time.Second.Nanoseconds())
  410. estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias)
  411. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
  412. case 3:
  413. wantMinInterval, wantRecommitInterval = time.Second, time.Second
  414. }
  415. // Check interval
  416. if minInterval != wantMinInterval {
  417. t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval)
  418. }
  419. if recommitInterval != wantRecommitInterval {
  420. t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval)
  421. }
  422. result = append(result, float64(recommitInterval.Nanoseconds()))
  423. index += 1
  424. progress <- struct{}{}
  425. }
  426. w.start()
  427. time.Sleep(time.Second) // Ensure two tasks have been summitted due to start opt
  428. atomic.StoreUint32(&start, 1)
  429. w.setRecommitInterval(3 * time.Second)
  430. select {
  431. case <-progress:
  432. case <-time.NewTimer(time.Second).C:
  433. t.Error("interval reset timeout")
  434. }
  435. w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8}
  436. select {
  437. case <-progress:
  438. case <-time.NewTimer(time.Second).C:
  439. t.Error("interval reset timeout")
  440. }
  441. w.resubmitAdjustCh <- &intervalAdjust{inc: false}
  442. select {
  443. case <-progress:
  444. case <-time.NewTimer(time.Second).C:
  445. t.Error("interval reset timeout")
  446. }
  447. w.setRecommitInterval(500 * time.Millisecond)
  448. select {
  449. case <-progress:
  450. case <-time.NewTimer(time.Second).C:
  451. t.Error("interval reset timeout")
  452. }
  453. }