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