worker_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. loopErr := make(chan error)
  192. newBlock := make(chan struct{})
  193. listenNewBlock := func() {
  194. sub := w.mux.Subscribe(core.NewMinedBlockEvent{})
  195. defer sub.Unsubscribe()
  196. for item := range sub.Chan() {
  197. block := item.Data.(core.NewMinedBlockEvent).Block
  198. _, err := chain.InsertChain([]*types.Block{block})
  199. if err != nil {
  200. loopErr <- fmt.Errorf("failed to insert new mined block:%d, error:%v", block.NumberU64(), err)
  201. }
  202. newBlock <- struct{}{}
  203. }
  204. }
  205. // Ignore empty commit here for less noise
  206. w.skipSealHook = func(task *task) bool {
  207. return len(task.receipts) == 0
  208. }
  209. w.start() // Start mining!
  210. go listenNewBlock()
  211. for i := 0; i < 5; i++ {
  212. b.txPool.AddLocal(b.newRandomTx(true))
  213. b.txPool.AddLocal(b.newRandomTx(false))
  214. w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()})
  215. w.postSideBlock(core.ChainSideEvent{Block: b.newRandomUncle()})
  216. select {
  217. case e := <-loopErr:
  218. t.Fatal(e)
  219. case <-newBlock:
  220. case <-time.NewTimer(3 * time.Second).C: // Worker needs 1s to include new changes.
  221. t.Fatalf("timeout")
  222. }
  223. }
  224. }
  225. func TestEmptyWorkEthash(t *testing.T) {
  226. testEmptyWork(t, ethashChainConfig, ethash.NewFaker())
  227. }
  228. func TestEmptyWorkClique(t *testing.T) {
  229. testEmptyWork(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  230. }
  231. func testEmptyWork(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  232. defer engine.Close()
  233. w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  234. defer w.close()
  235. var (
  236. taskIndex int
  237. taskCh = make(chan struct{}, 2)
  238. )
  239. checkEqual := func(t *testing.T, task *task, index int) {
  240. // The first empty work without any txs included
  241. receiptLen, balance := 0, big.NewInt(0)
  242. if index == 1 {
  243. // The second full work with 1 tx included
  244. receiptLen, balance = 1, big.NewInt(1000)
  245. }
  246. if len(task.receipts) != receiptLen {
  247. t.Fatalf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
  248. }
  249. if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
  250. t.Fatalf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
  251. }
  252. }
  253. w.newTaskHook = func(task *task) {
  254. if task.block.NumberU64() == 1 {
  255. checkEqual(t, task, taskIndex)
  256. taskIndex += 1
  257. taskCh <- struct{}{}
  258. }
  259. }
  260. w.skipSealHook = func(task *task) bool { return true }
  261. w.fullTaskHook = func() {
  262. // Arch64 unit tests are running in a VM on travis, they must
  263. // be given more time to execute.
  264. time.Sleep(time.Second)
  265. }
  266. w.start() // Start mining!
  267. for i := 0; i < 2; i += 1 {
  268. select {
  269. case <-taskCh:
  270. case <-time.NewTimer(3 * time.Second).C:
  271. t.Error("new task timeout")
  272. }
  273. }
  274. }
  275. func TestStreamUncleBlock(t *testing.T) {
  276. ethash := ethash.NewFaker()
  277. defer ethash.Close()
  278. w, b := newTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1)
  279. defer w.close()
  280. var taskCh = make(chan struct{})
  281. taskIndex := 0
  282. w.newTaskHook = func(task *task) {
  283. if task.block.NumberU64() == 2 {
  284. // The first task is an empty task, the second
  285. // one has 1 pending tx, the third one has 1 tx
  286. // and 1 uncle.
  287. if taskIndex == 2 {
  288. have := task.block.Header().UncleHash
  289. want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()})
  290. if have != want {
  291. t.Errorf("uncle hash mismatch: have %s, want %s", have.Hex(), want.Hex())
  292. }
  293. }
  294. taskCh <- struct{}{}
  295. taskIndex += 1
  296. }
  297. }
  298. w.skipSealHook = func(task *task) bool {
  299. return true
  300. }
  301. w.fullTaskHook = func() {
  302. time.Sleep(100 * time.Millisecond)
  303. }
  304. w.start()
  305. for i := 0; i < 2; i += 1 {
  306. select {
  307. case <-taskCh:
  308. case <-time.NewTimer(time.Second).C:
  309. t.Error("new task timeout")
  310. }
  311. }
  312. w.postSideBlock(core.ChainSideEvent{Block: b.uncleBlock})
  313. select {
  314. case <-taskCh:
  315. case <-time.NewTimer(time.Second).C:
  316. t.Error("new task timeout")
  317. }
  318. }
  319. func TestRegenerateMiningBlockEthash(t *testing.T) {
  320. testRegenerateMiningBlock(t, ethashChainConfig, ethash.NewFaker())
  321. }
  322. func TestRegenerateMiningBlockClique(t *testing.T) {
  323. testRegenerateMiningBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  324. }
  325. func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  326. defer engine.Close()
  327. w, b := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  328. defer w.close()
  329. var taskCh = make(chan struct{})
  330. taskIndex := 0
  331. w.newTaskHook = func(task *task) {
  332. if task.block.NumberU64() == 1 {
  333. // The first task is an empty task, the second
  334. // one has 1 pending tx, the third one has 2 txs
  335. if taskIndex == 2 {
  336. receiptLen, balance := 2, big.NewInt(2000)
  337. if len(task.receipts) != receiptLen {
  338. t.Errorf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
  339. }
  340. if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
  341. t.Errorf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
  342. }
  343. }
  344. taskCh <- struct{}{}
  345. taskIndex += 1
  346. }
  347. }
  348. w.skipSealHook = func(task *task) bool {
  349. return true
  350. }
  351. w.fullTaskHook = func() {
  352. time.Sleep(100 * time.Millisecond)
  353. }
  354. w.start()
  355. // Ignore the first two works
  356. for i := 0; i < 2; i += 1 {
  357. select {
  358. case <-taskCh:
  359. case <-time.NewTimer(time.Second).C:
  360. t.Error("new task timeout")
  361. }
  362. }
  363. b.txPool.AddLocals(newTxs)
  364. time.Sleep(time.Second)
  365. select {
  366. case <-taskCh:
  367. case <-time.NewTimer(time.Second).C:
  368. t.Error("new task timeout")
  369. }
  370. }
  371. func TestAdjustIntervalEthash(t *testing.T) {
  372. testAdjustInterval(t, ethashChainConfig, ethash.NewFaker())
  373. }
  374. func TestAdjustIntervalClique(t *testing.T) {
  375. testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  376. }
  377. func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  378. defer engine.Close()
  379. w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  380. defer w.close()
  381. w.skipSealHook = func(task *task) bool {
  382. return true
  383. }
  384. w.fullTaskHook = func() {
  385. time.Sleep(100 * time.Millisecond)
  386. }
  387. var (
  388. progress = make(chan struct{}, 10)
  389. result = make([]float64, 0, 10)
  390. index = 0
  391. start uint32
  392. )
  393. w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) {
  394. // Short circuit if interval checking hasn't started.
  395. if atomic.LoadUint32(&start) == 0 {
  396. return
  397. }
  398. var wantMinInterval, wantRecommitInterval time.Duration
  399. switch index {
  400. case 0:
  401. wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second
  402. case 1:
  403. origin := float64(3 * time.Second.Nanoseconds())
  404. estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias)
  405. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
  406. case 2:
  407. estimate := result[index-1]
  408. min := float64(3 * time.Second.Nanoseconds())
  409. estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias)
  410. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
  411. case 3:
  412. wantMinInterval, wantRecommitInterval = time.Second, time.Second
  413. }
  414. // Check interval
  415. if minInterval != wantMinInterval {
  416. t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval)
  417. }
  418. if recommitInterval != wantRecommitInterval {
  419. t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval)
  420. }
  421. result = append(result, float64(recommitInterval.Nanoseconds()))
  422. index += 1
  423. progress <- struct{}{}
  424. }
  425. w.start()
  426. time.Sleep(time.Second) // Ensure two tasks have been summitted due to start opt
  427. atomic.StoreUint32(&start, 1)
  428. w.setRecommitInterval(3 * time.Second)
  429. select {
  430. case <-progress:
  431. case <-time.NewTimer(time.Second).C:
  432. t.Error("interval reset timeout")
  433. }
  434. w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8}
  435. select {
  436. case <-progress:
  437. case <-time.NewTimer(time.Second).C:
  438. t.Error("interval reset timeout")
  439. }
  440. w.resubmitAdjustCh <- &intervalAdjust{inc: false}
  441. select {
  442. case <-progress:
  443. case <-time.NewTimer(time.Second).C:
  444. t.Error("interval reset timeout")
  445. }
  446. w.setRecommitInterval(500 * time.Millisecond)
  447. select {
  448. case <-progress:
  449. case <-time.NewTimer(time.Second).C:
  450. t.Error("interval reset timeout")
  451. }
  452. }