worker_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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) PostChainEvents(events []interface{}) {
  135. b.chain.PostChainEvents(events, nil)
  136. }
  137. func (b *testWorkerBackend) newRandomUncle() *types.Block {
  138. var parent *types.Block
  139. cur := b.chain.CurrentBlock()
  140. if cur.NumberU64() == 0 {
  141. parent = b.chain.Genesis()
  142. } else {
  143. parent = b.chain.GetBlockByHash(b.chain.CurrentBlock().ParentHash())
  144. }
  145. blocks, _ := core.GenerateChain(b.chain.Config(), parent, b.chain.Engine(), b.db, 1, func(i int, gen *core.BlockGen) {
  146. var addr = make([]byte, common.AddressLength)
  147. rand.Read(addr)
  148. gen.SetCoinbase(common.BytesToAddress(addr))
  149. })
  150. return blocks[0]
  151. }
  152. func (b *testWorkerBackend) newRandomTx(creation bool) *types.Transaction {
  153. var tx *types.Transaction
  154. if creation {
  155. tx, _ = types.SignTx(types.NewContractCreation(b.txPool.Nonce(testBankAddress), big.NewInt(0), testGas, nil, common.FromHex(testCode)), types.HomesteadSigner{}, testBankKey)
  156. } else {
  157. tx, _ = types.SignTx(types.NewTransaction(b.txPool.Nonce(testBankAddress), testUserAddress, big.NewInt(1000), params.TxGas, nil, nil), types.HomesteadSigner{}, testBankKey)
  158. }
  159. return tx
  160. }
  161. func newTestWorker(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine, db ethdb.Database, blocks int) (*worker, *testWorkerBackend) {
  162. backend := newTestWorkerBackend(t, chainConfig, engine, db, blocks)
  163. backend.txPool.AddLocals(pendingTxs)
  164. w := newWorker(testConfig, chainConfig, engine, backend, new(event.TypeMux), nil, false)
  165. w.setEtherbase(testBankAddress)
  166. return w, backend
  167. }
  168. func TestGenerateBlockAndImportEthash(t *testing.T) {
  169. testGenerateBlockAndImport(t, false)
  170. }
  171. func TestGenerateBlockAndImportClique(t *testing.T) {
  172. testGenerateBlockAndImport(t, true)
  173. }
  174. func testGenerateBlockAndImport(t *testing.T, isClique bool) {
  175. var (
  176. engine consensus.Engine
  177. chainConfig *params.ChainConfig
  178. db = rawdb.NewMemoryDatabase()
  179. )
  180. if isClique {
  181. chainConfig = params.AllCliqueProtocolChanges
  182. chainConfig.Clique = &params.CliqueConfig{Period: 1, Epoch: 30000}
  183. engine = clique.New(chainConfig.Clique, db)
  184. } else {
  185. chainConfig = params.AllEthashProtocolChanges
  186. engine = ethash.NewFaker()
  187. }
  188. w, b := newTestWorker(t, chainConfig, engine, db, 0)
  189. defer w.close()
  190. db2 := rawdb.NewMemoryDatabase()
  191. b.genesis.MustCommit(db2)
  192. chain, _ := core.NewBlockChain(db2, nil, b.chain.Config(), engine, vm.Config{}, nil)
  193. defer chain.Stop()
  194. loopErr := make(chan error)
  195. newBlock := make(chan struct{})
  196. listenNewBlock := func() {
  197. sub := w.mux.Subscribe(core.NewMinedBlockEvent{})
  198. defer sub.Unsubscribe()
  199. for item := range sub.Chan() {
  200. block := item.Data.(core.NewMinedBlockEvent).Block
  201. _, err := chain.InsertChain([]*types.Block{block})
  202. if err != nil {
  203. loopErr <- fmt.Errorf("failed to insert new mined block:%d, error:%v", block.NumberU64(), err)
  204. }
  205. newBlock <- struct{}{}
  206. }
  207. }
  208. // Ignore empty commit here for less noise
  209. w.skipSealHook = func(task *task) bool {
  210. return len(task.receipts) == 0
  211. }
  212. w.start() // Start mining!
  213. go listenNewBlock()
  214. for i := 0; i < 5; i++ {
  215. b.txPool.AddLocal(b.newRandomTx(true))
  216. b.txPool.AddLocal(b.newRandomTx(false))
  217. b.PostChainEvents([]interface{}{core.ChainSideEvent{Block: b.newRandomUncle()}})
  218. b.PostChainEvents([]interface{}{core.ChainSideEvent{Block: b.newRandomUncle()}})
  219. select {
  220. case e := <-loopErr:
  221. t.Fatal(e)
  222. case <-newBlock:
  223. case <-time.NewTimer(3 * time.Second).C: // 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. // Aarch64 unit tests are running in a VM on travis, they must
  266. // be given more time to execute.
  267. time.Sleep(time.Second)
  268. }
  269. w.start() // Start mining!
  270. for i := 0; i < 2; i += 1 {
  271. select {
  272. case <-taskCh:
  273. case <-time.NewTimer(3 * time.Second).C:
  274. t.Error("new task timeout")
  275. }
  276. }
  277. }
  278. func TestStreamUncleBlock(t *testing.T) {
  279. ethash := ethash.NewFaker()
  280. defer ethash.Close()
  281. w, b := newTestWorker(t, ethashChainConfig, ethash, rawdb.NewMemoryDatabase(), 1)
  282. defer w.close()
  283. var taskCh = make(chan struct{})
  284. taskIndex := 0
  285. w.newTaskHook = func(task *task) {
  286. if task.block.NumberU64() == 2 {
  287. // The first task is an empty task, the second
  288. // one has 1 pending tx, the third one has 1 tx
  289. // and 1 uncle.
  290. if taskIndex == 2 {
  291. have := task.block.Header().UncleHash
  292. want := types.CalcUncleHash([]*types.Header{b.uncleBlock.Header()})
  293. if have != want {
  294. t.Errorf("uncle hash mismatch: have %s, want %s", have.Hex(), want.Hex())
  295. }
  296. }
  297. taskCh <- struct{}{}
  298. taskIndex += 1
  299. }
  300. }
  301. w.skipSealHook = func(task *task) bool {
  302. return true
  303. }
  304. w.fullTaskHook = func() {
  305. time.Sleep(100 * time.Millisecond)
  306. }
  307. w.start()
  308. for i := 0; i < 2; i += 1 {
  309. select {
  310. case <-taskCh:
  311. case <-time.NewTimer(time.Second).C:
  312. t.Error("new task timeout")
  313. }
  314. }
  315. b.PostChainEvents([]interface{}{core.ChainSideEvent{Block: b.uncleBlock}})
  316. select {
  317. case <-taskCh:
  318. case <-time.NewTimer(time.Second).C:
  319. t.Error("new task timeout")
  320. }
  321. }
  322. func TestRegenerateMiningBlockEthash(t *testing.T) {
  323. testRegenerateMiningBlock(t, ethashChainConfig, ethash.NewFaker())
  324. }
  325. func TestRegenerateMiningBlockClique(t *testing.T) {
  326. testRegenerateMiningBlock(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  327. }
  328. func testRegenerateMiningBlock(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  329. defer engine.Close()
  330. w, b := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  331. defer w.close()
  332. var taskCh = make(chan struct{})
  333. taskIndex := 0
  334. w.newTaskHook = func(task *task) {
  335. if task.block.NumberU64() == 1 {
  336. // The first task is an empty task, the second
  337. // one has 1 pending tx, the third one has 2 txs
  338. if taskIndex == 2 {
  339. receiptLen, balance := 2, big.NewInt(2000)
  340. if len(task.receipts) != receiptLen {
  341. t.Errorf("receipt number mismatch: have %d, want %d", len(task.receipts), receiptLen)
  342. }
  343. if task.state.GetBalance(testUserAddress).Cmp(balance) != 0 {
  344. t.Errorf("account balance mismatch: have %d, want %d", task.state.GetBalance(testUserAddress), balance)
  345. }
  346. }
  347. taskCh <- struct{}{}
  348. taskIndex += 1
  349. }
  350. }
  351. w.skipSealHook = func(task *task) bool {
  352. return true
  353. }
  354. w.fullTaskHook = func() {
  355. time.Sleep(100 * time.Millisecond)
  356. }
  357. w.start()
  358. // Ignore the first two works
  359. for i := 0; i < 2; i += 1 {
  360. select {
  361. case <-taskCh:
  362. case <-time.NewTimer(time.Second).C:
  363. t.Error("new task timeout")
  364. }
  365. }
  366. b.txPool.AddLocals(newTxs)
  367. time.Sleep(time.Second)
  368. select {
  369. case <-taskCh:
  370. case <-time.NewTimer(time.Second).C:
  371. t.Error("new task timeout")
  372. }
  373. }
  374. func TestAdjustIntervalEthash(t *testing.T) {
  375. testAdjustInterval(t, ethashChainConfig, ethash.NewFaker())
  376. }
  377. func TestAdjustIntervalClique(t *testing.T) {
  378. testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  379. }
  380. func testAdjustInterval(t *testing.T, chainConfig *params.ChainConfig, engine consensus.Engine) {
  381. defer engine.Close()
  382. w, _ := newTestWorker(t, chainConfig, engine, rawdb.NewMemoryDatabase(), 0)
  383. defer w.close()
  384. w.skipSealHook = func(task *task) bool {
  385. return true
  386. }
  387. w.fullTaskHook = func() {
  388. time.Sleep(100 * time.Millisecond)
  389. }
  390. var (
  391. progress = make(chan struct{}, 10)
  392. result = make([]float64, 0, 10)
  393. index = 0
  394. start uint32
  395. )
  396. w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) {
  397. // Short circuit if interval checking hasn't started.
  398. if atomic.LoadUint32(&start) == 0 {
  399. return
  400. }
  401. var wantMinInterval, wantRecommitInterval time.Duration
  402. switch index {
  403. case 0:
  404. wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second
  405. case 1:
  406. origin := float64(3 * time.Second.Nanoseconds())
  407. estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias)
  408. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
  409. case 2:
  410. estimate := result[index-1]
  411. min := float64(3 * time.Second.Nanoseconds())
  412. estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias)
  413. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
  414. case 3:
  415. wantMinInterval, wantRecommitInterval = time.Second, time.Second
  416. }
  417. // Check interval
  418. if minInterval != wantMinInterval {
  419. t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval)
  420. }
  421. if recommitInterval != wantRecommitInterval {
  422. t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval)
  423. }
  424. result = append(result, float64(recommitInterval.Nanoseconds()))
  425. index += 1
  426. progress <- struct{}{}
  427. }
  428. w.start()
  429. time.Sleep(time.Second) // Ensure two tasks have been summitted due to start opt
  430. atomic.StoreUint32(&start, 1)
  431. w.setRecommitInterval(3 * time.Second)
  432. select {
  433. case <-progress:
  434. case <-time.NewTimer(time.Second).C:
  435. t.Error("interval reset timeout")
  436. }
  437. w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8}
  438. select {
  439. case <-progress:
  440. case <-time.NewTimer(time.Second).C:
  441. t.Error("interval reset timeout")
  442. }
  443. w.resubmitAdjustCh <- &intervalAdjust{inc: false}
  444. select {
  445. case <-progress:
  446. case <-time.NewTimer(time.Second).C:
  447. t.Error("interval reset timeout")
  448. }
  449. w.setRecommitInterval(500 * time.Millisecond)
  450. select {
  451. case <-progress:
  452. case <-time.NewTimer(time.Second).C:
  453. t.Error("interval reset timeout")
  454. }
  455. }