gitee.com/liu-zhao234568/cntest@v1.0.0/miner/worker_test.go (about)

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