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