worker_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 TestAdjustIntervalEthash(t *testing.T) {
  229. testAdjustInterval(t, ethashChainConfig, ethash.NewFaker())
  230. }
  231. func TestAdjustIntervalClique(t *testing.T) {
  232. testAdjustInterval(t, cliqueChainConfig, clique.New(cliqueChainConfig.Clique, rawdb.NewMemoryDatabase()))
  233. }
  234. func testAdjustInterval(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. w.skipSealHook = func(task *task) bool {
  239. return true
  240. }
  241. w.fullTaskHook = func() {
  242. time.Sleep(100 * time.Millisecond)
  243. }
  244. var (
  245. progress = make(chan struct{}, 10)
  246. result = make([]float64, 0, 10)
  247. index = 0
  248. start uint32
  249. )
  250. w.resubmitHook = func(minInterval time.Duration, recommitInterval time.Duration) {
  251. // Short circuit if interval checking hasn't started.
  252. if atomic.LoadUint32(&start) == 0 {
  253. return
  254. }
  255. var wantMinInterval, wantRecommitInterval time.Duration
  256. switch index {
  257. case 0:
  258. wantMinInterval, wantRecommitInterval = 3*time.Second, 3*time.Second
  259. case 1:
  260. origin := float64(3 * time.Second.Nanoseconds())
  261. estimate := origin*(1-intervalAdjustRatio) + intervalAdjustRatio*(origin/0.8+intervalAdjustBias)
  262. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
  263. case 2:
  264. estimate := result[index-1]
  265. min := float64(3 * time.Second.Nanoseconds())
  266. estimate = estimate*(1-intervalAdjustRatio) + intervalAdjustRatio*(min-intervalAdjustBias)
  267. wantMinInterval, wantRecommitInterval = 3*time.Second, time.Duration(estimate)*time.Nanosecond
  268. case 3:
  269. wantMinInterval, wantRecommitInterval = time.Second, time.Second
  270. }
  271. // Check interval
  272. if minInterval != wantMinInterval {
  273. t.Errorf("resubmit min interval mismatch: have %v, want %v ", minInterval, wantMinInterval)
  274. }
  275. if recommitInterval != wantRecommitInterval {
  276. t.Errorf("resubmit interval mismatch: have %v, want %v", recommitInterval, wantRecommitInterval)
  277. }
  278. result = append(result, float64(recommitInterval.Nanoseconds()))
  279. index += 1
  280. progress <- struct{}{}
  281. }
  282. w.start()
  283. time.Sleep(time.Second) // Ensure two tasks have been summitted due to start opt
  284. atomic.StoreUint32(&start, 1)
  285. w.setRecommitInterval(3 * time.Second)
  286. select {
  287. case <-progress:
  288. case <-time.NewTimer(time.Second).C:
  289. t.Error("interval reset timeout")
  290. }
  291. w.resubmitAdjustCh <- &intervalAdjust{inc: true, ratio: 0.8}
  292. select {
  293. case <-progress:
  294. case <-time.NewTimer(time.Second).C:
  295. t.Error("interval reset timeout")
  296. }
  297. w.resubmitAdjustCh <- &intervalAdjust{inc: false}
  298. select {
  299. case <-progress:
  300. case <-time.NewTimer(time.Second).C:
  301. t.Error("interval reset timeout")
  302. }
  303. w.setRecommitInterval(500 * time.Millisecond)
  304. select {
  305. case <-progress:
  306. case <-time.NewTimer(time.Second).C:
  307. t.Error("interval reset timeout")
  308. }
  309. }