worker_test.go 16 KB

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